var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday");
var months = new Array("January", "February", "March", "April","May", "June", "July", "August", "September", "October", "November", "December");

function ClickButton(pId) {
	document.getElementById(pId).click();
}

function formatnumber(p) {
	n = p.length;

	res = '';
	pInd = p.indexOf('.');
	if (1*pInd > 0) {
		res = p.substring(pInd, n).toString();
		if (res.length == 2) {
			res = res + '0';
		}
		p = p.substring(0, pInd);
	}
	else {
		res = '.00';
	}

	n = p.length;
	resnew = '';
	for (i = n - 1; i >= 0; i--) {
		lAdd = '';
		lAt = 1*n - 1 - 1*i;
		if ((i % 3 == 0) && i) {
			lAdd = p.charAt(lAt).toString() + ',';
		}
		else {
			lAdd = p.charAt(lAt).toString();
		}
		resnew = resnew.toString() + lAdd ;
	}
	resnew = '$' + resnew.toString() + res;

	return resnew;
}

function retformatdate(pYear, pMonth, pDay) {
	var lYear;

	if ((parseInt(pYear, 10) == 0) && (parseInt(pMonth, 10) == 0) && (parseInt(pDay, 10) == 0)) {
		d = new Date();
	}
	else {
		lYear = parseInt(pYear, 10);
		if (lYear < 100) {
			lYear += 2000;
		}
		else if (lYear < 1900 && lYear >= 100) {
			lYear = 0;
		}
		if (lYear) {
			d = new Date(lYear, parseInt(pMonth, 10) - 1, parseInt(pDay, 10));
		}
		else {
			d = new Date();
		}
	}

	if ((d.getMonth() + 1) < 10) {
		s = '0' + (d.getMonth() + 1) + "/";
	}
	else {
		s = (d.getMonth() + 1) + "/";
	}

	if (d.getDate() < 10) {
		s += '0';
	}

	s += d.getDate() + "/";
	s += d.getFullYear();

	return s;
}

function IncDate(pStrDate, pInc) {
	if (!pStrDate) {
		return retformatdate(0, 0, 0);
	}

	var RE = /(\d{1,2})\/(\d{1,2})\/(\d{1,4})/;
	if(RE.test(pStrDate)) {
		regRes = RE.exec(pStrDate);
		return retformatdate(1*regRes[3], 1*regRes[1], 1*regRes[2] + 1*pInc);

	}
	else {
		return retformatdate(0, 0, 0);
	}


}

function IncDateByRef(pRef, pInc) {
	document.forms['def1'].elements[pRef].value = IncDate(document.forms['def1'].elements[pRef].value, pInc);
}

function managesize(pId, pDif, pMinWidth) {
	lWidth = 1*document.body.clientWidth;
	lWidth = lWidth - (1*pDif);
	if ((1*lWidth) < (1*pMinWidth)) lWidth = (1*pMinWidth);

	document.getElementById(pId).style.width = lWidth;
}

/* // Old Zip popup function, it is used no more
function setZip1(zip, city, province, zipFieldName, cityFieldName, provFieldName) {
	// this function allows multiple zip codes on one page

	var rightedge=document.body.clientWidth-event.clientX;
	var bottomedge=document.body.clientHeight-event.clientY;

	var winwidth = 10;
	var winheight = 10;

	if (rightedge<parseInt(winwidth)) {
		xoffset = ((-1) * parseInt(winwidth));
	}
	else {
		xoffset = -10;
	}

	if (bottomedge < parseInt(winheight)) {
		yoffset = ((-1) * parseInt(winheight));
	}
	else {
		yoffset = -10;
	}

	x = (event.screenX + xoffset).toString(10);
	y = (event.screenY + yoffset).toString(10);
	window.open("/lib/fillzip.php?zip=" + zip + "&city=" + escape(city) + "&province=" + escape(province) + "&zip_field_name=" + escape(zipFieldName) + "&city_field_name=" + escape(cityFieldName) + "&prov_field_name=" + escape(provFieldName), "fillzip","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,copyhistory=0,width=" + winwidth.toString() + ",height=" + winheight.toString() + ",top=" + y + ",left=" + x);
}
*/

