/*
 * 	Little bit of javascript to hook into HTML elements that have a class of 'TinyMCE-capable'.
 *
 * 	The calling web page must have the TinyMCE jQuery plugin loaded.
 */

$(function() {
	//
	//	Constants
	//
	var Y_OFFSET = 5;
	var X_OFFSET = 5;

	//
	//	The TinyMCE initialisation parameter block.
	//
	var TinyMCE_Params = {
		script_url : '/includes/js/tinymce/jscripts/tiny_mce/tiny_mce.js',		//	This is used by the jQuery TinyMCE plugin to load up the standard TinyMCE library.

		theme : "advanced",
		plugins : "safari,pagebreak,inlinepopups,preview,searchreplace,print,paste,directionality,fullscreen,visualchars,nonbreaking,table,imagemanager",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,sub,sup,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,formatselect,|,forecolor,backcolor,|,removeformat",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,link,unlink,anchor,image,hr,nonbreaking,pagebreak,charmap,|,print,preview,code,cleanup,help",
		theme_advanced_buttons3 : "tablecontrols,|,fullscreen",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		forced_root_block : false,
		force_p_newlines : false,
		remove_linebreaks : false,
		force_br_newlines : true,
		remove_trailing_nbsp : false,   
		verify_html : false
		};
	
	//
	//	Return the ID we'll use for the hidden version number, based off the ID of the div being edited.
	//
	function get_version_number_id (div_id) {
		return (div_id + '-VERSION_NUMBER');
		}

	//
	//	Return a string representation of a HTML ID which can be used literally in a jQuery selector.
	//
	function get_jq_safe_selector(txt) {
		var chars = [ '.', ':', '-' ];

		for (i in chars) {
			var a = txt.split(chars[i]);
			txt = a.join('\\' + chars[i]);
			}

		return (txt);
		}

	//
	//	Given a selector to one or more <div> elements we intend to edit, create the floating 'edit' tag,
	//	complete with its click() trigger.
	//
	//	'version_number' is the version number for the content of the div; we have to create a hidden field to store it.  It will only
	//	be supplied when the div content is first retrieved.
	//
	//	The selector string *is* sanitised by this point!
	//
	function add_TinyMCE_tag(sel_string, version_number) {
		$(sel_string).each(function(index) {
			var div = $(this);
			var div_id = div.attr('id');

			//var tag = $('<span class="TinyMCE-tag"><input type="button" value="Edit"><input type="button" value="Clear"><input type="button" value="Print"></span>');
			var tag = $('<span class="TinyMCE-tag"><input type="button" value="Edit"><input type="button" value="Clear"></span>');

			div.after(tag);		//	add the tag to come after the <div>

			//	Now we position the tag to just after the top left corner of the <div>

			var pos = div.position();
			var width = div.innerWidth();

			var tagwidth = tag.outerWidth(true);

			//	top left corner of the div
			//tag.css('position', 'absolute').css('top', pos.top + Y_OFFSET).css('left', pos.left + X_OFFSET);

			//	Top right
			tag.css('position', 'absolute').css('top', pos.top + Y_OFFSET).css('left', pos.left + width - tagwidth - X_OFFSET);

			//	Now we have to attach javascript to the two buttons.

			tag.find('[value="Edit"]').click(function(e) {
				start_TinyMCE(div_id);
				});

			tag.find('[value="Clear"]').click(function(e) {
				tag.remove();
				div.toggleClass('TinyMCE-capable', false);
			});

			//	Print button.

			tag.find('[value="Print"]').click(function(e) {
				print_div(div_id, div);
			});

			//	Now add the hidden version number field.

			if (version_number != undefined) {
				var ver_id = get_version_number_id(div_id);

				var verfield = $('<input type="hidden" name="' + ver_id + '" id="' + ver_id + '" value="' + version_number + '">').addClass('TinyMCE-version');

				div.after(verfield);
				}
		});
	}

	//
	//	Kick off a TinyMCE editing session on the supplied JQuery element.
	//
	function start_TinyMCE(div_id) {
		var jq_el = $('#' + get_jq_safe_selector(div_id));

		//	
		//	Keep a copy of the former contents, which we copy back on a CANCEL.
		//
		var old_html = jq_el.html();
		
		//
		//	Remove ALL of the edit tags
		//
		$('.TinyMCE-tag').remove();

		//
		//	Add save/query buttons.  Append them after the TinyMCE instance, which should have appeared courtesy of
		//	the initialisation above.
		//
		//	If the TinyMCE editor is already up then place the tag after it.  Otherwise we can't do this; if we're
		//	instantiating the editor for the first time it will still be loading, it seems, when we move onto here - there's
		//	definitely a delay.  In which case we place the tag after the original div.
		//
		var tag = $('<div class="TinyMCE-savecancel"><input type="button" value="Save"><input type="button" value="Cancel"></div>');

		var mce_div = $('#' + get_jq_safe_selector(div_id + '_parent'));			//	TinyMCE's <span>, which is the top element of its hierarchy which it creates, has an ID with the suffix of '_parent'
		
		var root = mce_div.length > 0 ? mce_div : jq_el;

		root.after(tag);

		//
		//	On a cancel we copy back the old HTML.
		//
		//	This is where I don't understand how tinyMCE works.  I tried to copy back the old contents to the 'jq_el' div AFTER calling stop_TinyMCE() (which just
		//	does a jQuery hide() on it).  Absolutely no effect.  But if I copy the contents back to the div BEFORE I hide the editor I see that (a) the *editor* 
		//	window's contents get replaced by the old content, and then when the editor closes down the original div gets it back too.
		//
		//	So I think tinyMCE is doing evil things with events ... 'redirecting' things somewhow?  I wouldn't mind looking into it more one day.
		//
		tag.find('[value="Cancel"]').click(function(e) {
			jq_el.html(old_html);		//	put back the old contents ... to the div, even though the tinyMCE editor is still up.

			//	Close down the editor.

			$('.TinyMCE-savecancel').remove();
			stop_TinyMCE(jq_el);
			});

		tag.find('[value="Save"]').click(function(e) {
			var content = jq_el.tinymce().getContent();
			save_content(div_id, content);

			$('.TinyMCE-savecancel').remove();
			stop_TinyMCE(jq_el);
			});

		//	Now fire up the editor.  Fun and games to see if TinyMCE is loaded first; if not we have to initialise it.
		//
		//	(We could just do the initialisation at page load - presumably there's a way to stop the editor windows from firing up straight away - and just
		//	do the show() here.  Or, rather than testing for the existence of tinymce in its various forms, we could just have our own flag variable?

		if (typeof(tinyMCE) == 'undefined'  ||  jq_el.tinymce == 'undefined'  ||  jq_el.tinymce() == undefined)
			jq_el.tinymce(TinyMCE_Params);
		else
			jq_el.tinymce().show();
	}

	//
	//	Transmit the edited content to the web server for storage.
	//
	//	We now create a <form> element on the fly so we can call form.serialize() to get our data to send
	//	to the server.
	//
	function save_content (div_id, content) {
		//
		//	Build up the object we're going to send.
		//
		var ver_id = get_version_number_id(div_id);
		var ver_jq = $('#' + get_jq_safe_selector(ver_id));

		var obj = {
			savecontent:	content,
			version: 		ver_jq.val()
			};

		var formData = jQuery.param(obj);

		//	Now send it off to the server.

		$.ajax( {
			type:		"POST",
			url:		'/includes/website_content/website_content.php?op=save&divId=' + encodeURIComponent(div_id),
			data: 		formData,
			dataType: 	"json",

			success: function(json) {
				if (json.error == 1)
					alert(json.message);
				else {
					//
					//	Update the hidden field for the version number.
					//
					ver_jq.val(json.version);
					}
				},

			error: function(XMLHttprequest, textStatus, errorThrown) {
				alert('Server communication error on SAVE!');
				}
		});
	}

	//
	//	Stop the TinyMCE editing session on the passed JQuery element.
	//
	function stop_TinyMCE(jq_el) {
		jq_el.tinymce().hide();						//	close down the session

		add_TinyMCE_tag('.TinyMCE-capable');		//	re-create the edit tags (but not the version number hidden field)
	}


	/*
	 * 	Print the contents of a div.
	 *
	 * 		div		-	the jQuery div element
	 * 		div_id
	 *
	 * 	We do this by:
	 *
	 * 	-	creating a new window (the brower's print() function only works on windows and frames);
	 * 	-	populating the window's document with the <head> of the current web page and the content of the <div> we're printing;
	 * 	-	calling print() on the window
	 * 	-	closing the window.
	 */
	function print_div (div_id, div) {
		var head = $('head');

		var win = window.open('', 'PrintWindow', 'width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');

		win.document.writeln('<html><head>' + head.html() + '</head><body>' + div.html() + '</body></html>');

		win.document.close();

		win.focus();
		win.print();
		win.close();
	}
	
	//
	//	-----------	Initiaisation ------------
	//
	//	Initialisation - populate the divs.
	//
	//	It's VITAL that we find this to the *load* event and not carry on under the *ready* event that we're currently under!!
	//
	$(window).load(function() {
		$('.TinyMCE-capable').each(function(index) {
			var div = $(this);
			var div_id = div.attr('id');
			
			//
			//	Retrieve the content of each div via AJAX.  We have to set up the edit tag in the
			//	callback function, and not in subsequent initialisation steps after this loop through
			//	the 'TinyMCE-capable' elements, as we can't set up the tags until after the asynchronous
			//	call has returned!
			//
			$.ajax( {
				type:		"GET",
				url:		'/includes/website_content/website_content.php?op=get&divId=' + encodeURIComponent(div_id),
				dataType:	'json',
				
				success:	function(json) {
								if (json.error)
									alert(json.message);
								else {
									if (json.editor)
										add_TinyMCE_tag('#' + get_jq_safe_selector(div_id), json.version);
									else
										div.toggleClass('TinyMCE-capable', false);

									//	If the content exists - i.e. is not null - then wipe what's in the div with it.
								
									if (json.content != null)
										div.html(json.content);
									}
						},

				error: 	function(XMLHttprequest, textStatus, errorThrown) {
					alert('Server communication error!');
					}
			});
		});

	});

});

