/* DB: disabled 21032011 (triggering javascript errors in firefox/firebug)
// For browswers that don't have Firebug installed
// handle calls to Firebug console command, otherwise get an error (especially in IE)
// Credit to: http://ajax-prototype.blogspot.com/2006/12/workaround-to-make-firebug-consolelog.html
if (console && console.log) try {
	console.assert(1);
	} catch(e) {
		console = {
		log: function() {},
		debug: function() {},
		info: function() {},
		warn: function() {},
		error: function() {},
		assert: function() {},
		dir: function() {},
		dirxml: function() {},
		trace: function() {},
		group: function() {},
		groupCollapsed: function() {},
		groupEnd: function() {},
		time: function() {},
		timeEnd: function() {},
		profile: function() {},
		profileEnd: function() {},
		count: function() {},
		exception: function() {},
		table: function() {}
	}
}*/

function diosPopUpDefs( ) {
	// Open help window
	url = "/dios/help/definitions.php";
	hdl = window.open( url, 'defs', 'width=500,height=600,scrollbars=yes,resizable=yes' );
	hdl.focus();
}

function diosPopUpHelp(  ) {
	// Open help window
	url = "/dios/help/";
	hdl = window.open( url, 'help', 'width=850,height=550,scrollbars=yes,resizable=yes,toolbar=yes' );
	hdl.focus();
}

function diosGo( dst ) {
	// Optional Params = action, params
	result = true;

	// Confirmation required for delete
	if( ( arguments.length > 1 ) && (arguments[1] == 'delete') ) {
		result = confirm('Are you sure you want to permanantly delete this user?');
	}

	// Confirmation required for delete division - WaiLing 101006
	if( ( arguments.length > 1 ) && (arguments[1] == 'deleteDiv') ) {
		result = confirm('Are you sure you want to permanantly delete this division?');
	}

	if( result ) {
		document.diosAdmin.pageDst.value = dst;
		if( arguments.length > 1 ) {
			document.diosAdmin.action.value = arguments[1];
			if( arguments.length > 2 ) {
				document.diosAdmin.params.value = arguments[2];
			}
		}
		document.diosAdmin.submit();
	}
}

function showHide( _id ) {
	if( (obj = document.getElementById( _id )) ) {
		if( typeof(obj.style.display) == 'string' ) {
			if( obj.style.display == 'none' ) {
				obj.style.display = 'inline';
			} else {
				obj.style.display = 'none';
			}
		}
	}
}

function setTickCross( val, imgName ) {
	if( val ) {
		document.images[imgName].src = '/dios/images/tick.gif';
	} else {
		document.images[imgName].src = '/dios/images/cross.gif';
	}
}

function validateNotEmpty( val, imgName ) {
	if( val == '' ) {
		result = false;
	} else {
		result = true;
	}
	setTickCross( result, imgName );
	return result;
}

function validateEmail( val, imgName ) {
	re = /^[^\s\@]+\@[^\s\@]+\.[^\s\@]+$/;
	result = re.test( val );
	setTickCross( result, imgName );
	return result;
}

function validatePwd( val, imgName ) {
	str = new String( val );
	if( str.length < 6 ) {
		result = false;
	} else {
		result = true;
	}
	setTickCross( result, imgName );
	return result;
}

function validateSame( val1, val2, imgName ) {
	if( val1 == val2 ) {
		result = true;
	} else {
		result = false;
	}
	setTickCross( result, imgName );
	return result;
}

function validateState (val, imgName, NotSet){
	if (val == NotSet){
		result = false;
	} else {
		result = true;
	}
	setTickCross( result, imgName );
	return result;
 }

//WaiLing 310806 - add to alert user to submit the survey
function pleaseSubmit(){
	//alert("You have 100% completed the survey. Can you please kindly submit your completed responses. Thank you.");
	//document.getElementById('survey_finished').style.display='block';
//alert('100%');
	document.getElementById('survey_finished_text').style.display='inline';
	return;
}
//End WaiLing 310806

