/******************************************
 * UAA Javascript Standard Library
 * Revision $Id: uaa.js 8 2011-01-26 18:14:50Z axsrn $
 *
 * UAA
 * -init: Called upon documentReady to initialize objects and logging facilities
 * -consoleInitialize: Makes sure that logging functionality will work properly across browsers
 * --- jsTree
 * --- litebox
 *
 ******************************************/

var UAA = {
	init: function() {
		//Ensure that all console logging will not error out the script if tools aren't present
		UAA.consoleInitialize();
		
		//Set up library initialization timing
		console.time("UAA Standard Library Initialization");
		
		//Called on documentReady. All UAA-specific Javascript libaries and objects should be initialized here.
		try {
			if(typeof jQuery === 'undefined') throw('jQuery must be present for the UAA library to function properly.');
			
			//Style all elements requiring some JavaScript assistance
			UAA.styleize();
			
			//Initialize the leftnav jsTree
			if(document.getElementById('leftnav') !== null) UAA.jsTree();
			
			console.info('Litebox initialization currently disabled.');
			//UAA.litebox();
		}
		catch(e) {
			console.log(e);
		}
		
		// Print out timing initialization info
		console.timeEnd("UAA Standard Library Initialization");
	},
	
	/*******************************************************
	 * Ensure that a window.console function exists. This allows for calls to Firebug & other development
	 * tools without having to check for a console each time by creating dummy replacements
	 *******************************************************/
	consoleInitialize: function() {
		if(typeof window.console === 'undefined') window.console = new Object();
		if(typeof window.console.profile === 'undefined') window.console.profile = function() {};
		if(typeof window.console.profileEnd === 'undefined') window.console.profileEnd = function() {};
		if(typeof window.console.log === 'undefined') window.console.log = function(s) {};
		if(typeof window.console.notice === 'undefined') window.console.notice = function(s) { window.console.log(s); };
		if(typeof window.console.info === 'undefined') window.console.info = function(s) { window.console.log(s); };
		
		//If time functions do not exist, replace with custom ones. This gives the IE developer tools access to timing functionality
		if(typeof window.console.time === 'undefined') {
			window.console.time = function(s) {
				console.time.timers[s] = new Date().getTime();
			};
			
			window.console.time.timers = new Object();
		}
		
		if(typeof window.console.timeEnd === 'undefined') {
			window.console.timeEnd = function(s) {
				//Check to see if timer has started
				if(typeof console.time.timers[s] !== 'undefined') {
					//Print out difference and reset timer
					console.info(s + ": " + (new Date().getTime() - console.time.timers[s]) + "ms");
					console.time.timers[s] = null;
				}
			}
		};
	},
	
	/*******************************************************
	 * Cross-browser replacement for jQuery's documentReady event that will work
	 * regardless of jQuery's presence.
	 *******************************************************/
	documentReady: function(fn) {
		if (document.addEventListener)
			document.addEventListener("DOMContentLoaded", fn, false);
		else if (document.all && !window.opera) {
			document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>')

			var contentloadtag = document.getElementById("contentloadtag");
			contentloadtag.onreadystatechange = function() {
				if (this.readyState=="complete")
					fn();
			}
		}
	},
	
	
	styleize: function(fn) {
		jQuery(" .striped > tr:nth-child(even), .striped > tbody > tr:nth-child(even), .striped > li:nth-child(even)").addClass("altStripe");
	}
}

/************************************************************************************************************
 * UAA.jsTree Static Class
 * ------------------------
 * This uses the jsTree jQuery library to set up the left navigation bar as a tree. This allows expanding and
 * collapsing of the items in the tree to enhance usability. If in author mode, it will also allow reordering
 * of items within their level on the tree. This makes it much easier to change a page's sort order.
 ************************************************************************************************************/
