function changeDisplayStyle(targetId, toWhat)
{
	var target=document.getElementById(targetId);
	if (target)
	{
		target.style.display=toWhat;
	}
	else
	{
		alert("Element with Id " + targetId + " does not exist");
	}
}
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

//
// onLoadPageHeight()
// Adjusts lcol's height to extend it to the bottom of the viewport
//

var eventTooltips = "no";
var containingRecords = "no";

function onLoadPageHeight() {
	var e;
	
	if(document.getElementById("lcol")) {
		e = document.getElementById("lcol");
	} else {
		e = document.getElementById("mcol");
	}

	var page = getPageSize();
	var currWinHeight = parseInt(page[1]);

	if(e) {
	// masthead height, footer height, nav_links height, IE constant (FF ignores
	// it, sort of)
		var newHeight = currWinHeight - (81 + 60 + 35 + 17);

		e.style.height = newHeight + "px";
	}
		
	if ( eventTooltips === 'yes')
		createTooltips();
	if ( containingRecords == 'yes')
		addContainingRecords();
}

var eventTooltips="no";
var containingRecords="no";

/* The new onLoadPageHeight function. The parameter is the height of the
   decorative parts (header footer etc). If you don't specify it, the
   function gives an estimate. In the body attribute of the company home
   page the function is named with a parameter of 161 - that makes it
   fill the window accurately.
*/

function onLoadPageHeight2( decoration ) 
{
	if ( decoration == undefined)
		decoration = 210;
		
	var e = document.getElementById("betweenHeaderAndFooter");
	if ( ! e)
		return;

	var page = getPageSize();
	var currWinHeight = parseInt(page[1]);

	if(e) {
	// masthead height, footer height, nav_links height, IE constant (FF ignores
	// it, sort of)
		var newHeight = currWinHeight - decoration;
		if ( e.offsetHeight < newHeight)
			e.style.height = newHeight + "px";
	}
}

/* an unsuccessful attempt to solve the issues with dynamic page height changes
   - to be continued
function onLoadPageHeight2( decoration ) 
{
	if ( decoration == undefined)
		decoration = 210;
		
	var e = document.getElementById("betweenHeaderAndFooter");
	if ( ! e)
		return;
		
	var e2 = document.getElementById("betweenHeaderAndFooter2");
	if ( ! e2)
		return;

	var page = getPageSize();
	var currWinHeight = parseInt(page[1]);

	alert( e.offsetHeight + "===" + e2.offsetHeight);
	alert( e.style.height + "===" + e2.style.height);

	if(e) {
	// masthead height, footer height, nav_links height, IE constant (FF ignores
	// it, sort of)
		var newHeight = currWinHeight - decoration;
		if ( e2.offsetHeight < newHeight)
			e.style.height = newHeight + "px";
		else
		{
			var bighe = (e2.offsetHeight) + "px";
			alert( bighe)
			e.style.height = bighe; 
		}
	}
}
*/   

function setValue(targetId, value)
{
	var target=document.getElementById(targetId);
	if (target)
	{
		target.value=value;
	}
	else
	{
		alert("Element with Id " + targetId + " does not exist");
	}
}


function getValue(targetId)
{
	var target=document.getElementById(targetId);
	if (target)
	{
		return target.value;
	}
	else
	{
		alert("Element with Id " + targetId + " does not exist");
	}
}

function setInnerHTML(targetId, value)
{
	var target=document.getElementById(targetId);
	if (target)
	{
		target.innerHTML = value;
	}
	else
	{
		alert("Element with Id " + targetId + " does not exist");
	}
}

function openPopup(location, height, width) {
	window.open(location, 'popup',"toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=" + width + ",height=" + height);
}

var d = new Date();
var curr_day = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();

// this function is used to get rid of the greyed out helper text
function clearDefaultText(field)
{
	field.style.color="#000000";
	field.value="";
}

function resizeOuterTo(w,h)
{
	if (parseInt(navigator.appVersion)>3)
	{
		if (navigator.appName=="Netscape")
		{
			top.outerWidth=w;
			top.outerHeight=h;
		}
		else top.resizeTo(w,h);
	}
}

function isEmpty(val)
{
	if (val == null || val == "")
	{
		return true;
	}
	return false;
}