function diosPopUpPrint ( frm ){
	for (i=0; i<document.diosPrintStyle.print_style.length; i++) {
		if (document.diosPrintStyle.print_style[i].checked) {
			frm.style.value = document.diosPrintStyle.print_style[i].value;
			//alert(frm.style.value);
		}
	}

	if(frm.style.value != "rtf") {
		var w = window.open('about:blank','Popup_Window', 'width=920,height=550,scrollbars=yes,menubar=yes,resizable=yes');
		frm.target = 'Popup_Window';
		if (window.focus) { w.focus() }
	}
	else {
		frm.target = '';
	}
	return true;

}

function diosPopUpPrintPreview ( frm ) {
	if(frm.style.value == "web") {
		var w = window.open('about:blank','Popup_Window', 'width=920,height=550,scrollbars=yes,menubar=yes,resizable=yes');
		frm.target = 'Popup_Window';
		if (window.focus) { w.focus() }
	}
	else {
		frm.target = '';
	}
	return true;
}

function autoSuggestCode (control, codeName) {
	frm = control.form;
	code = "";
	arrayOfStrings = control.value.split(" ");
	for (var i=0; i < arrayOfStrings.length; i++) {
		code = code + arrayOfStrings[i].charAt(0);
	}
	for (var a = 0; a < frm.length; a++) {
		if(frm.elements[a].name == codeName){
			frm.elements[a].value = code.toUpperCase();
			//frm.elements[a].focus();
			break;
		}
	}
	return;
}

function displayCustPrintOpt () {
	document.getElementById('customisePrintPlan').style.display='inline';
	document.getElementById('CustPrintOptionLink').style.display='none';
}

function hideCustPrintOpt () {
	document.getElementById('customisePrintPlan').style.display='none';
	document.getElementById('CustPrintOptionLink').style.display='inline';
}

function displayCustSAOpt () {
	document.getElementById('customisePrintSA').style.display='inline';
	document.getElementById('CustSAOptLink').style.display='none';
}

function hideCustSAOpt () {
	document.getElementById('customisePrintSA').style.display='none';
	document.getElementById('CustSAOptLink').style.display='inline';
}

function displayPrintLandscape () {
	alert('This document is best printed on a LANDSCAPE page.\n\nSelect the "File" menu and "Page Setup" to select LANDSCAPE. Then select "File" and "Print".\n\nClick OK to continue...');
	return;
}

function displayPrintPortrait () {
	alert('This document is best printed on a PORTRAIT page.\n\nSelect the "File" menu and "Page Setup" to select PORTRAIT (if necessary). Then select "File" and "Print".\n\nClick OK to continue...');
	return;
}

function displayOutputFormatInfo () {
	document.getElementById('OutputFormatInfo').style.display='inline';
	document.getElementById('OutputFormatInfoLink').style.display='none';
}

function hideOutputFormatInfo () {
	document.getElementById('OutputFormatInfo').style.display='none';
	document.getElementById('OutputFormatInfoLink').style.display='inline';
}


/**
 * AJAX functions
 */

function getComponentStatusPR() {
	/**
	 * Retrieve all components' progress via ajax call
	 */
	flagPRDone = 0; // flag to store 1 when PR results have been returned to the callback function
	flagPR2Done = 0; // flag to store 1 when PR2 results have been returned to the callback function
	divProgress = ''; // to store final contents of progress div
	divCompleted = ''; // to store final contents of completed div
	divArchived = ''; // to store final contents of archived div

	// header html for status functions
	headerProgress = '<div class="statusTable"><p><nomarkup><b>Current items requiring completion or action:</b></nomarkup></p><table class="startlist">';
	headerCompleted = '<div class="statusTable"><p><nomarkup><b>Recently submitted or approved items:</b></nomarkup></p><table class="startlist">';
	headerArchived = '<div class="statusTable"><p class="cursor-link" onclick="toggle(\'archivedItemsList\', \'/dios/images/menu/expand\')"><nomarkup><img id="archivedItemsListButton" class="cursor-link" alt="[+]" src="/dios/images/menu/expandDown.gif"/>&nbsp;<b>Archived items:</b> (click to toggle)</nomarkup></p><table id="archivedItemsList" class="startlist" style="display: none;">';

	// footer html for status functions
	footerProgress = '</table></div>';
	footerCompleted = '</table></div>';
	footerArchived = '</table></div>';

	// add reload link
	$('#reload-link').html('<a id="reload-button" href="/dios/admin.php">Start Performing Tasks as New Organisation</a>');
	$('#reload-button').button();

	strRequest = '/dios/ajaxGetItemStatus.php';

	sendRequest(strRequest, getComponentStatusPR_Callback);
}

