////////////////////////////
// GLOBAL Page Load Functions
////////////////////////////

// PRINT VERSION
// Print Style Sheet is possibly loaded using the /phplib/pageprintcss.php


/*
// CHECK FOR LEAVING SITE
// a few tests

window.unlock = false;

addUnLoadHandler(testthis)

document.onmousedown=function() {
  window.unlock = true;
}

//addLoadHandler(test2)

function test2() {
	var st= "alertMe('test');";
	setTimeout(st,10*1000);
}

function testthis() {

	if(!window.unlock) {
		alertMe("unloack");
	}
	var el=document.activeElement;
	//alertMe("" + el.nodeName + ' ' + window.event.clientX);
	if ( el.nodeName == 'A'){
    if (exit && document.all) {
            if((window.event.clientX<0) || (window.event.clientY<0)){
            } else {
								//alertMe("" + el.nodeName);
            //     window.open("unloader.asp","","height=1,width=1");
            }
    }
  }
}
*/

// SEARCH INPUT BOX
// Default to last search area
///addLoadHandler(testthis);
addLoadHandler(setSearchArea);
function setSearchArea() {
	// Set the Search Area select to what the user has already selected
	var searcharea = GetCookie('SEARCHAREA');
	if (typeof document.forms['frmSearch'] == "object" && typeof document.forms['frmSearch'].searcharea == "object" ) {
		// Search appears to be there, so select an option if possible
		var opt = document.forms['frmSearch'].searcharea;
		var index = 0;
		for (var intLoop = 0; intLoop < opt.length; intLoop++) {
			if (opt[intLoop].value == searcharea) {
				opt[intLoop].selected = true;
			}
		}
	}
}


function popupAcronyms( url ) {
	// Using document.body for height and width, so IE will work
	features = "width=750px";
	features += ",height=550px";
	features += ",menubar=no,toolbar=no,resizable=yes,scrollbars=yes";
	features += ",location=no";
	hdl = window.open( url, "acronym", features );
	hdl.focus();
}

function bookmarksite(title, url){
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "")
}

////////////////////////////
// GLOBAL COMMON 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.onload)
	{
		var oldHandler = window.onload;
		window.onload = function piggyback()
		{
			oldHandler();
			handler();
		};
	}
	else
	{
		window.onload = handler;
	}
}

/**
 * Read the JavaScript cookies tutorial at:
 *   http://www.netspade.com/articles/javascript/cookies.xml
 */

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function SetCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function GetCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function DeleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}


var debugs = '';
// function to only alert the web developer... deluxe debugging ;-)
function alertMe(s) {
	if (DebugIsMe()) {
		alert(s);
	}

	return false;
}

function DebugIsMe() {
	if (typeof REMOTE_ADDR == 'undefined') {
			return false;
		// Not defined
	} else {
		//debugs = debugs + REMOTE_ADDR;
		if (REMOTE_ADDR == "10.18.3.206") {
			return true;
		}
	}

	return false;
}

// Some handy utility functions, found at
// http://www.crockford.com/javascript/remedial.html
function isNull(a) {
    return typeof a == 'object' && !a;
}
function isUndefined(a) {
    return typeof a == 'undefined';
}

/*
 * handy elementary DHTML functions
 */
function toggleVisibility(obj) {
	/*
		purpose of function is to toggle the
		style display of an element. the name
		of the element is passed as obj.
		note that when made visible element
		display style is set to 'block', thus
		if you wish to toggle the visibility
		of inline elements this function will
		need to be modified.
	*/

	// initialisation
	var hide = '';

	if (document.getElementById) {
		// we have a modern dhtml browser
		togObj = document.getElementById(obj);
	} else if (document.all) {
		// it's ok, we can cope with this
		togObj = document.all[obj];
	} else {
		// nothing we can do; no dhtml support
		return false;
	}

	if (togObj.style.display != 'block') { // I test this way because initially the style attribute will have no value
		// make visible
		togObj.style.display = 'block';
	} else {
		// hide
		togObj.style.display = 'none';
	}

	return true;
}

function toggleVisibilityHide(obj) {
	/*
		purpose of function is to toggle the
		style display of an element. the name
		of the element is passed as obj.
		note that when made visible element
		display style is set to 'block', thus
		if you wish to toggle the visibility
		of inline elements this function will
		need to be modified.

		** this version of this function hides
		the element first **
	*/

	// initialisation
	var hide = '';

	if (document.getElementById) {
		// we have a modern dhtml browser
		togObj = document.getElementById(obj);
	} else if (document.all) {
		// it's ok, we can cope with this
		togObj = document.all[obj];
	} else {
		// nothing we can do; no dhtml support
		return false;
	}

	if (togObj.style.display == 'block') { // I test this way because initially the style attribute will have no value
		togObj.style.display = 'none';
	} else if (togObj.style.display == '') {
		// show
		togObj.style.display = 'none';
	} else {
		// hide
		togObj.style.display = 'block';
	}

	return true;
}

/**** WaiLing 161006 to pass in the title and url to the feedback form ****/
function submitFeedback () {
	//var url = 'http://' + window.location.hostname + window.location.pathname;
	var url = window.location.href;
	var urlTidy = '';
	for (i=0,n=url.length;i<n;i++) {
		if (url.charAt(i) == '&') {
			urlTidy += '%26';
		}
		else {
			urlTidy += url.charAt(i);
		}
	}
	var pageTitle = new String (document.title);
	pageTitle = pageTitle.replace(/&/g, "and");     /*replace '&' with 'and'*/
	pageTitle = pageTitle.replace(/\W/g, "+");		/*replace non-alphanumeric with '+'*/
	window.location.href="/website/feedback.php?topic=" + pageTitle + "&url=" + urlTidy;
}

