
/**
 * Form validation functions
 */
$.any.ui('forum_form',
{
	_init: function()
	{
		var self = this;
		self.objNotification = $('.comment-form-notification', self.element);
		self.submitTriggers();
	},
	
	/**
	 * Stuff to check on submit
	 */
	submitTriggers: function()
	{
		var self = this, $notificationObj;
		
		// Submit + preview
		$('#comment-form .button-submit-forum, #comment-form .button-preview').click(function()
			{
				r = self.fieldsValid(false);
				if (r !== true)
				{
					return self.handleError(r, false);
				}
				
				// Preview
				if ($(this).hasClass('button-preview'))
				{
					$('#comment-form-element').attr('action', '#comment-preview');
				}
			});
		
		// Flowers (body not required)
		$('#comment-form .button-throw-flower').click(function()
			{
				var flower, image, r;

				r = self.fieldsValid(true);
				if (r !== true)
				{
					return self.handleError(r, true);
				}
			
				flower = Math.ceil(Math.random() * 10);
				flowerField = $('<input type="hidden" name="Forum[image]" value="flower' + flower + '.gif" />');
				
				$('#comment-form-element').append(flowerField);
			});
	},
	
	/**
	 * Show appropriate error message
	 */
	handleError: function(r, flowers)
	{
		var self = this;

		if (r === false && flowers)
		{
			$.any.notification.error('De titel is veplicht', self.objNotification);
		} else if (r === false && !flowers)
		{
			$.any.notification.error('De titel is veplicht', self.objNotification);
		} else if (r == 'email')
		{
			$.any.notification.error('Your email address is not valid', self.objNotification);
		}
		
		return false;
	},
	
	/**
	 * Check if all required fields have data
	 * When a flower is thrown, no body field is required
	 */
	fieldsValid: function(flower)
	{
		var self = this, $guestName, $guestEmail;
		
		if (!$.trim( $('#forum-comment-title').val() ))
		{
			return false;
		}

		// Fail when: body field is empty unless it has a flower
		else if (!$.trim($('#forum-comment-body').val()) && !flower)
		{
			return false;
		}
		
		$guestName	= $('#comment-guest-name');
		$guestEmail	= $('#comment-guest-email');
		
		if ($guestName.length)
		{
			if (!$.trim( $guestName.val() )) { return false; }
			if (!$.trim( $guestEmail.val() )){ return false; }
			if (!$.isEmailAddress( $guestEmail.val() )){ return 'email'; }
		}
		
		return true;
	}
});

/**
 * Comment button widgets
 * All call functions from within the $.any.forum object
 */
$.any.ui('forum_edit_note',
{
	_init: function()
	{
		var self = this;
		$(self.element).click(function()
			{
				$.any.forum.editNote(self.element, self.options.id, self.options.lang);
			});
	}
});

$.any.ui('forum_delete_note',
{
	_init: function()
	{
		var self = this;
		$(self.element).click(function()
			{
				$.any.forum.deleteNote(self.element, self.options.id);
			});
	}
});

if (typeof $.any.ui.action != 'undefined') // lightbox, remove this check if we dont use a lightbox anymore
{
	$.any.ui.action.js('forum_quote', {
		callQuote: function()
		{
			var self = this;
			$.any.dialog.close();
			$.any.forum.quoteNote(self.options.thg_id);
		}
	});
}

/**
 * Submit the preview
 * Allows users to submit without manually scrolling down to the form
 */
$.any.ui('forum_submit_preview', {
	_init: function()
	{
		var self = this;
		$(self.element).click(function()
			{
				$('#comment-form .button-submit-forum:first').click();
			});
	}
});

/**
 * Edit the preview
 */
$.any.ui('forum_edit_preview', {
	_init: function()
	{
		var self = this;
		$(self.element).click(function()
			{
				$.any.forum.scrollToCommentForm(true);
			});
	}
});

/**
 * Static functions wrapper
 */