function isValidPassword(password)
{
	var minLength = 6;
	var actualLength = password.length;
	if (actualLength < minLength)
	{
		return false;
	}
	return true;
}

function openWindow(url, width, height)
{
	newWin = window.open(url,'newWin','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' + width + ',height=' + height + '');
	newWin.focus();
}

function disableField(fieldId)
{
	var field = document.getElementById(fieldId);
	field.readOnly = true;
	field.style.backgroundColor = "#F2F2F2";
	field.style.color = "#696969";
}

function isValidDate(date)
{
	if(date.length != 10)
	{
		return false;
	}
	var year = date.substr(0,4);
	var month = date.charAt(5) + date.charAt(6);
	var day = date.substr(8,9);

	var firstSeparator = date.charAt(4);
	var secondSeparator = date.charAt(7);

	if (firstSeparator != "-")
	{
		return false;
	}

	if (secondSeparator != "-")
	{
		return false;
	}

	if (year < 1900 || year > 2500)
	{
		return false;
	}
	if (month == 00 || month > 12)
	{
		return false;
	}
	if (day == 0 || day > 31)
	{
		return false;
	}
	return true;
}
function clearDefaultText(field)
{
	if (field.className=="defaultFieldText")
	{
		field.value="";
	}
}

function isAllowableFileExtension(file)
{
	var allowableExtensions=new Array("pdf","doc","txt");
	var actualExtension = file.substring((file.length-3),file.length);
	var foundIt = false;
	for ( var i = 0; i < allowableExtensions.length; i++ )
	{
		if (allowableExtensions[i] == actualExtension)
		{
			foundIt = true;
		}
	}
	return foundIt;
}



function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

var requiredFieldIds = [];

function makeFieldRequired(fieldId)
{
	requiredFieldIds.push(fieldId);
}

var publicDomains = new Array("gmail.com", "googlemail.com", "yahoo.com ", "msn.com", "hotmail.com", "mac.com", "aol.com", "yahoo.ca");

function getNiceListValidEmailDomains()
{
	var str;
	for(var i = 0; i < publicDomains.length; i++)
	{
		str = str + publicDomains[i];
		if (i != (publicDomains.length - 1))
		{
			str = str + ", ";
		}
	}
	return str;
}

function isInvalidEmailDomain(email) 
{
    
    // Split the user's email address on '@' to get user and domain
    var userEmail = email.split('@');

    // Iterate through the array with a loop to check if the user's domain matches a public domain 
    for(var i = 0; i < publicDomains.length; i = i + 1) {
        if(userEmail[1] == publicDomains[i]) {
            // Match found, return true
            return true;
        }
    }
    // Return false unless found 
    return false;    
} 

var leaveQuietly = false;

function leaveWoWarning()
{
	leaveQuietly = true;
}

function leaveWithWarning()
{
	leaveQuietly = false;
}


function leavePage()
{

	if ( leaveQuietly)
		return;
		
	var changes = false;
	
	for ( ix in formValues) {
		if ( valuesChanged( ix)) {
			changes = true;
			break;
		}		
	}
	
	if ( changes) 
		return "If you leave this page now, you'll lose all your changes";
		
}

function showPleaseWait( div)
{
	var div = document.getElementById( div);
	div.innerHTML=pleaseWait;
}

function validate(requiredFields) {
	var hasMissingFields=false;
	for(var i=0; i<requiredFields.length; i++) {
		if("string"==typeof requiredFields[i]) {
			var field = $(requiredFields[i]);
			if(field!=null&&isEmpty(field.value)) {
				hasMissingFields=true;
				field.className="missingValueField";
			}
		} 
	}
	if(!hasMissingFields) return true;
	alert("One or more required fields need to be filled in before proceeding");
	return false;
}

function validateFormFields(requiredFields)
{
	var hasMissingFields=false;
	for(var i = 0; i < requiredFields.length; i++) 
	{
		if("string" == typeof requiredFields[i]) 
		{
			var field = $(requiredFields[i]);
			if(field!=null && isEmpty(field.value)) 
			{
				hasMissingFields=true;
				field.className="missingValueField";
			}
		} 
	}
	if(!hasMissingFields) 
		return true;
	else
		return false;
}