function getComponentStatusPR_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	var statusInProgress = ''; // to store in progress status
	var statusCompleted = ''; // to store completed status
	var statusArchived = ''; // to store archived status

	s = req.responseText;

	flagPRDone = 1; // flag PR results as returned

	// split result string into array elements
	var arrResults = s.split('$$$$$');

	// spin through results array
	for (i = 0; i < arrResults.length; i++) {
		var ss = arrResults[i];
		if (ss.length > 1) { // we have results - trim off first character
			switch (i) {
				case 0: // in progress
					statusInProgress = (ss.substring(1)); // trim first character (']')
					break;

				case 1: // completed
					statusCompleted = (ss.substring(1)); // trim first character (']')
					break;

				case 2: // archived
					statusArchived = (ss.substring(1)); // trim first character (']')
					break;
			}
		}
	}

	getObj('inProgressItems'); // select report progress object
	if (flagPR2Done) { // PR2 results returned already - add PR results at the beginning of the element contents and add footer
		divProgress = (headerProgress + divProgress + statusInProgress + footerProgress);
	} else { // PR2 results not yet returned - clear contents of element
		divProgress = (statusInProgress); // replace contents of element
	}

	getObj('completedItems'); // select report progress object
	if (flagPR2Done) { // PR2 results returned already - add PR results at the beginning of the element contents and add footer
		divCompleted = (headerCompleted + divProgress + divCompleted + footerCompleted); // replace contents of element
	} else { // PR2 results not yet returned - clear contents of element
		divCompleted = (statusCompleted); // replace contents of element
	}

	getObj('archivedItems'); // select report progress object
	if (flagPR2Done) { // PR2 results returned already - add PR results at the beginning of the element contents and add footer
		divArchived = (headerArchived + divArchived + statusArchived + footerArchived); // replace contents of element
	} else { // PR2 results not yet returned - clear contents of element
		divArchived = (statusArchived); // replace contents of element
	}

	getComponentStatusPR2();
}

function getComponentStatusPR2() {
	/**
	 * Retrieve all components' progress via ajax call
	 */
	strRequest = '/dios/ajaxGetItemStatus2.php';

	sendRequest(strRequest, getComponentStatusPR2_Callback);
}