/***
//  code by Alan Dix 2004   http://www.meandeviation.com/
//  you are free to use, copy, or distribute this code so long as this notice
//  is included in full and any modifications clearly indicated
//  16/10/2006 changed title
***/
function email_addr(name,host,isLink,otherName) {
	var email = name + "@" + host;
	var linktext = email;   // text to display within link
	if (otherName) {
		linktext = otherName;
		isLink = 1;  // only makes sense for live link
	}
	if ( isLink ) document.write("<a title=\"Click here to send an email\" href=\"mailto:"
+ email + "\">");
	document.write(linktext);
	if ( isLink ) document.write("</a>");
	document.close();
}

/* To conduct a simple fields checking (not empty) in a <form>.
   To use this function, the <form> must have a hidden input field name "required"
   and the value will be all the fields name that required checking (seperated with comma).
*/
function checkValidity( frm ) {
	var i = 0;
	var f = 0;
	for(i=0; i<frm.length; i++) {
		//To get the required field
		if(frm.elements[i].name == 'required') {
			requiredField = frm.elements[i].value;
			break;
		}
	}

	if(requiredField != '') {
		//Split the required field
		requiredarray = requiredField.split(",");
		for(f=0; f<requiredarray.length; f++) {
			//To trim the field before passing to checkEmpty
			if( checkEmpty(requiredarray[f].replace(/^\s+|\s+$/g,""), frm ) == false ) {
				//document.getElementById('warning').style.display='inline';
				alert("Error - please make sure that all the compulsory fields are occupied");
				return false;
			}
		}
	}

	//to confirm submission
	if (confirm("Submit form?\r\n\r\nClick OK to submit or Cancel to continue editing.")) {
		return true;
	}
	else {
		return false;
	}
	/*return true;*/
}

/* WaiLing - To check whether a field in the <form> is empty */
function checkEmpty(field, frm) {
	var i = 0;
	for(i=0; i<frm.length; i++) {
		if(frm.elements[i].name == field){
			if(frm.elements[i].value == '') {
				return false;
			}
			else {
				return true;
			}
		}
	}
	return true;
}

/* WaiLing - To do a simple email checking */
function checkEmail( control ) {
	if( typeof( control.type ) == 'string' ) {
		if (control.value == 'enter changed email address if appropriate') return true;
		val = control.value.replace(/^\s+|\s+$/g,"");
		if( val != '' ){
			re = /^[^\s\@]+\@[^\s\@]+\.[^\s\@]+$/;
			result = re.test( val );
			if( result ) {
				return true;
			}
			else {
				alert("Error - invalid email address");
				control.focus();
				return false;
			}
		}
	}

	return false;
}

function openDoc( url ) {
	hdl = window.open( url, 'document', 'width=800,height=600,scrollbars=yes,resizable=yes,menubar=yes' );
	hdl.focus();
}

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 objId = document.getElementById(strId);

	var imgUp = '';
	var imgDown = '';

	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

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

	// check for optional specified state
	if (strState===undefined) { // no optional state specified
		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
			objId.style.display = 'block';
			if (objButton) { // button object exists
				objButton.src = imgUp;
			}
		} else { // hide element and button
			objId.style.display = 'none';
			if (objButton) { // button object exists
				objButton.src = imgDown;
			}
		}
	}

	return;
}// function toggle

function toggleWIT(strId) {
	/*
	 * Versatile toggle function, takes id of element to toggle it's display: block/none
	 *
	 * Looks for another element with the id '_whatisthis' + strId to switch its display style
	 */

	var objId = document.getElementById(strId);

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

	var objToggleLink = document.getElementById(strId + '_whatisthis');

	if (objId.style.display == 'none') { // show element
		objId.style.display = 'block';
		objToggleLink.style.display = 'none';
	} else { // hide element
		objId.style.display = 'none';
		objToggleLink.style.display = 'block';
	}

	return false;
}

function togglebtn(strId, imgUrl) {
	/*
	 * 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
	 *
	 */

	objId = document.getElementById(strId);

	var imgUp = '';
	var imgDown = '';

	if (!imgUrl) { // no image supplied, use default
		imgUp = '/images/collapse.gif';
		imgDown = '/images/expand.gif';
	} else { // use image supplied
		imgUp = imgUrl + 'collapse.gif';
		imgDown = imgUrl + 'expand.gif';
	}

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

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

	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;
		}
	}

	return;
}

function openPhcred( url ) {
	result = confirm('This action will take you to the PHCRED strategy section of our website. Click OK if you would like to know more about PHCRED strategy. Cancel to stay in this page.');
	if ( result ) {
		//openDoc( url );
		window.open( url, '_self');
	}
	return;
}

function openAccessJournal( url ) {
	result = confirm('This action will take you to PHC RIS infobytes - Accessing journal articles in our website. Click OK if you would like to know more about Open Access Journal. Cancel to stay in this page.');
	if ( result ) {
		//openDoc( url );
		window.open( url, '_self');
	}
	return;
}

function openContentSuggestion( url ) {
	result = confirm('This action will take you to eBulletin content suggestion form. Click OK if you would like to suggest an item to be included in a future edition of eBulletin. Cancel to stay in this page.');
	if ( result ) {
		//openDoc( url );
		window.open( url, '_self');
	}
	return;
}