function checkInvalidEmailFormat(pEmail)
{
	var hasInvalidEmailFormat = false;
	var email = getField(pEmail);
	if (!isEmpty(email.value))
	{
		if (!isValidEmail(email.value))
		{
			email.className="invalidEmailField";
			hasInvalidEmailFormat=true;
		}
	}
	return hasInvalidEmailFormat;
}

function checkHasErrors(errorMsg, hasErrors, divId){

	if(hasErrors)
		{
			toggleOn(divId);
			document.getElementById(divId).innerHTML = errorMsg;
			return false
		}	
		else
		{		
			document.getElementById(divId).innerHTML = "";
			toggleOff(divId);
			return true;
		}
}

function checkFieldsEquals(pOne, pTwo)
{

	var equals = true;
	
	var one = getField(pOne);
	var two = getField(pTwo)

	if (!isEmpty(one.value) && !isEmpty(two.value))
	{
	
		if (one.value != two.value)
		{
			setFieldsInvalid(one, two);
			equals = false;
		}
	}
	
	return equals;
}

function setFieldsInvalid(one, two)
{
	one.className="invalidField";
	two.className="invalidField";
}

function createURLFromForm(pForm, formHandler){
	var params = "";
		var form = document.getElementById(pForm);
		for(i=0; i<form.elements.length; i++)
		{
		   var fieldName = form.elements[i].name;
		   var fieldValue = form.elements[i].value;
	
		   params += fieldName + '=' + fieldValue + '&';
		}
	
	url = formHandler + "?" + params;
	return url;
}

function printDiv(divId, printCSSUrl)
{
	var headerDiv = getField("printHeader");
	var footerDiv = getField("printFooter");
	var printDiv = getField(divId);
	var printable=window.open();
	printable.document.write("<link type=\"text/css\" href=\"" + printCSSUrl + "\" rel=\"stylesheet\">");
	if(headerDiv != null)
	{
		printable.document.write("<div id=\"header\" style=\"width:100%;\">");
		printable.document.write(headerDiv.innerHTML);
		printable.document.write("</div>");
	}
	printable.document.write("<div id=\"mainContent\" style=\"width:100%;\">");
	printable.document.write(printDiv.innerHTML);
	printable.document.write("</div>");
	
	if(footerDiv != null)
	{
		printable.document.write("<div id=\"footer\" style=\"width:100%;\">");
		printable.document.write(footerDiv.innerHTML);
		printable.document.write("</div>");
	}
	printable.print();
	printable.document.close();
	
}

function imposeMaxLength(field,maxChars)
 {
       if(field.value.length >= maxChars) {
          event.returnValue=false; 
          //alert("More than " +maxChars + " chars");
          return false;
       }

 }  

 function imposeMaxLengthPaste(field,maxChars)
 {
       event.returnValue=false;
       if((field.value.length +  window.clipboardData.getData("Text").length) > maxChars) {
         //alert("more than " +maxChars + " chars");
         return false;
       }
       event.returnValue=true;
 }

/* Used in those Facebook styled pages to open and close sections with a given div id, 
   cooperating with the openingDivHeader.jsp include file 
*/

 function openSection( divId)
 {
 	changeDisplayStyle( divId, '');
 	changeDisplayStyle( divId + 'OpenDiv', 'none');
 	changeDisplayStyle( divId + 'CloseDiv', '');
 }
 
 function closeSection( divId)
 {
 	changeDisplayStyle( divId, 'none');
 	changeDisplayStyle( divId + 'OpenDiv', '');
 	changeDisplayStyle( divId + 'CloseDiv', 'none');
 }
 
 function getSelectedIdFromSelectMenu(selectMenuId)
{
	var menu = document.getElementById(selectMenuId);
	for (var i=0; i < menu.length; i++)
	{
		if(menu.options[i].selected)
			return menu.options[i].value;
	}
}

function removeOptionFromSelectMenu(selectMenuId, optionValue)
{
	var menu = document.getElementById(selectMenuId);
	for (var i=0; i < menu.length; i++)
	{
		if(menu.options[i].value == optionValue)
			menu.remove(i);
	}
}

function addOptionToSelectMenu(selectMenuId, optionValue, optionText)
{
	var menu = document.getElementById(selectMenuId);
	var rpOption = document.createElement('option');
	rpOption.text = optionText;
	rpOption.value = optionValue;
	try 
	{
		menu.add(rpOption, null); // standards compliant; doesn't work in IE
	}
	catch(ex) 
	{
		menu.add(rpOption); // IE only
	}
}