function FireEvents(pArr, pEvent) {
	for (i = 1; i< pArr.length; i++) {
		document.getElementById(pArr[i]).fireEvent(pEvent);
	}
}


//the function sets the field that matches the selector and resets all others in fields_arr
function gChangeReqFiled(selector,fields_arr,inverted) {
	marked = '';
	for (i=0; i< fields_arr.length; i++) {
		index = fields_arr[i][0];
		field = fields_arr[i][1];

		if ( (inverted && selector != index) || (!inverted && selector == index) ) {
			document.getElementById(field).className = 'reqtd';
			//patch allowing the same field to be present in more than 1 fields_arr arrays, otherwise the field could be unset without us wanting to
			marked = field;
		}
		else if (field != marked) {
			document.getElementById(field).className = 'normaltd';
		}
	}
}

function CycleControls(pCallbackFunc, pParam) {
	var lControls;

	if (typeof eval(pCallbackFunc) != 'function') {
		return;
	}

	lControls = document.getElementsByTagName('INPUT');
	for (i = 0; i < lControls.length; i++) {
		eval(pCallbackFunc+'(lControls(i), pParam)');
	}
	lControls = document.getElementsByTagName('TEXTAREA');
	for (i = 0; i < lControls.length; i++) {
		eval(pCallbackFunc+'(lControls(i), pParam)');
	}
	lControls = document.getElementsByTagName('SELECT');
	for (i = 0; i < lControls.length; i++) {
		eval(pCallbackFunc+'(lControls(i), pParam)');
	}
}

function colorControl(pControl) {
	if (pControl.tagName == "INPUT") {
		if (pControl.type == "text" || pControl.type == "password") {
			pControl.onfocus = makeYellow;
			pControl.onblur = removeYellow;
		}
	} else if (pControl.tagName == "TEXTAREA") {
			pControl.onfocus = makeYellow;
			pControl.onblur = removeYellow;
	} else if (pControl.tagName == "SELECT") {
			pControl.onfocus = makeYellow;
			pControl.onclick = makeYellow;
			pControl.onmousedown = makeYellow;
			pControl.onblur = removeYellow;
	}
}

function colorControls() {
	CycleControls('colorControl');
}

function disableControl(pControl, pExcludeCtrls) {
	if (!in_array(pControl.name, pExcludeCtrls) && pControl.type != 'image' && pControl.type != 'submit') {
		pControl.disabled = true;
	}
}

//disable all controls found inside the given tag
function disableEnclosedControls(pElement, pDisable) {

	if (in_array(pElement.tagName, ['INPUT','TEXTAREA','SELECT'])) {
		pElement.disabled = pDisable;
	}

	if (IsValidObject(pElement.childNodes)) {
		var children = pElement.childNodes;
		for (var i = 0; i < children.length; i++) {
			disableEnclosedControls(children[i], pDisable);
		}
	}
}

function formSubmit(oForm, sAction, pSubmit, pUrl, pSubmitCtrls) {
	if (IsValidObject(oForm)) {
		if (pUrl != undefined && pUrl != '') {
			oForm.action = pUrl;
		}
		if (IsValidObject(oForm.tAction)) {
			if (oForm.tAction.value != sAction) {
				oForm.tAction.value = sAction;
			} else {
				return false;
			}
		}
		if (is_Array(pSubmitCtrls, true) && pSubmitCtrls.length > 0) {
			//if we have specified pSubmitCtrls, then disable all other (non-submitting) controls on the page so that they don't get submitted
			CycleControls('disableControl', pSubmitCtrls);
		}
	}
	if (pSubmit == "submit") {
		oForm.submit();
	}
	return true;
}

// change form fields values
function setFormValues(oFormStr,paramsArr) {
	for (i=0;i<paramsArr.length;i++) {
		formParam = eval(oFormStr + '.' + paramsArr[i]['key']);
		formParam.value = paramsArr[i]['value'];
	}

}