//
// Open dialog box with meta tags edit form
//
function meta_tags_dialog() {
	$('#meta-tags-dialog').html($('#meta-tags .form').html());
	$('#meta-tags-dialog').dialog({
		buttons: { 
			"OK" 	: meta_tags_submit,
			"Cancel": function() { $(this).dialog("close"); } 
		},
		title: 'Edit meta tags',
		width: 650,
		beforeClose: function(event, ui) {  $('#meta-tags .TinyMCE-tag').show(); },
		position: [10,10]
	});
	
	$('#meta-tags .TinyMCE-tag').hide();
}

//
// Submit meta tags form with ajax
//
function meta_tags_submit() {
	var p = '#meta-tags-dialog #';
	
	var data = {
		page: $(p + 'page-name').val()
	};
	
	var tags = Array('title', 'description', 'keywords', 'top_banner', 'bottom_banner');
	for (var i=0; i<tags.length; i++) {
		data[ tags[i] ] = {};
		
		data[ tags[i] ].content = $(p + tags[i]).val();
		data[ tags[i] ].version = $(p + tags[i] + '-version').val();		
	}
	
	$.ajax({
		type:		'POST',
		url: 		'/includes/website_content/website_content.php?op=save&divId=1',
		data:		data,
		success:	function(response) {
			/**
			 * Anyway inform user about result
			 */
			alert(response.message);
			
			/**
			 * If no error, then this page should be reloaded to take
			 * effect all changes in meta-tags.
			 */
			if (!response.error) {
				window.location.reload();
			}
		},
		error: 		function(jqXHR, textStatus, errorThrown) {
			alert('Server communication error! ' + errorThrown);
		}
	});
}

//
//	Char counter implementation. Counts chars in input field, alerts when number of chars
//	is more then 155 symbols.
//	@param string field Field id to set the counter to. 
//
function set_counter(field) {
	field = '#' + field;

	var curr_len = $(field).val().length;
	
	// Set counter value
	$(field + '-counter').html(soft_limit(curr_len));
}

//
// Returns just number, but if the number is greater then 155, then mark it with the red 
//
function soft_limit(i) { 
	return i > 155 ? '<span class="red">' + i + '!</span>': i;
}

// Set all counters
$(document).ready(function(){
	if (typeof isLoggedIn != "undefined" && isLoggedIn) {
		set_counter('title');
		set_counter('description');
		set_counter('keywords');
	}
});