function stepBack(backStepIndex, fieldId)
{
	var stepIndexElement = getField(fieldId);
	if(stepIndexElement != null)
	{
		stepIndexElement.value = backStepIndex;
		document.stepBackForm.submit();
	}
}

function generateUrlFromForm(formHandlerUrl, formId)
{
	var formUrl;
	var params = "";
	var form = getField(formId);
	for(i=0; i<form.elements.length; i++)
	{
	   var fieldName = form.elements[i].name;
	   var fieldValue = form.elements[i].value;

	   params += fieldName + '=' + fieldValue + '&';
	}

	formUrl = formHandlerUrl + "?" + params;
	
	return formUrl;
}

function writeToDiv(divId, content)
{
	var divToWriteTo = getField(divId);
	
	if(divToWriteTo != null)
	{
		divToWriteTo.innerHTML = content;
	}
}

function showLegend()
{
	var legendDiv = $("legendDiv");
	var divPos = getPosition($("legendLink"));
	legendDiv.style.position = 'absolute';
	legendDiv.style.top      = divPos.y-10;
	legendDiv.style.left     = divPos.x-360;
	toggleOn("legendDiv");
}


function getPosition(e){
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};

}

function convertYUIDateToJSDate(yuiDate)
{
	var yuiDateYear = yuiDate.substring(0,4);
	var yuiDateMonth = yuiDate.substring(5,7) - 1;
	var yuiDateDay = yuiDate.substring(8,10);
	
	var jsDate = new Date(yuiDateYear,yuiDateMonth,yuiDateDay);
	
	return jsDate;
}

function calculateDateDiffenceInDays(jsStartDate, jsEndDate)
{
	var one_day=1000*60*60*24;
	
	return Math.ceil((jsEndDate.getTime() - jsStartDate.getTime()) / (one_day));
}

// this function removes a given ID from an array
function makeFieldNotRequired(field)
{
	if(typeof field!="string") field=field.id;
	var tmpRequiredFieldIds = new Array();
	for (var i=0; i<requiredFieldIds.length; i++) {
		var req=requiredFieldIds[i];
		if((typeof req=="string"?req:req.id)!=field)
			tmpRequiredFieldIds.push(req);
	}
	requiredFieldIds = tmpRequiredFieldIds;
}

function makeFieldRequiredCond(field, cond) {
	(cond?makeFieldRequired:makeFieldNotRequired)(field);
}

/* convert the ',",\,;,<,> to HTML code */
function changeSpecialChar(str){

	if(((typeof str)=="undefined")||(str === null)||(str.length < 1)) {
		return "";
	}

	var i=0;
	while(i<str.length){
		var remStr = str.substring(i);
		if(remStr.indexOf("&#39;")===0){
			i = i + 5;
		}else if(remStr.indexOf("&#92;")===0){
			i = i + 5;
		}else if(remStr.indexOf("&#59;")===0){
			i = i + 5;
		}else if(remStr.indexOf("&#60;")===0){
			i = i + 5;
		}else if(remStr.indexOf("&#62;")===0){
			i = i + 5;
		}else if(remStr.indexOf("&quot;")===0){
			i = i + 6;
		}else{
			if(str.charAt(i) == "\'"){
				str = str.substring(0,i) + "&#39;" + str.substring(i+1);	
				i=i+5;
			}else if(str.charAt(i) == "\""){
				str = str.substring(0,i) + "&quot;" + str.substring(i+1);
				i=i+6;
			}else if(str.charAt(i) == "\\"){
				str = str.substring(0,i) + "&#92;" + str.substring(i+1);
				i=i+5;
			}else if(str.charAt(i) == ";"){
				str = str.substring(0,i) + "&#59;" + str.substring(i+1);
				i=i+5;
			}else if(str.charAt(i) == "<"){
				str = str.substring(0,i) + "&#60;" + str.substring(i+1);
				i=i+5;
			}else if(str.charAt(i) == ">"){
				str = str.substring(0,i) + "&#62;" + str.substring(i+1);
				i=i+5;
			}else{
				i=i+1;
			}
		}
	}
	return str;
}