function IsValidObject(objToTest) {
		if (null == objToTest) {
			return false;
		}
		if ("undefined" == typeof(objToTest) ) {
			return false;
		}
		return true;
}

 function setduedateglobal(pInc,pElement,pForm) {
	document.forms[pForm].elements[pElement].value = IncDate(document.forms[pForm].elements[pElement].value, pInc);
	document.forms[pForm].elements[pElement].fireEvent('onChange');
}

function setTitleHint(pObject, pForceShowHint) {
  if (pForceShowHint || (pObject.scrollWidth > pObject.clientWidth)) {
    pObject.title = pObject.myTitle;
  } else {
    pObject.title = '';
  }
}

function manageControlVisibility(pShow, pFormName, pCtrlName, pSetReq) {
  var tempCtrl = document.forms[pFormName].elements[pCtrlName];
  if (pShow) {
    tempCtrl.disabled = false;
		tempCtrl.style.visibility = 'visible';
  } else {
    tempCtrl.disabled = true;
		tempCtrl.style.visibility = 'hidden';
  }
  if (pShow)
  	gChangeReqFiled(1, Array(Array(1, pCtrlName)));
  else
  	gChangeReqFiled(0, Array(Array(1, pCtrlName)));
}

function roundFloat (num, sign, letOrNum){
	//ONLY FOR DISPLAY
	//this function rounds a floating number to "sign" figure after the decimal point
	//flNum - the number to be rounded, sign - the figure after the decimal point to be rounded;

	//convert the number to a string in order to use the substring method
	flNum = num+"";

	cutTo = sign+1;
	//check if there's adecimal point
	if(flNum.indexOf(".")== -1){
		//the number is not of type float so just add "." and "sign" zeros after it - used only for displaying
		flNum += ".";
		//flNumBefore = "";
		for(i=0;i<sign;i++){
			flNum += "0";
		}//end for
	}
	//flNumAfter is multiplied 10 powered by the sign parameter in order to create a deciaml number which will be rounded by the Math.round
	flNumAfter = flNum.substring(flNum.indexOf("."), flNum.length-(flNum.indexOf(".")-flNum.indexOf(".")))*(Math.pow(10, sign));
	//round the flNumAfter and multiply it by 0.10 powered by "sign" in order to make it less the zero
	flNumAfter = Math.round(flNumAfter)*(Math.pow(0.10, sign));
	//find the decimal point and separate the the figures before it from the figures after it
	flNumBefore = flNum.substring(0, flNum.indexOf("."));
	//check if the result should be a number or a formatted string
	if(letOrNum == 1){
		//process flNumBefore to put commas as separators for thousands
		//check if flNumBefore is 4 or more figures in length
		re="";
		flBegin="";
		flTxt="";
		flLen=0;
		v=0;
		if(flNumBefore.length >= 4){
			//thousands = flNumBefore.substring(flNumBefore.length, -3);
			flTxt = flNumBefore;
			flLen = flTxt.length;
			v = flLen%3;
			flBegin = flTxt.substr(0, v);
			c=0;
			flNumBefore="";
			while(flLen>v) {
				flLen-=3;
				c++;
				//flNumBefore = flTxt.replace(flTxt.charAt);

				re=(flTxt.substring(flTxt.length-(c*3), flTxt.length-(c*3)+3));
				flNumBefore = ","+re+flNumBefore;
			}
			//alert(flTxt.length);
			//alert(flNumBefore.length);
			flNumBefore = (flNumBefore.charAt(flNumBefore.length-1)=="")?flNumBefore.replace(flNumBefore.charAt(flNumBefore.length-1), ""):flNumBefore;
			flNumBefore = flBegin+flNumBefore;

		}//end check if flNumBefore is 4 or more figures in length
		//alert(flTxt.length);


		//remove the first comma
		if(flTxt.length%3==0 && flTxt.length!=0){
			flNumBefore=flNumBefore.substr(1, flNumBefore.length);
		}

		flNumAfter=""+flNumAfter;
		flNumAfter=flNumAfter.substr(1, cutTo);

	} else if(letOrNum == 2) {
		flNumBefore = flNum.substring(0, flNum.indexOf("."))*1;
	} else {
		alert("letOrNum must be of either '1' or '2' values");
		return false;
	}

	if(flNumAfter == 0 || flNumAfter==""){
		flNumBefore+=".";
		for(i=0;i<sign;i++){
			flNumBefore+= "0";
		}//end for
		return flNumBefore;
	}
	//finally add flNumBefore to flNumAfter

	result = flNumBefore+flNumAfter;
	return result;
}