$.any.forum = {

	/**
	 * Get note DOM element by note id
	 */
	getNoteById: function(id)
	{
		return $('#comment-' + id);
	},
	
	/**
	 * Throbber after button
	 */
	addThrobberAfterObj: function(obj)
	{
		var self = this;
		
		if (typeof self.throbber == 'undefined')
		{
			self.throbber = $('<img src="http://fast.mediamatic.nl/f/lbcb/image/throbberwait.gif" width="16" height="16" class="comment-throbber left" />');
		}
		$(obj).parent().append(self.throbber);
	},

	/**
	 * Edit a note
	 * Get edit note template from database
	 */
	editNote: function(el, id, lang)
	{
		var self = this, data, html, $note;
		
		self.addThrobberAfterObj(el);
	
		// Get fig field
		data = {
			name	: 'forum_note_edit',
			id		: id
		};
		
		$.any.rest.get('anymeta.html.scomp', data, function(json)
			{
				self.editNoteDom(json, id, lang);
			});
	},
	
	/**
	 * Replace title, message field and buttons
	 */
	editNoteDom: function(json, id, lang)
	{
		var self = this, $note, $titleField, $bodyField;
		
		$note = self.getNoteById(id);
		
		$note.find('.comment-content')
			.html(json.html);
			
		init_widgets($note.find('.comment-content'));
		
		$note.find('.edit-comment-save').click(function()
			{
				self.editNoteSave(id, lang);
				self.addThrobberAfterObj(this);
			});

		$note.find('.edit-comment-cancel').click(function()
			{
				self.refreshNote(id);
				self.addThrobberAfterObj(this);
			});
	},
	
	/**
	 * Save note
	 * and refresh dom
	 */
	editNoteSave: function(id, lang)
	{
		var self = this, $note, data, titleVal, bodyVal;

		$note		= self.getNoteById(id);
		titleVal	= $.trim( $note.find('.comment-title').val() );
		bodyVal		= $.trim( $note.find('.comment-body').val() );

		if (!titleVal || !bodyVal)
		{
			$.any.notification.error('Alle velden zijn verplicht', $note.find('.comment-notification'));
			return false;
		}
		
		data = {
			thing_id: id, 
			data	: {
				text	: {
					language	: lang,
					title		: titleVal,
					body		: bodyVal
				}
			}
		};
		
		$.any.rest.post('anymeta.thing.update', data, function(json)
			{
				self.refreshNote(id);
			});
	},
	
	/**
	 * Refresh note
	 */
	refreshNote: function(id)
	{
		var self = this, data, $note;
		
		$note = self.getNoteById(id);
		
		data = {
			name	: 'forum_note',
			id		: id
		};
		
		$.any.rest.get('anymeta.html.scomp', data, function(json)
			{
				$note.replaceWith(json.html);
				$.any.ui.scan(self.getNoteById(id));
			});
	},
	
	/**
	 * Delete a note
	 * Secure delete a comment and remove comment from dom
	 */
	deleteNote: function(el, id)
	{
		var self = this, $note, data, noteTitle, confirmMsg;
		
		$note		= self.getNoteById(id);
		noteTitle	= $note.find('h3').text();
		confirmMsg	= 'Weet u zeker dat u %1% wilt verwijderen ?';
		confirmMsg	= confirmMsg.replace('%1%', noteTitle);
		
		if (confirm(confirmMsg))
		{
			self.addThrobberAfterObj(el);
		
			data = {
				secure		: 1,
				thing_id	: id
			};

			$.any.rest.post('anymeta.things.delete', data, function()
				{
					$note.fadeOut('slow', function()
						{
							$(this).remove();
						});
				});
		}
	},
	
	/**
	 * Quote note
	 */
	quoteNote: function(id)
	{
		var self = this, $note, $formTitleField, $formBodyField, noteTitle, noteBody, noteOwner;
		
		$note = self.getNoteById(id);

		$formTitleField = $('#forum-comment-title').val('');
		$formBodyField  = $('#forum-comment-body').val('');
	
		noteTitle = $.trim( $('.comment-title',  $note).text() );
		noteBody  = $.trim( $('.comment-body',   $note).text() ); // todo: also copy markup
		noteOwner = $.trim( $('.comment-author', $note).text() );

		$formTitleField.val('Re: ' + noteTitle);
		
		if (noteOwner)
		{
			$formBodyField[0].value += '> ' + noteOwner + ':\n';
		}

		$formBodyField[0].value += self.prefixQuoteNote(noteBody) + '\n';
		
		self.scrollToCommentForm(true);
	},
	
	/**
	 * Prefix string with >
	 */
	prefixQuoteNote: function(comment)
	{
		var self = this, prefix, lines, line, quotedComment;
		
		prefix	= '> ';
		quotedComment	= '';
		lines	= comment.split(/\n/);
		
		for ( i = 0; i < lines.length; ++i )
		{
			line = $.trim(lines[i]);
			if (line) 
			{
				quotedComment += prefix + line + '\n';
			}
		}
		
		return quotedComment;
	},
	
	/**
	 * Scroll to comment form
	 * Focus, put caret at end
	 */
	scrollToCommentForm: function(focus)
	{
		var self = this, caretEnd, $forumCommentBody;
		
		$forumCommentBody = $('#forum-comment-body');
		
		$('html,body').stop().animate({scrollTop: $('#comment-form').offset().top}, 1000, 'easeOutQuart');
		
		if (focus)
		{
			caretEnd = $forumCommentBody.val().length;
			$forumCommentBody
				.focus()
				.caret(caretEnd, caretEnd)
				.scrollTop(9999);
		}
	}
};





