<!--
/*
 *	$Id: core.js 1 2006-12-16 10:21:16Z james $
 *
 *	These functions are use by all modules' own scripts.
 *	All functions are prefixed with 'EXNT_' to separate them from users' own functions.
 */

// Globals
var EXNT_LOADED_JAVASCRIPT = new Array();	// Keeps track of what JavaScript and CSS has been loaded into the current page
var EXNT_LOADED_STYLESHEET = new Array();

// Window event listener
if(!window.addEventListener) {
	window.addEventListener = function(ev, func, useCapture) {
		if(!window['__eventHandlerQueue_'+ev]) {
			window['__eventHandlerQueue_'+ev] = new Array();
			window['on'+ev] = function() {
				for(var i=0; i<window['__eventHandlerQueue_'+ev].length; i++) {
					window['__eventHandlerQueue_'+ev][i]();
				}
			}
		}
		window['__eventHandlerQueue_'+ev].push(func);
	}
}

//-------------------------------
// STRING EXNT_genHREF( module, action, custom )
//--
// STRING module	= module name
// STRING action	= module action
// OBJECT custom	= name=value pairs of custom parameters
//--
// Generates a URL in line with the setting of 'shortURI'.
// If you provided a custom parameter that is an array, then note
// that only one level of elements within that array is supported.
// It uses 'encodeURIComponent()' to escape the parameter strings for
// use in the URI, but this requires JavaScript 1.5, but curiously enough
// it works in IE6 which only support up to v1.3
//-------------------------------
function EXNT_genHREF(module, action, custom) {

	// Vars
	var href = '';
	var k = '';

	// Build custom parameters list
	if(custom!=undefined) {
		// Set NavNode ID
		if(custom.node==undefined) custom.node = EXNT_EXEC.node;
		//var cp = '';
		//var separator = (EXNT_config('shortURI')=='1') ? '/' : '&';
		custom = _exntgenhref_addCustom(null, custom);
		custom = custom.replace(/^\//, "");
		/*for(k in custom) {
			if(typeof custom[k]=='object') {
				for(var i in custom[k]) {
					cp += k + '['+i+']=' + encodeURIComponent(custom[k][i]) + separator;
				}
			}
			else {
				cp += k + '=' + encodeURIComponent(custom[k]) + separator;
			}
		}
		custom = cp;*/
	}
	else {
		custom = 'node=' + EXNT_EXEC.node;
	}

	// Generate href
	if(EXNT_config('shortURI')=='1') {
		href = EXNT_config('urlPublic') + '/exec/' + module + '/' + action + '/' + custom;
	}
	else {
		href = EXNT_config('urlPublic') + '/?module=' + module + '&action=' + action + '&' + custom;
	}

	// Result
	return href;
}

function _exntgenhref_addCustom(key, param) {

	// Vars
	var url = '';
	var separator = (EXNT_config('shortURI')==1) ? '/' : '&';

	// Add all sub-parameters
	if(typeof param=='object') {
		for(var k in param) {
			var p = param[k];
			var newKey = key==null ? k : key+"["+k+"]";
			url += _exntgenhref_addCustom(newKey, p, separator);
		}
	}
	else {
		url += separator+key+"="+encodeURIComponent(param);
	}

	// Result
	return url;
}

//-------------------------------
// MIXED EXNT_config( varName )
//--
// STRING varName	= Name of the configuration variable to fetch
//--
// Returns the specified configuration directive.
// All config is stored in the global 'EXNT_SYS_CONFIG' variable as generated in 'JavaScript.tpl'
//-------------------------------
function EXNT_config(varName) {
	return (EXNT_SYS_CONFIG[varName]!=null) ? EXNT_SYS_CONFIG[varName] : '';
}

//-------------------------------
// BOOL EXNT_loadJavaScript( url )
//--
// STRING url	= The URL of the javascript source file.
//--
// If the specified JavaScript file has not alreay been loaded into the current page, it is loaded
// and an entry is made in EXNT_LOADED_JAVASCRIPT so it will not be loaded again.
//-------------------------------
function EXNT_loadJavaScript(url, dhtml) {
	//dhtml = true;
	if(!in_array(url, EXNT_LOADED_JAVASCRIPT)) {
		if(dhtml==null || !dhtml) {
			document.write('<scr'+'ipt type="text/javascript" src="'+url+'"></scr'+'ipt>');
		}
		else {
			var e = document.createElement("script");
			e.src = url;
			e.type="text/javascript";
			document.getElementsByTagName("head")[0].appendChild(e);
		}
		EXNT_LOADED_JAVASCRIPT.push(url);
		return true;
	}
	return false;
}

//-------------------------------
// BOOL EXNT_loadModuleJavaScript( modName, scriptName )
//--
// STRING modName	= Name of the module that provides the required script.
// STRING scriptName	= The name of the script to load.
//--
// Loads the specified JavaScript file into the current page.
// All modules store these global scripts in their "/remote/int/jscript" folder.
//-------------------------------
function EXNT_loadModuleJavaScript(modName, scriptName) {

	// Build URL
	var url = '/mod/'+modName+'/remote/int/jscript/'+scriptName;

	// Load JavaScript
	return EXNT_loadJavaScript(url);
}

//-------------------------------
// VOID EXNT_loadStylesheet( url )
//--
// STRING url	= The URL of the stylesheet source file.
//--
// If the specified Stylesheet file has not alreay been loaded into the current page, it is loaded
// and an entry is made in EXNT_LOADED_STYLESHEET so it will not be loaded again.
//-------------------------------
function EXNT_loadStylesheet(url, dhtml) {
	//dhtml = true;
	if(!in_array(url, EXNT_LOADED_STYLESHEET)) {
		var disable = EXNT_getToggleCssState();
		if(dhtml==null || !dhtml) {
			document.write('<li'+'nk rel="stylesheet" type="text/css" href="'+url+'" />');
		}
		else {
			var e = document.createElement("link");
			e.href = url;
			e.rel = 'stylesheet';
			e.type = "text/css";
			document.getElementsByTagName("head")[0].appendChild(e);
			e.disabled = disable;
		}
		EXNT_LOADED_STYLESHEET.push(url);
		return true;
	}
	return false;
}

//-------------------------------
// VOID EXNT_uploadFiles( form, sid, uploadRedirect, [mainRedirect] )
//--
// HTMLElement form		= The form that contains the files to be uploaded
// STRING sid			= The unique identifier for this process
// STRING uploadRedirect	= URL pointing to the script that will handle the uploaded data once it has been processed by 'upload.cgi'
// STRING mainRedirect		= URL to which the main window will be redirected once the form is submitted (null if you do not want to redirect)
//--
// This function prepares the popup window that will send the specified form through
// the 'upload.cgi' script and display the progress bar that monitors this process.
// Once the 'upload.cgi' script has finished processing the uploaded files it will redirect
// to the 'uploadRedirect' script which handles the actual processing of the remaining form data
// (this URL must include the 'sid' as a parameter).
// The popup window opened by this function is 400x300 pixels, so the page redirection specified
// by uploadRedirect must generate a page that looks ok within these dimensions.
//-------------------------------
function EXNT_uploadFiles(form, sid, uploadRedirect, mainRedirect) {

	// Vars
	var seed = Math.round(Math.random()*1000000);
	var tgt = "EXNT_fileUploadWindow_"+seed;
	var tgtTOP = "EXNT_fileUploadWindowTOP_"+seed;
	var tgtBOT = "EXNT_fileUploadWindowBOT_"+seed;

	// Set form attributes
	// - The order in which the parameters are set in the 'action' is important for 'upload.cgi' to read them correctly.
	form.target = tgtTOP;
	form.action = '/cgi-bin/fileUpload/upload.cgi?sid='+sid+'&uploadRedirect='+escape(uploadRedirect);

	// Prepare popup window that will display the progress bar
	// and results of the upload
	//var win = window.open('', tgt, 'width=400,height=300,scrollbars=yes');
	var win = openPopupWindow(tgt, 400, 300, ['scrollbars=yes'], '');
	win.document.write('<frameset rows="0,*" frameborder="0"><frame name="'+tgtTOP+'">');
	win.document.write('<frame name="'+tgtBOT+'" scrolling="no"></frameset>');

	// Set cookies required by the upload script
	//setCookie('EXNT_fileUploadTmpDir', EXNT_config('dirTemp'), null, '/');

	// Load Progress Bar
	win[tgtBOT].location = '/core/tplElements/fileUpload/progress.php?sid='+sid;

	// Submit form
	form.submit();

	// Redirect main window
	if(mainRedirect!=null) self.location = mainRedirect;
}

//-------------------------------
// void EXNT_submitTinyMCEForm( form )
//--
// HTMLForm form	= Form to submit
//--
// Since adding the TinyMCE WYSIWYG editor, any forms that use
// the JavaScript "form.submit()" function need to first call
// "tinyMCE.triggerSave()" if there are any WYSIWYG instances
// within that form. This function does just that, so use it
// whenever you need to submit a form that may contain TinyMCE instances.
//
// TinyMCE adds an "onsubmit" handler to every form in the page
// automatically, but of course we need to use "form.submit()"
// in some functions which doesn't trigger the "onsubmit" event.
//-------------------------------
function EXNT_submitTinyMCEForm(form) {

	// Save all instances of the TinyMCE editor before submitting form
	var undefined;
	if(typeof tinyMCE!='undefined') tinyMCE.triggerSave();
	form.submit();
}

//-------------------------------
// INT EXT_i18n_timeOffset( [ds] )
//--
// BOOL ds	= If set then this function will return the number of seconds of daylight saving currently in effect
//--
// Returns the number of seconds required to convert the current local time to GMT (or whatever the server time is).
//-------------------------------
function EXNT_i18n_timeOffset(ds) {

	// Get current time
	var Dserver = new Date(EXNT_serverTime);
	var Dclient = new Date();
	var diff = Math.floor(Dserver.getTime()/1000) - Math.floor(Dclient.getTime()/1000);

	// Calculate offset
//alert(unixtime+':'+D.getHours()+':'+EXNT_serverTime);
	return diff;
/*
	// Vars
	if(ds==null) ds = false;

	// Determine if Daylight Saving is in effect
	var now = new Date();
	var date1 = new Date(now.getFullYear(), 0, 1, 0, 0, 0, 0);
	var date2 = new Date(now.getFullYear(), 6, 1, 0, 0, 0, 0);
	var temp = date1.toGMTString();
	var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var temp = date2.toGMTString();
	var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
	var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);
	//var daylightSavingDiff = hoursDiffDaylightTime * 60 * 60;
	var daylightSavingDiff = (hoursDiffDaylightTime - hoursDiffStdTime) * 60 * 60;

	// Return daylight saving offset
	if(ds) return daylightSavingDiff;

	// Result
	var D = new Date();
	return (D.getTimezoneOffset()*60) + daylightSavingDiff;	// This works
	//return (D.getTimezoneOffset()*60) - daylightSavingDiff;
	//return (D.getTimezoneOffset()*60);	// Remove the daylight saving so that times are always stored in 'true' GMT.
*/
}

// Store a cookie holding current timezone offset (in seconds)
// If the cookie name is changed in class.i18n.php then it must also be changed here.
setCookie('EXNT_LOCALE_timeOffset', EXNT_i18n_timeOffset(), null, '/');

//-------------------------------
// VOID EXNT_openObjectSelector( module, action, args )
//--
// STRING module	= Name of the module to load
// STRING action	= Name of the moduleAction to load into this selector window.
// OBJECT args		= Object containg name=value argument pairs (MUST include the 'fn' argument)
//--
// Opens a popup window containg an object selector.
// The 'args' variable can contain any custom arguments and the following system arguments:
//	fn	= [REQUIRED] Name of the JavaScript function to call when the selection has been made
//
//-------------------------------
function EXNT_openObjectSelector(module, action, args) {

	// Vars
	var features = 'width=550,height=420';
	var win_name = 'EXNT_ObjectSelector';

	// Check for required arguments
	if(args.fn==null) {
		alert("Invalid Argument:\n- You must provide an application function name");
		return;
	}

	// Open window
	var url = EXNT_genHREF(module, action, args);
	var win = window.open(url, win_name, features);
	win.focus();
}

/*
# @function void EXNT_toggleCss( [bool state] )
# state	= If TRUE then system should go into accessibility mode.
#
# Sets a cookie that can be used to tell the rest of the system whether or not
# to include CSS sources in a page.
# This is useful for accessibility issues.
# If state is not set, then the current state stored in the cookie will be
# inverted.
*/
function EXNT_toggleCss(state) {
	var undefined;
	var cur = getCookie('EXNT_toggleCssState');
	if(!cur || cur==undefined) {
		cur = false;
	}
	else {
		cur = cur==1 ? true : false;
	}

	state = arguments.length>0 ? state : !cur;

	setCookie('EXNT_toggleCssState', state===true ? 1 : 0, null, '/');

	// Disable/enable CSS links in head
	var cssSources = document.getElementsByTagName('head')[0].getElementsByTagName('link');
	for(var i=0; i<cssSources.length; i++) {
		if(cssSources[i].rel && cssSources[i].rel=='stylesheet') {
			cssSources[i].disabled = state;
		}
	}
}

function EXNT_getToggleCssState() {
	var undefined;
	var c = getCookie('EXNT_toggleCssState');
	if(!c || c===undefined) {
		c = false;
	}
	else {
		c = c==1 ? true : false;
	}
	return c;
}
//-->