UAA.jsTree = function() {
	if(typeof jQuery.jstree === 'undefined') throw('jsTree Javascript library must be present for the UAA jsTree to function properly.');
	if(document.getElementById('leftnav') === null) throw('jsTree library cannot load due to #leftnav element not being present in DOM');
	
	console.time('jsTree initialization');

	/****** This event fires when the tree finishes loading ******/
	jQuery("#leftnav").bind('loaded.jstree', function(event, data) {
	
		jQuery('.tree-root').addClass('jstree-open').removeClass('jstree-closed');
		console.timeEnd('jsTree initialization');
	});
	
	//Open all nodes from the current item up
	jQuery('.tree-current').parentsUntil("#leftnav").addClass('jstree-open');
	
	/******Initialize the jTree ******/
	var params = new Object();
	params["plugins"] = ["html_data"];
	//params["core"] = {"animation": 0 };
	jQuery("#leftnav").jstree(params);
	
	/****** Events for links above the tree ******/
	jQuery('#leftnavExpand').click(function(event) {
		event.preventDefault();
		jQuery('#leftnav').jstree("open_all");
	});
	
	jQuery('#leftnavCollapse').click(function(event) {
		event.preventDefault();
		jQuery('#leftnav').jstree("close_all", '.tree-root li');
	});
	
	
	/****** Author Mode Links ******/
	
	jQuery("#sidebar .page-meta").click(function(event) {
		event.preventDefault();
		
		var pageid = jQuery(this).parent().attr('id').replace("page", "");
		var obj = document.createElement("iframe");
		obj.src = '/loader.cfm?csModule=pagemode/pageprop-action&pageid='+ pageid + '&setlock=1&bProcessType=7&hidePrevious=1';
		jQuery(obj).dialog();
		//newWindow('pagemetadata','/loader.cfm?csModule=pagemode/pageprop-action&pageid='+ pageid + '&setlock=1&bProcessType=7&hidePrevious=1');
	});

	jQuery("#sidebar .page-properties").click(function(event) {
		event.preventDefault();
		
		var pageid = jQuery(this).parent().attr('id').replace("page", "");
		
		newWindow('pageprop','/loader.cfm?csModule=pagemode/pageprop&pageid='+ pageid + '&getlock=1&bProcessType=7&hidePrevious=1');
	});
	
	jQuery("#leftnavAuthoring .reorganize").click(function(event) {
		event.preventDefault();
		
		var sortElem = jQuery("#leftnav .tree-current");
		
		//If root, go down a level
		if(sortElem.hasClass('tree-root')) sortElem = jQuery('> ul', sortElem);
		else sortElem = sortElem.parent("ul");
		
		if(jQuery(this).hasClass("edit_order")) UAA.jsTree.editTreeOrder.apply(this, [sortElem]);
		else UAA.jsTree.saveTreeOrder.apply(this, [sortElem]);
	});
	
	jQuery("#leftnavAuthoring .help").click(function(event) {
		event.preventDefault();
		
		jQuery.get('/customcf/authoringHelp.html', function(content) {
			UAA.litebox.open(content, { title: "Authoring Help", height: 500 }, function() {
			
			});
		});
	});
}

/****** Used by the leftnav tree to determine if the user has changed the sort order of the items ******/
UAA.jsTree.needsSaving = false;


/*************************************************************************
 * Used by the main tree function to turn on edit mode of the left nav for authors.
 *************************************************************************/
UAA.jsTree.editTreeOrder = function(sortElem) {
	//Close children of tree first
	jQuery("#leftnav").addClass('author').jstree("close_node", sortElem.children("li"), true);
	
	UAA.jsTree.needsSaving = false;
	
	//Make items sortable
	sortElem.sortable({
		update: function(event, ui) { UAA.jsTree.needsSaving = true; }
	});
	
	jQuery(this).removeClass('edit_order').addClass("save_order").attr("alt", "Save Menu Order");
}

/*************************************************************************
 * Used by the main tree function to save changes to menu edits.
 *************************************************************************/
