// JavaScript Document

if(typeof(tinyMCE) != "undefined")
{
	/* Set up the tinyMCE */
	tinyMCE.init({
		plugins : '-example', // - tells TinyMCE to skip the loading of the plugin
		mode : "textareas",
		theme : "advanced",
		content_css : "/tiny_mce.css",
		theme_advanced_buttons1 : "bold,italic,underline,fontsizeselect,justifyleft,justifycenter,justifyright,justifyfull,undo,redo",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		encoding : "xml",
		entity_encoding : "numeric",
		setup : function(ed) {
		  ed.onKeyDown.add(function(ed, e) {
				VPChanged = true;
		  });
	   }
	});
}

// Array to define the pages into which different objects reside
var VPPage = [];
var VPDiv = [];
var VPLoadedFunc = [];
var VPxParams = null;
var VPOnPageLoadedFunc = null;
var VPXMLInt = null;
var VPBase = "";
var VPParams = null;
var VPGuestAccess = false;
var VPLastHash = '';
var VPFCKEditorBasePath = '/fckeditor/';

document.observe("dom:loaded", function() {
	// Set up timer to check for back forward hash changes
	new PeriodicalExecuter(function(pe) {
		if(location.hash != VPLastHash)
			VPInitPage();
		}, 0.5);

	// Display the initial page
	VPInitPage();
	if(VPOnPageLoadedFunc != null)
		eval(VPOnPageLoadedFunc + '()');
}); 

function VPInitPage()
{
	var params = {};
	var hash;
	
	// Get the hash if there is one 
	// If VPParams set use it instead
	VPLastHash = location.hash;
	if(VPParams != null)
		hash = VPParams;
	else
		hash = location.hash.substring(1);
	if(VPxParams != null)
		hash = hash + '&' + VPxParams;
	params = hash.parseQuery();
	if(params['Object'] == null && params['Results'] == null)
		params['Object'] = 'Login';
	if(params['Ajax'] == null)
		params['Ajax'] = 'true';
		
	// Do we have a session. If not and a User Name is supplied
	// then get one.
	var session = VPGetSession();
	if(session == null && params['Name'] != null)
	{
		// Lets get a session 
		VPObjectXML("User", "Name=" + params['Name'] + "&Password=" + params['Password'], "VPSessionReturned", hash);
	}
	else
		VPLoadHTML(params);
}

function VPSessionReturned(xml, Error, params)
{
	if(Error != null)
	{
		alert('Error');
		return;
	}
	
	var session = xml.getElementsByTagName("Session")[0].childNodes[0].nodeValue;
	hash = location.hash;
	if(hash == "")
		hash = "#Session=" + session;
	else
		hash = location.hash + "&Session=" + session;
	VPLastHash = hash;
	location.hash = hash;

	if(VPParams != null)
		hash = VPParams;
	else
		hash = location.hash.substring(1);
	if(VPxParams != null)
		hash = hash + '&' + VPxParams;
	params = hash.parseQuery();

	VPLoadHTML(params);
}

function VPLoadHTML(params)
{
	if(VPDiv[params['Object']] == null)
	{
		// Is there a div to which html content should be rendered
		if($('VariablePDF') != null)
		{
			// Yes lets get it from the server
			new Ajax.Request(VPBase + 'Interface.php', {
							method: 'post', parameters: params,
							onSuccess: function(response) {
								VPRenderHTML(response.responseText, 'VariablePDF');
							} 
			});
		}
	}
	else
	{
		var vpdivs = VPDiv[params['Object']];

		vpdivs.each(function(s) {
						var a = s.split("=>");
						params['Object'] = a[1];
						new Ajax.Request(VPBase + 'Interface.php', {
										method: 'post', parameters: params,
										onSuccess: function(response) {
											VPRenderHTML(response.responseText, a[0]);
										} 
						});
					}); 
	}
}

function VPFormSubmitted(iframe, form, div)
{
	/* Form submitted through a iframe
	May have used a defered result if need to load a new
	html file */
	i = $(iframe);
	f = $(form);
	if (i.contentDocument) {
		var d = i.contentDocument;
	} else if (i.contentWindow) {
		var d = i.contentWindow.document;
	} else {
		var d = window.frames[i.id].document;
	}
	
	if(d.body.innerHTML == '#')
		// If this is just the load of the hash page do nothing
		return;

	if(d.body.innerHTML == '')
	{
		// Force a refresh of the current page in this case
		// Returning nothing from php is used for instance for
		// add and deletes of Assets and Templates
		window.location.reload(true);
		return;
	}
	
	var params = f.serialize().parseQuery();
	var object = params['Object'];
	
	/* Should we be loading a different html page for these
	results? If so results will have been defered */
	if(d.body.innerHTML.substr(0, 7) == 'DEFERED')
	{
		/* We need to go to another page and load the defered results */
		path = VPPage[object] + '#';
		path += d.body.innerHTML.substr(7).replace(new RegExp('&amp;','g'), '&');
		location.href = path;
	}
	else
		VPRenderHTML(d.body.innerHTML, $(div));
}

function VPAddHiddenField(form, name, value)
{
	if(typeof(form.elements[name]) == "undefined")
	{
		var el = document.createElement("input");
		el.type = "hidden";
		el.name = name;
		el.value = value;
		form.appendChild(el);
	}
	else
	{
		form.elements[name].value = value;
	}
}