var oLastRow = null;
var oLastRowBGColor = "";

function ToggleRowColor(oThis, bHighlight, sHighlightColor)
{
		if (isSet(oThis.customHighlightColor)) {
			sHighlightColor = oThis.customHighlightColor;
		}

		if (!isSet(sHighlightColor)) {
			sHighlightColor = "#DCDCDC";
		}

     if (bHighlight)
     {
          oLastRow = oThis;
          oLastRowBGColor = oThis.style.backgroundColor;

          oThis.style.backgroundColor = sHighlightColor;
     }
     else
     {
          oThis.style.backgroundColor = oLastRowBGColor;

          oLastRow = null;
          oLastRowBGColor = "";
     }
}


function copy2ClipBoard() {
	holdtext = document.createElement('TEXTAREA');

	holdtext.innerText = document.body.innerHTML;

	Copied = holdtext.createTextRange();
	Copied.execCommand("Copy");
}

function pasteFromClipBoard() {
	holdtext = document.createElement('TEXTAREA');
	Pasted = holdtext.createTextRange();
	Pasted.execCommand("Paste");
	//alert(Pasted.text);
}

function setPopupPadding(oEl){
	oEl.parentElement.parentElement.style.paddingRight='10px';
	window.onload = setPopupPadding;
	window.onresize = setPopupPadding;
}

gSearchArrowUp = new Image();
gSearchArrowDown = new Image();

gSearchArrowUp.src   = '/images/search_arrow_up.gif';
gSearchArrowDown.src = '/images/search_arrow_down.gif';

function manageSearchVisibility(elementIds_group1, elementIds_group2) {
	if (document.all.searcharrowstatus.value == -1) {
		searchArrow.src = gSearchArrowDown.src;
	}
	else {
		searchArrow.src = gSearchArrowUp.src;
	}

	display = {'-1': '', '1': 'none'};
	ctrldisable = {'-1': false, '1': true};

	for (i=0;i<elementIds_group1.length;i++) {
		document.getElementById(elementIds_group1[i]).style.display = display[document.all.searcharrowstatus.value];
		disableEnclosedControls(document.getElementById(elementIds_group1[i]), ctrldisable[document.all.searcharrowstatus.value]);
	}
	for (i=0;i<elementIds_group2.length;i++) {
		document.getElementById(elementIds_group2[i]).style.display = display[document.all.searcharrowstatus.value*-1];
		disableEnclosedControls(document.getElementById(elementIds_group2[i]), ctrldisable[document.all.searcharrowstatus.value*-1]);
	}

	document.all.searcharrowstatus.value = document.all.searcharrowstatus.value * -1;
}

function chkBrowser(){
	if(document.getElementById && document.all){
		//check if version 5.5. or higher
		if(navigator.userAgent.indexOf('Opera') != -1){
			nav = 'opera';
		} else if(navigator.userAgent.indexOf('MSIE 5.5') != -1 || navigator.userAgent.indexOf('MSIE 6') != -1){
			nav = 'ie5.5+';
		} else {
			nav = 'ie5';
		}
	} else if (document.getElementById && !document.all && !document.layers) {
		nav = 'ns6+';
	} else if (document.layers) {
		nav = 'ns4'
	} else {
		nav = 'undefined';
	}
	return nav;
}

function handleBrowserCompat(pNav, gJSBrowsers) {

	var exitSite = 'browser.html';

	if(!gJSBrowsers){
		window.location = exitSite;
		return;
	} else {
		var redir = true;
		for(i=0;i<gJSBrowsers.length;i++){
			if(pNav != gJSBrowsers[i]){
				redir = true;
			} else {
				redir = false;
			}
		}

		if(redir == true){
			window.location = exitSite;
		}
	}
}