UAA.jsTree.saveTreeOrder = function(sortElem) {
	if(!UAA.jsTree.needsSaving) {
		UAA.jsTree.exitTreeOrder(sortElem);
		return;
	}
	
	jQuery(this).removeClass('save_order').addClass("saving_order").attr("alt", "Saving Menu Order");

	var params = new Object();
	params["pages"] = new Array();
	
	sortElem.children("li").each(function() {
		params['pages'].push(this.id.replace("page", ""));
	});

	jQuery.post("/customcf/menu_order_save.cfm", params, function() {
		UAA.jsTree.exitTreeOrder(sortElem);
	});
}

/*************************************************************************
 * Used by the main tree function to turn off edit mode of the leftnav for authors.
 *************************************************************************/
UAA.jsTree.exitTreeOrder = function(sortElem) {
	sortElem.sortable("destroy");
	
	jQuery("#leftnavAuthoring .reorganize").removeClass('saving_order').removeClass('save_order').addClass("edit_order").attr("alt", "Edit Menu Order");;
	jQuery("#leftnav").removeClass('author');
}


/************************************************************************************************************
 * UAA Litebox Static Class
 * -------------------------
 * Opens up a UAA-themed litebox with no content or prepared content. This dialog has a delayed content-
 * handling function to play nice with Commonspot's load functionality. It can be used standalone or to
 * replace many various Commonspot pop-up dialogs.
 ************************************************************************************************************/
UAA.litebox = function() {
	jQuery(function() {
		console.time('Litebox initialization');
		
		window.commonspotNewWindow = window.newWindow;
		window.newWindow = UAA.litebox.newWindow;
		
		window.CloseWindow = function() {
			CloseWindow.apply(this);
			jQuery('.ui-dialog').dialog("destroy");
		};
		
		console.timeEnd('Litebox initialization');
	});
},

UAA.litebox.open = function(content, options, callback) {
	var params = new Object();
	params.width = window.screen.width / 2;
	params.zIndex = 999999;
	params.resizable = true;
	params.modal = false;
	params.open = callback;
	
	if(typeof options !== Object) {
		for (var i in options) {
			params[i] = options[i];
		}
	}

	jQuery(content).dialog(params);
},