function getComponentStatusPR2_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	var statusInProgress = ''; // to store in progress status
	var statusCompleted = ''; // to store completed status
	var statusArchived = ''; // to store archived status

	s = req.responseText;

	flagPR2Done = 1; // flag PR2 results as returned

	// split result string into array elements
	var arrResults = s.split('$$$$$');

	// spin through results array
	for (i = 0; i < arrResults.length; i++) {
		var ss = arrResults[i];
		if (ss.length > 1) { // we have results - trim off first character
			switch (i) {
				case 0: // in progress
					statusInProgress = (ss.substring(1)); // trim first character (']')
					break;

				case 1: // completed
					statusCompleted = (ss.substring(1)); // trim first character (']')
					break;

				case 2: // archived
					statusArchived = (ss.substring(1)); // trim first character (']')
					break;
			}
		}
	}

	if (flagPRDone) { // PR results returned already - add PR2 results at the beginning of the element contents and add footer
		divProgress = (headerProgress + statusInProgress + divProgress + footerProgress);
	} else { // PR2 results not yet returned - clear contents of element
		divProgress = (statusInProgress); // replace contents of element
	}

	if (flagPRDone) { // PR results returned already - add PR2 results at the beginning of the element contents and add footer
		divCompleted = (headerCompleted + statusCompleted + divCompleted + footerCompleted); // replace contents of element
	} else { // PR2 results not yet returned - clear contents of element
		divCompleted = (statusCompleted); // replace contents of element
	}

	if (flagPRDone) { // PR results returned already - add PR2 results at the beginning of the element contents and add footer
		divArchived = (headerArchived + statusArchived + divArchived + footerArchived); // replace contents of element
	} else { // PR2 results not yet returned - clear contents of element
		divProgress = (statusArchived); // replace contents of element
	}

	 // write div contents
	 getObj('inProgressItems'); // select report progress object
	 obj.innerHTML = divProgress; // write div contents
	 getObj('completedItems'); // select report progress object
	 obj.innerHTML = divCompleted; // write div contents
	 getObj('archivedItems'); // select report progress object
	 obj.innerHTML = divArchived; // write div contents
}

////////////////////////////
// GENERAL FUNCTIONS
////////////////////////////

function addLoadHandler(handler)
{
	if(window.addEventListener)
	{
		window.addEventListener("load",handler,false);
	}
	else if(window.attachEvent)
	{
		window.attachEvent("onload",handler);
	}
	else if(window.onload)
	{
		var oldHandler = window.onload;
		window.onload = function piggyback()
		{
			oldHandler();
			handler();
		};
	}
	else
	{
		window.onload = handler;
	}
}

function addUnloadHandler(handler)
{
	if(window.addEventListener)
	{
		window.addEventListener("unload",handler,false);
	}
	else if(window.attachEvent)
	{
		window.attachEvent("onunload",handler);
	}
	else if(window.onunload)
	{
		var oldHandler = window.onunload;
		window.onunload = function piggyback()
		{
			oldHandler();
			handler();
		};
	}
	else
	{
		window.onunload = handler;
	}
}

function getElementsByTagNames(list, obj) {
	if (!obj) obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}

function toggle(strId, imgUrl, strState) {
	/*
	 * Versatile toggle function, takes id of element to toggle it's display: block/none
	 *
	 * Looks for another element with the id 'button' + strId to switch its src property
	 * between /dios/images/arrowDown.gif (hidden) and /dios/images/arrowUp.gif (visible)
	 * (or a custom image may be supplied to imgUrl as full image URL without filename
	 * extension, and will toggle between imgUrl + 'Up.gif' and imgUrl + 'Down.gif')
	 *
	 * example is of an element which will start hidden
	 *
	 * example - button:
	 * <img id="indMoreDetailsButton" src="/dios/images/expandDown.gif" onclick="toggle('indMoreDetails', '/dios/images/menu/expand');" class="cursor-link"/>
	 *
	 * example - element to toggle:
	 * <div id="indMoreDetails" class="item_text" style="display: none;">
	 *
	 * strState		- optional, may be one of 'show' or 'hide' to set the display style of the element and button
	 */

	var imgUp = '';
	var imgDown = '';
	var objId = document.getElementById(strId);
	if (!imgUrl) { // no image supplied, use default
		imgUp = '/dios/images/arrowUp.gif';
		imgDown = '/dios/images/arrowDown.gif';
	} else { // use image supplied
		imgUp = imgUrl + 'Up.gif';
		imgDown = imgUrl + 'Down.gif';
	}

	if (!objId) return false; // unable to load element

	objButton = document.getElementById(strId + 'Button');

	// check for optional specified state
	if (strState===undefined) { // no optional state specified
		// toggle element state using jquery fast slide
		if ($('#' + strId).is(':hidden')) {// show element, up arrow
			$('#' + strId).slideDown('fast');// show
			if (objButton) { // button object exists
				objButton.src = imgUp;
			}
		} else {// hide element, down arrow
			$('#' + strId).slideUp('fast');// hide
			if (objButton) { // button object exists
				objButton.src = imgDown;
			}
		}
		/*if (objId.style.display == 'none') { // show element, up arrow
			objId.style.display = 'block';
			if (objButton) { // button object exists
				objButton.src = imgUp;
			}
		} else { // hide element, down arrow
			objId.style.display = 'none';
			if (objButton) { // button object exists
				objButton.src = imgDown;
			}
		}*/
	} else { // optional state specified
		if (strState == 'show') { // show element and button
			$('#' + strId).slideDown('fast');// show
			/*objId.style.display = 'block';*/
			if (objButton) { // button object exists
				objButton.src = imgUp;
			}
		} else { // hide element and button
			$('#' + strId).slideUp('fast');// hide
			/*objId.style.display = 'none';*/
			if (objButton) { // button object exists
				objButton.src = imgDown;
			}
		}
	}

	return false;
}// function toggle