/**
 * Forum note figure adding
 * OLD BUT STILL IN USE NEEDS CLEANUP
 */
var node = null;
var forumManager = {

	rebuildNoteFig: function(forum_form_react_fig)
	{
		var dom_id 		  = "ForumFormNoteFig";
		var scomp_options = 
			{ 	'name':   					'forum_form_react_fig',
				'forum_form_react_fig': 	forum_form_react_fig
			};
		
			anyRest.html.scomp(scomp_options, function (xml) 
			{
				if (anyRest.aux.error(xml)) 
				{
					jQuery.log(anyRest.aux.errorMsg(xml));
				}
				else
				{
					var ts = xml.getElementsByTagName( 'html' )[0];
					var x = window.parent.document.getElementById( dom_id );
				
					if ( ts && x )
					{
						var v = anyRest.aux.concatChildNodes( ts );
						$( x ).after ( v ).remove();
	
						var y = window.parent.document.getElementById( dom_id );
						window.parent.init_widgets(y);
					}
					else
					{
						jQuery.log('Internal error: did not get a template from the server or no dom id. Sorry...');
					}
					
				}
			}
		);
	},

	rebuildNoteEditFig: function(id)
	{
		setTimeout(function()
		{
		
			var dom_id = "ForumFormNoteEditFig"+id;
			var scomp_options = 
				{ 	'name':   	'forum_note_edit_fig',
					'id':	  	id
				};
			
				anyRest.html.scomp(scomp_options, function (xml) 
				{
					if (anyRest.aux.error(xml)) 
					{
						jQuery.log(anyRest.aux.errorMsg(xml));
					}
					else
					{
						var ts = xml.getElementsByTagName( 'html' )[0];
						var x = window.parent.document.getElementById( dom_id );
					
						if ( ts && x )
						{
							var v = anyRest.aux.concatChildNodes( ts );
							$( x ).after ( v ).remove();
		
							var y = window.parent.document.getElementById( dom_id );
							window.parent.init_widgets(y);
						}
						else
						{
							jQuery.log('Internal error: did not get a template from the server or no dom id. Sorry...');
						}
						
					}
				}
			);
		
		}, 100);
	}
};

//