UAA.litebox.newWindow = function(name,workUrl) {
	if(name != 'tbEdit') {
		return commonspotNewWindow(name, workUrl);	
	}
	
	var externalLinkRegEx = /^https?:[\/\\]{2}/i;
	var blnPopUpsOffScreen=0;
	var intTop=200;
	var intLeft=200;
	var intHeight=640;
	var intWidth=960;
	var cookieStr = document.cookie;
	var cookieWinRegEx = /CSOFFSCREENPOPUPSALLOWED=\d/i;
	var rxVal = /\d+/;
	try {
		if (cookieStr && cookieStr.match(cookieWinRegEx)) {
			var strVal=cookieStr.match(cookieWinRegEx);
			if (strVal)
				blnPopUpsOffScreen=strVal.toString().match(rxVal);
			else
				blnPopUpsOffScreen = 0;
		}
		else
			blnPopUpsOffScreen=0;
	}
	catch (oErr) {
		blnPopUpsOffScreen=0;
	}
	if(blnPopUpsOffScreen==1)
	{
		intTop=window.screen.height - 9;
		intLeft=window.screen.width - 9;
		intHeight=1;
		intWidth=1;
	}
	else
	{
		intTop=(window.screen.height / 2) - 109;
		intLeft=(window.screen.width / 2) - 210;
		intHeight=218;
		intWidth=421;
	}
	if(!workUrl.match(externalLinkRegEx) && workUrl.indexOf('kurrentPageID') == -1)
	{
		if(typeof js_gvPageID != 'undefined')
		{
			try
			{
				if( workUrl.indexOf ('?') == -1 )
					workUrl = workUrl + '?kurrentPageID=' + js_gvPageID;
				else
					workUrl = workUrl + '&kurrentPageID=' + js_gvPageID;
			}
			catch (oErr)
				{ /* Do Nothing */ }
		}
	}
	var re = new RegExp();
	re = /&amp;/gi;
	workUrl = workUrl.replace(re,"&");
	// do not use CommonSpot loader if the URL is fully-qualified (i.e. if we find a protocol)
	if ((workUrl.search(/^[a-zA-Z]+:\/\//) == 0) && (workUrl.search(/[\/\\]/g) >= 0) && (blnPopUpsOffScreen==0))
	{
		if (document.CS_StaticURL && window.location.href.indexOf(document.CS_StaticURL) == -1)
		workUrl = jsDlgLoader + '?proc_type=dynamic_page&onlyurlvars=1&realTarget=' + escape(workUrl);
	}
	var strWinOptions = 'toolbar=no,resizable=yes,scrollbars=yes,menubar=no,location=no';
	if(arguments.length >= 2 && arguments[2])
	{
		var strOptions=arguments[2];
		var strTopPos=strOptions.match(/top=\s*(\d+)/i);
		if(strTopPos && strTopPos[1] >=0)
		{
			intTop=strTopPos[1];
			strOptions=strOptions.replace(/top=\s*\d+\s*,?/i,'')
		}
		var strLeftPos=strOptions.match(/left=\s*(\d+)/i);
		if(strLeftPos && strLeftPos[1] >=0)
		{
			intLeft=strLeftPos[1];
			strOptions=strOptions.replace(/left=\s*\d+\s*,?/i,'')
		}
		var strHeight=strOptions.match(/height=\s*(\d+)/i);
		if(strHeight && strHeight[1] >=0)
		{
			intHeight=strHeight[1];
			strOptions=strOptions.replace(/height=\s*\d+\s*,?/i,'')
		}
		var strWidth=strOptions.match(/width=\s*(\d+)/i);
		if(strWidth && strWidth[1] >=0)
		{
			intWidth=strWidth[1];
			strOptions=strOptions.replace(/width=\s*\d+\s*,?/i,'')
		}
		var strWinOptions = strOptions;
	}
	strWinOptions = strWinOptions + ',top='+ intTop + ',left=' + intLeft + ',height=' + intHeight + ',width=' + intWidth;
	/*var winWindow=window.open(workUrl,name,strWinOptions);
	if (!winWindow)
		alert('Unable to open window - please make sure the pop-up blocker is disabled for this site');
	else
		winWindow.focus();
		if(arguments.length==4 && arguments[3]==1 && winWindow)
		return winWindow;*/
		
	var obj = document.createElement("iframe");
	obj.src = workUrl;
	
	jQuery(obj).dialog({
		width: window.screen.width - 200,
		height: window.screen.height - 300,
		zIndex: 999999,
		resizable: false,
		modal: true,
		open: function() {
			var openedWindow = this.contentWindow;
			window.setTimeout(function() { UAA.litebox.newWindowCallback.apply(openedWindow); }, 100);
		}
		
	});
},

UAA.litebox.newWindowCallback = function() {
	var dialogWindow = this;
	
	while(this.loaded != true) {
		window.setTimeout(function() { UAA.litebox.newWindowCallback.apply(dialogWindow); }, 100);
		return;
	}
	
	jQuery(".ui-dialog iframe").removeAttr('style').css('height', (window.screen.height - 300) + 'px');
	
	this.commonspotCloseWindow = this.CloseWindow;
	this.CloseWindow = function() {
		dialogWindow.commonspotCloseWindow();
		jQuery(".ui-dialog iframe").dialog('destroy');
	};
	
	this.commonspotUnload = this.cp__onUnload;
	this.cp__onUnload = function() {
		dialogWindow.commonspotUnload();
		jQuery(".ui-dialog iframe").dialog('destroy');
		window.location.reload();
	};
}


/*************************************************************************************************************/
/*************************************************************************************************************/
/*************************************************************************************************************/

//Initialize the UAA static object on documentReady
jQuery(UAA.init);