function VPPreSubmitForm(form, div)
{
	// Set up form so that it uses a hidden iframe in an ajaxing style.
	if(typeof(tinyMCE) != "undefined")
		tinyMCE.triggerSave(true,true);
	var params = form.serialize().parseQuery();
	var d = document.createElement('DIV');
	d.innerHTML = '<iframe style="visibility:hidden;position:absolute" src="' + VPBase + 'hash.html" name="' + form.id + '" id="VPF' + form.id + '" onLoad="VPFormSubmitted(this, \'' + form.id + '\', \'' + $(div).id + '\');" />';
	document.body.appendChild(d);
	
	/* Do we need to defer the results? */
	if(VPPage[params['Object']] != null)
	{
		/* Yep - add the defer parameter */
		VPAddHiddenField(form, 'Defer', 'true');
	}
	/* Add any extra params */
	if(VPxParams != null)
	{
		cform = form;
		$A(VPxParams.split('&')).each(function(p) {
			a = p.split('=');
			// Don't add the Object field if it is in the xparams
			if(a[0] != "Object")
				VPAddHiddenField(cform, a[0], a[1]);
		});
	}
	
	/* Add session if known */
	var session = VPGetSession();
	if(session != null)
	{
		VPAddHiddenField(cform, 'Session', session);
	}

	form.target=form.id;
	return true;
}

function VPSubmitForm(form, div)
{
	VPPreSubmitForm(form, div);
	$(form).submit()
}

function VPRenderHTML(text, div)
{
	VPLastHash = location.hash;
	$(div).update(text);

	if(VPLoadedFunc[$(div).id] != null)
	{
		eval(VPLoadedFunc[$(div).id] + "();");
	}

	// Catch any forms
	if(false)
	{
	$$('form[id^=VPForm]').invoke('observe', 'submit', function(e) {
		e.stop();
		/* If tiny mce involved make sure updates have been applied */														
		if(typeof(tinyMCE) != "undefined")
			tinyMCE.triggerSave(true,true);
		var params = this.serialize().parseQuery();
		if(VPPage[params['Object']] != null)
		{
			location.href = VPPage[params['Object']] + '#' + this.serialize();
		}
		else
		{
			new Ajax.Request(this.action, {
							 method: 'post', parameters: this.serialize() + "&Ajax=true",
							 onSuccess: function(response) {
								  VPRenderHTML(response.responseText, div);
							 } 
			});
		}
	});
	}
	
	if(true)
	{
	/* Use an iframe to submit any forms */
	/* A system that defers the results will be used if a different
	page is used to display the results */
	$$('form[id^=VPForm]').invoke('observe', 'submit', function(e) {
		return(VPPreSubmitForm(this, div));
	});
	}
	
	// Catch any anchor clicks for VariablePDF
	$$('a[id^=VPRef]').invoke('observe', 'click', function(e) {
		e.stop();
		// Hash get values
		var params = this.href.parseQuery();
		var hash = $H(params).toQueryString();
		
		hash += "&Ajax=true";
		// Does this object require that we go to a different container page?
		if(VPPage[params['Object']] != null)
		{
			location.href = VPPage[params['Object']] + '#' + hash;
		}
		else
		{
			location.hash = hash;
			new Ajax.Request(this.href + "&Ajax=true", {
							method: 'get',
							onSuccess: function(response) {
							VPRenderHTML(response.responseText, div);
							} 
			});
		}
	});
	
	// If tinymce being used change textareas to tinymce
	if(typeof(tinyMCE) != "undefined")
	{
		tinyMCE.idCounter=0;
		$$('textarea[id^=VPF]').each(function(ta) {
						tinyMCE.execCommand('mceAddControl', true, $(ta).id);
					});
	}
	
	// If fckeditor being used change textareas to fckeditor
	if(typeof(FCKeditor) != "undefined")
	{
		$$('textarea[id^=VPF]').each(function(s) { 
			var oFCKeditor = new FCKeditor( $(s).id ) ;
			oFCKeditor.BasePath = VPFCKEditorBasePath ;
			oFCKeditor.ToolbarSet = 'VariablePDF'; 
			oFCKeditor.ReplaceTextarea() ;
		});
	}
}

function VPBackForward()
{
	if(location.hash != VPLastHash)
		VPInitPage();
	setTimeout('VPBackForward()', 500);
}

// Register VPSwapImage with each of the fckeditors
function FCKeditor_OnComplete( editorInstance )
{
	// Name is proceeded by VPS so remove
	var name = editorInstance.Name.substring(3);
    editorInstance.Events.AttachEvent( 'OnFocus', function() {
														   VPSwapImage(name, 'Field', $('VPSession').value, $('VPTemplate_id').value, true);
														   if($('VPDefaultFields').value == 'true')
														   {
																if($('VPFOrg' + name).value == 1)
																{
																	editorInstance.EditorDocument.body.innerHTML = '';
																	$('VPFOrg' + name).value = 0;
																}
															}
														   } );
    editorInstance.Events.AttachEvent( 'OnSelectionChange', function() {VPChanged = true;} );
}