function toggleShow(strId, imgUrl, strState) {
	/*
	 * Versatile toggle function, takes id of element to toggle it's display: block/none
	 *
	 * Differs to toggle function by using a different jQuery 'show' method
	 *
	 * Looks for another element with the id 'button' + strId to switch its src property
	 * between /dios/images/arrowDown.gif (hidden) and /dios/images/arrowUp.gif (visible)
	 * (or a custom image may be supplied to imgUrl as full image URL without filename
	 * extension, and will toggle between imgUrl + 'Up.gif' and imgUrl + 'Down.gif')
	 *
	 * example is of an element which will start hidden
	 *
	 * example - button:
	 * <img id="indMoreDetailsButton" src="/dios/images/expandDown.gif" onclick="toggle('indMoreDetails', '/dios/images/menu/expand');" class="cursor-link"/>
	 *
	 * example - element to toggle:
	 * <div id="indMoreDetails" class="item_text" style="display: none;">
	 *
	 * strState		- optional, may be one of 'show' or 'hide' to set the display style of the element and button
	 */

	var imgUp = '';
	var imgDown = '';
	var objId = document.getElementById(strId);

	if (!imgUrl) { // no image supplied, use default
		imgUp = '/dios/images/arrowUp.gif';
		imgDown = '/dios/images/arrowDown.gif';
	} else { // use image supplied
		imgUp = imgUrl + 'Up.gif';
		imgDown = imgUrl + 'Down.gif';
	}

	if (!objId) return false; // unable to load element

	objButton = document.getElementById(strId + 'Button');

	// check for optional specified state
	if (strState===undefined) { // no optional state specified
		// toggle element state using jquery fast slide
		if ($('#' + strId).is(':hidden')) {// show element, up arrow
			$('#' + strId).show('fast');// show
			if (objButton) { // button object exists
				objButton.src = imgUp;
			}
		} else {// hide element, down arrow
			$('#' + strId).slideUp('fast');// hide
			if (objButton) { // button object exists
				objButton.src = imgDown;
			}
		}
	} else { // optional state specified
		if (strState == 'show') { // show element and button
			$('#' + strId).show('fast');// show
			if (objButton) { // button object exists
				objButton.src = imgUp;
			}
		} else { // hide element and button
			$('#' + strId).slideUp('fast');// hide
			if (objButton) { // button object exists
				objButton.src = imgDown;
			}
		}
	}

	return false;
}// function toggleShow

// cookie functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function getElementsByClassName(oElm, strTagName, strClassName) {
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all :
	oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++) {
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)) {
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements);
}

function viewProfile( orgnum ) {
	// Open organisation profile
	url = "/divisions/profiles/detail.php?div=" + orgnum;
	hdl = window.open( url, 'Division Profile', 'width=850,height=550,scrollbars=yes,resizable=yes,toolbar=yes' );
//IE doesn't like window.open??????
	hdl.focus();
}