function getOffsetTop(element, deep) {
	return getOffsetProperty(element, 'Top', deep);
}

function getOffsetLeft(element, deep) {
	return getOffsetProperty(element, 'Left', deep);
}

function getOffsetProperty(element, property, deep) {
   var offsetValue = 0;
   offsetProperty = 'offset' + property;

   do {
      offsetValue += element[offsetProperty];
      element = element.offsetParent;
   } while ((deep == true) && (element != document.body) && (element != null));
   return offsetValue;
}

function manageDivPopup() {
	if (document.getElementById('divpopup').style.display == 'none') {
		openDivPopup('/director/quicknote.php',425,163,'quicknotelink',-359,16);
	}
	else {
		CloseDivPopup("divpopup", "divpopupiframe1");

		document.getElementById('divpopupiframe').contentWindow.document.all.tAction.value='save';
		document.getElementById('divpopupiframe').contentWindow.document.getElementById('def1').submit();
	}
}

function manageDivPopup1() {
	if (document.getElementById('divpopup1').style.display == 'none') {
		openDivPopup1('/director/myinfo.php',300,288,'quicknotelink',-178,16);
	}
	else {
		CloseDivPopup("divpopup1", "divpopupiframe1");
	}
}

function manageDivPopup2(pMessageId) {
	if (document.getElementById('divpopup2').style.display == 'none') {
		openDivPopup2('/notifications/quickthreadview.php?currentmsg='+pMessageId,300,0,'quickthreadview',-279,20);
	}
	else {
		CloseDivPopup("divpopup2", "divpopupiframe2", false, true);
	}
}

function openDivPopup(locUrl,width,height,clickedObjectID,offsetTop,offsetLeft) {
		clickedObjectOffsetLeft  = getOffsetLeft(document.getElementById(clickedObjectID),true);
		clickedObjectOffsetTop = getOffsetTop(document.getElementById(clickedObjectID),true);

		CloseDivPopup("divpopup1", "divpopupiframe1");
		CloseDivPopup("divpopup2", "divpopupiframe2", false, true);

		document.getElementById("divpopup").style.display=''
		document.getElementById("divpopup").style.width=initialwidth=width+"px"
		document.getElementById("divpopup").style.height=initialheight=height+"px"
		document.getElementById("divpopup").style.left= clickedObjectOffsetLeft + offsetTop;
		document.getElementById("divpopup").style.top = clickedObjectOffsetTop + offsetLeft;
		document.getElementById("divpopupiframe").src=locUrl
}

function openDivPopup1(locUrl,width,height,clickedObjectID,offsetTop,offsetLeft){
		clickedObjectOffsetLeft  = getOffsetLeft(document.getElementById(clickedObjectID),true);
		clickedObjectOffsetTop = getOffsetTop(document.getElementById(clickedObjectID),true);

		CloseDivPopup("divpopup", "divpopupiframe");
		CloseDivPopup("divpopup2", "divpopupiframe2", false, true);

		document.getElementById("divpopup1").style.display=''
		document.getElementById("divpopup1").style.width=initialwidth=width+"px"
		document.getElementById("divpopup1").style.height=initialheight=height+"px"
		document.getElementById("divpopup1").style.left= clickedObjectOffsetLeft + offsetTop;
		document.getElementById("divpopup1").style.top = clickedObjectOffsetTop + offsetLeft;
		document.getElementById("divpopupiframe1").src=locUrl
}

function openDivPopup2(locUrl,width,height,clickedObjectID,offsetTop,offsetLeft){
		clickedObjectOffsetLeft  = getOffsetLeft(document.getElementById(clickedObjectID),true);
		clickedObjectOffsetTop = getOffsetTop(document.getElementById(clickedObjectID),true);

		CloseDivPopup("divpopup", "divpopupiframe");
		CloseDivPopup("divpopup1", "divpopupiframe1");

		document.getElementById("divpopup2").style.display=''
		document.getElementById("divpopup2").style.width=initialwidth=width+"px"
		document.getElementById("divpopup2").style.height=initialheight=height+"px"
		document.getElementById("divpopup2").style.left= clickedObjectOffsetLeft + offsetTop;
		document.getElementById("divpopup2").style.top = clickedObjectOffsetTop + offsetLeft;
		document.getElementById("divpopupiframe2").src=locUrl
}

function CloseDivPopup(pDivId, pIFrameId, pInFrame, pShrinkFrame) {
	if (!isSet(pInFrame) || !pInFrame) {
		getElement(pDivId).style.display = 'none';
		getElement(pIFrameId).src = "/lib/blank.html";
		if (isSet(pShrinkFrame) && pShrinkFrame) {
			getElement(pIFrameId).style.height = 0;
		}
	}
	else {
		getElement(pDivId, window.parent.document).style.display = 'none';
		getElement(pIFrameId, window.parent.document).src = "/lib/blank.html";
		if (isSet(pShrinkFrame) && pShrinkFrame) {
			getElement(pIFrameId, window.parent.document).style.height = 0;
		}
	}
}

function is_Array(pVar, pStrict) {
	if (typeof(pStrict) == 'undefined') var pStrict = false;
	if (pStrict) {
		return ((typeof(pVar) == 'object') && (pVar.constructor.toString().indexOf("Array") != -1));
	} else {
		return (typeof(pVar) == 'object');
	}
}

function in_array(needle, haystack) {
	for (var i=0; i < haystack.length; i++) {
		if (needle == haystack[i]) return true;
	}
	return false;
}

function show_props(obj, obj_name) {
   var result = "";
   for (var i in obj)
      result += obj_name + "." + i + " = " + obj[i] + "\n";
   return result
}

function GetSelfUrl_Js(excl_params, pUrlEncode) {
	var url = window.location.pathname+'?';
	var args = parseQueryString ();
	for (var arg in args) {
		if (!in_array(arg,excl_params)) {
			url += '&'+arg+'='+(pUrlEncode ? escape(args[arg]) : args[arg]);
	  	}
	}

	return url;
}

function parseQueryString (str) {
  str = str ? str : location.search;
  var query = str.charAt(0) == '?' ? str.substring(1) : str;
  var args = new Object();
  if (query) {
    var fields = query.split('&');
    for (var f = 0; f < fields.length; f++) {
      var field = fields[f].split('=');
		if (field != '') {
      	args[unescape(field[0].replace(/\+/g, ' '))] = unescape(field[1].replace(/\+/g, ' '));
      }
    }
  }
  return args;
}


function appendString2TextArea(pStr, pTextAreaId, pAppendBefore, pAddNewline, pAlertTxtOnEmpty) {

	if (pAlertTxtOnEmpty && pStr == '') {
		alert(pAlertTxtOnEmpty);
		return;
	}

	if (pStr == null || pTextAreaId == null) return;
	if (document.getElementById(pTextAreaId) == null) return;
	if (pAppendBefore == null) pAppendBefore = false;
	if (pAddNewline == null) pAddNewline = false;

	var lTextarea = document.getElementById(pTextAreaId);

	if (pAppendBefore) {
		lTextarea.value = pStr+(pAddNewline ? '\r\n' : '')+lTextarea.value;
	} else {
		lTextarea.value += (pAddNewline ? '\r\n' : '')+pStr;
	}

	return;
}

function checkboxSum(pCheckboxCtrl) {
	var lResult = 0;

	for (var i=0; i<pCheckboxCtrl.length; i++) {
		if (pCheckboxCtrl[i].checked) {
			lResult += pCheckboxCtrl[i].value;
		}
	}

	return lResult;
}

//  loan functions

function loans_showSeparatedBorrowers (pBorrowers, pBorrowerIds, pElement) {
    var myArray = pBorrowers.split('#!#');
    var lResult = myArray[0];

    for (var i = 1; i <= myArray.length+1; i++) {
        if (myArray[i]) {
            lResult = lResult + ', ' + myArray[i];
        }
    }

    setElementValue(pElement, lResult, 1);
    //document.getElementById(pElement).innerHTML = lResult;

    return lResult;
}

// end of loan functions



function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

	for(var i = 0; i < hashes.length; i++)	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}

	return vars;
}
