/*Print Labels*/
try{		
	$(document).ready(function(){
		$('.divPrintButton').each(function(index) {
			$('<img src="/control_GLOBAL/shared/images/Button_makelabel_transp.gif" style="cursor:pointer; border:0px;" title="Click here to generate printable label" onClick="$(this).parent().find(\'a\').remove(); fnPrintAddressLabel($(this), frmMainForm.'+$(this).attr("title")+'.value)">').appendTo($(this));
	   });
	});
	
	function fnPrintAddressLabel(obj,sAd) {
		$.ajax({
			error: function(xhr, desc, exceptionobj) {
				alert(xhr.responseText);
			},
			type: "GET", url: "/control_GLOBAL/shared/AddressLabels_Ajax.asp",
			data: "a="+escape(sAd)+"&c="+sDBConnection,
			contentType: "application/json; charset=utf-8", dataType: "text",
			success: function(response) {
				if(response=='Done') {
					if($(obj).parent().find("a").size()==0){
						$('<br><a href="http://www.highlandaviation.com/FileLibrary/LabelPrint.rtf" style="border:0px" target="_blank"><img src="/control_GLOBAL/shared/images/Button_print_transp.gif" border="0"/></a>').appendTo($(obj).parent())
					}
				} else {
					alert(response);
				}
			}
		});
	}
}catch(e){}
/*End Print Labels*/

function fnKeyPress(e) {
	var keynum;
	if(window.event){keynum = e.keyCode;}
	else if(e.which){keynum = e.which;}
	return keynum;
}

function fnToggleControlNavButton(objDoc, sID, fState, sStyle, sSpare) {
	if (fState == 'over') {
		try{
			objDoc.getElementById(sID+'_t').height = "2";
			objDoc.getElementById(sID+'_l').src = "/control_GLOBAL/shared/images/_CS"+sStyle+"/control_button_over_l.gif";
			objDoc.getElementById(sID+'_m').background = "/control_GLOBAL/shared/images/_CS"+sStyle+"/control_button_over_m.gif";
			objDoc.getElementById(sID+'_r').src = "/control_GLOBAL/shared/images/_CS"+sStyle+"/control_button_over_r.gif";
		}
		catch(e) {}
	}
	else {
		try{
			objDoc.getElementById(sID+'_t').height = "5";
			objDoc.getElementById(sID+'_l').src = "/control_GLOBAL/shared/images/_CS"+sStyle+"/control_button_l.gif";
			objDoc.getElementById(sID+'_m').background = "/control_GLOBAL/shared/images/_CS"+sStyle+"/control_button_m.gif";
			objDoc.getElementById(sID+'_r').src = "/control_GLOBAL/shared/images/_CS"+sStyle+"/control_button_r.gif";
		}
		catch(e) {}
	}
}

//callfilemanager('FM_Form:frmMainForm', 'FM_FileKey:hdnMemberFileKey', 'FM_FileName:', 'FM_ImageURL:MemberImage', 'FM_ReturnType:strIconURL', 'FM_TargetID:MemberTarget', '', '', 'FM_ImagesOnly:true', 'FM_FileWidth:', 'FM_FileHeight:', 'FM_FilePath:')
function callfilemanager (sForm, sFileKey, sFileName, sImageURL, sReturnType, sTargetID, sWidth, sHeight, fImagesOnly, sFormWidth, sFormHeight, sFullPath) {
	// sForm = The name of the form on the page the FM item is to be placed
	// sFileKey = The name of the form item to return the DB key of the file/image to
	// sFileName = The name of the form item to return the file/image name to (not full URL, just filename)
	// sImageURL = The name of the <img> where the returning thumb/icon will be placed
	// sReturnType = 3 options; 1)'thumb'=thumb image 2)'fullsize'=full image 3)[number]=Scale thumb image to this size as max h/w
	// sTargetID = The name of the target image (flashes as selected item if multiple targets on page!) (set to 'notarget' to disallow targetting from the FM)
	// sWidth & sHeight = Specify an exact width/height for image selection
	// fImagesOnly = Flag to specify only targeting images or All files
	// sFormWidth & sFormHeight = The name of the form items for width/height to return selected image dimentions to
	// sFullPath = The name of the form item to return the full path of the file/image to
		
	FMResetTarget(); //Reset the target icon for previous file being selected
	
	//Set all base cookie values not to expire 'no value' as they don't get refreshed
	createCookie('FM_Form',sForm,0);
	createCookie('FM_FileKey',sFileKey,0); 
	createCookie('FM_FileName',sFileName,0); 
	createCookie('FM_FileWidth',sFormWidth,0); 
	createCookie('FM_FileHeight',sFormHeight,0); 
	createCookie('FM_ImageURL',sImageURL,0);
	createCookie('FM_TargetID',sTargetID,0);
	createCookie('FM_FilePath',sFullPath,0);

	if(isNaN(parseInt(sReturnType))) { //ReturnType isn't a scale factor number
		if(sReturnType == 'thumb'){createCookie('FM_ReturnType','strIconURL',0);}
		else{createCookie('FM_ReturnType','strFullImageURL',0);}
	}
	else { //Return Type is a scale factor number
		createCookie('FM_ReturnType',parseInt(sReturnType),0)
	}
	
	createCookie('FM_ImgWidth',sWidth,0);
	createCookie('FM_ImgHeight',sHeight,0);
	if (sWidth+sHeight > "" || fImagesOnly=='true') {
		createCookie('FM_ImagesOnly','true',0);
		createCookie('FM_FileType','Images_Only',0);
	}
	else {
		createCookie('FM_ImagesOnly','false',0);
		createCookie('FM_FileType','All_Files',0);
	}
	
	FMShowTarget(); //Set the target icon for current file being selected
	
	if (!childWindow) { //If we can't find the FM window object
		//alert("FM window can't be found");
		if (readCookie('FM_IsOpen')!=null) { //If the FM window open flag (cookie) is set (it should be open!)
			//alert("Cookie says it's there, so try and link to it...");
			childWindow=open('','FMMain'); //Re-link the parent to child (parent to FM)
		}
	}
	//try {
		if (childWindow && childWindow.open && !childWindow.closed && childWindow.basefrm) { //Is FM there & is FM open & is FM un-closed
			//alert("FM is there, open and hasn't been closed... Set this page as opener and set focus to FM...");
			childWindow.FMopener = self; //Explicitly set this here as it probably contains an orphaned window label
			//As FM may previously have width& height refresh
				childWindow.basefrm.frmPreview.submit();
			//If we have values in width and height then FM needs to get these and refresh, so submit forms in FM
			if (sWidth+sHeight > "") {
				childWindow.basefrm.frmPreview.submit();
			}
			childWindow.topframe.focus(); //FM window is there, set focus
			//setTimeout(function() {childWindow.topframe.frmTopbar.hdnImgWidth.focus();}, 1000);

		}
		else {
			try {childWindow.close();}
			catch(e) {}
			openFMWin('/control_GLOBAL/FileManager/index.asp?q1='+readCookie('controlloginstatusencrypt')+'&q2='+escape(readCookie('controlloginusername'))+'&q3='+escape(readCookie('controlloginrealname'))+'&q4='+readCookie('controlloginuserkey'),874,700); //Open FM window
		}
	//}
	//catch(e) {
	//	openFMWin('/control_GLOBAL/FileManager/index.asp?q1='+readCookie('controlloginstatusencrypt')+'&q2='+escape(readCookie('controlloginusername'))+'&q3='+escape(readCookie('controlloginrealname'))+'&q4='+readCookie('controlloginuserkey'),874,700); //Open FM window
	//}
	
}

function openFMWin(url,theWidth,theHeight) {
	var theTop=(screen.height/2)-(theHeight/2);
	var theLeft=(screen.width/2)-(theWidth/2);
	var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",scrollbars=yes, resizable=yes";
	childWindow=open(url,'FileManager',features);
	if (childWindow.FMopener == null) childWindow.FMopener = self;
	childWindow.focus();
	//if (childWindow.targetfield ==null) childWindow.targetfield = knowledgebase.inputtarget0;
}

function createCookie(name,value,seconds)
{	
	if (seconds > 0) {
		var date = new Date();
		date.setTime(date.getTime()+(seconds*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else {
		var expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/;";
	//document.cookie = name+"="+value+expires+"; path=/control_GLOBAL";
}

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 eraseCookie(name) {
	createCookie(name,"",0);
}

function zzopenPopWin(winname, url,theWidth,theHeight,fScrollbars,fResizable) {
	try {
		childPopWindow.focus();
		childPopWindow.PopOpener = self;
	}
	catch(e) {
		
		var theTop=(screen.height/2)-(theHeight/2);
		var theLeft=(screen.width/2)-(theWidth/2);
		var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",scrollbars="+fScrollbars+", resizable="+fResizable+"";
		childPopWindow=open(url,'PopWin',features);
		try {
			if(childPopWindow.PopOpener != null) {
				childPopWindow.close();//alert('problem!');
				childPopWindow=open(url,'PopWin',features);
			}
		}
		catch(e) {
			alert('error');	
		}
		childPopWindow.PopOpener = self;
	}
}
function openPopWin(winname, url,theWidth,theHeight,fScrollbars,fResizable) {
	var theTop=(screen.height/2)-(theHeight/2);
	var theLeft=(screen.width/2)-(theWidth/2);
	var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",scrollbars="+fScrollbars+", resizable="+fResizable+"";
	var qs='q1='+readCookie('controlloginstatusencrypt')+'&q2='+escape(readCookie('controlloginusername'))+'&q3='+escape(readCookie('controlloginrealname'))+'&q4='+readCookie('controlloginuserkey')
	if(url.indexOf('?')!=-1) {
		url+='&'+qs
	}else{
		url+='?'+qs
	}

	try {
		if(childPopWindow.name != winname) {
			childPopWindow = open(url,winname,features);
			childPopWindow.focus();
		}
		else {
			childPopWindow.focus();
			childPopWindow.PopOpener = self;
		}
	}
	catch(e) {
		
		childPopWindow = open(url,winname,features);

		try {
			if(childPopWindow.PopOpener != null) {
				childPopWindow.close();//alert('problem!');
				childPopWindow=open(url,winname,features);
			}
		}
		catch(e) {
			alert('error');	
		}
		childPopWindow.PopOpener = self;
	}
}

function FMShowTarget() {
	sTarget = readCookie('FM_TargetID')
	if (document[sTarget] && sTarget!=null) {
		document[sTarget].src = "/control_GLOBAL/shared/images/button_target_anim.gif"
	}		
}

function FMResetTarget() {
	sTarget = readCookie('FM_TargetID')
	if (document[sTarget] && sTarget!=null) {
		document[sTarget].src = "/control_GLOBAL/shared/images/control_target.gif"
	}	
}

function FMKillCookies() {
	eraseCookie('FM_Form');
	eraseCookie('FM_FileKey');
	eraseCookie('FM_FileName');
	eraseCookie('FM_FileWidth');
	eraseCookie('FM_FileHeight');	
	eraseCookie('FM_ImageURL');
	eraseCookie('FM_TargetID');
	eraseCookie('FM_FilePath');
}

function setCaretToEnd (control) {
  if (control.createTextRange) {
    var range = control.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (control.setSelectionRange) {
    control.focus();
    var length = control.value.length;
//	alert(length);
    control.setSelectionRange(length, length);
  }
  control.focus();
}

function setSelectionRange(input, selectionStart, selectionEnd) {
	input.focus();
	
	if (input.setSelectionRange) {
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	}
	else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
}


//////=====DEPRICATED! Only used by a few pages in CS - Filter Box Display based on char count=====//////
//   This is the sort-by filter box display func          //
//   objFormTextField = FormName.TextField of filter box  //
//   sButtonID = ID of submit button for filter           //
function charcountmsg(objFormTextField, sButtonID) {
	var sFilterText = "<font color='#CC0000'>" + objFormTextField.value.replace(/ /gi, "&nbsp;") + "</font>"
	if (objFormTextField.value.length < 3) {
		document.getElementById(sButtonID).innerHTML = "&nbsp;Show&nbsp;ALL&nbsp;records&nbsp;";
		//frmKB.KBnavFilterSubmit.value = "Show ALL records";
	}
	if (objFormTextField.value.length > 0 && objFormTextField.value.length < 3) {
		document.getElementById(sButtonID).innerHTML = "&nbsp;Show&nbsp;records&nbsp;Starting&nbsp;with&nbsp;'" + sFilterText + "'&nbsp;";
		//frmKB.KBnavFilterSubmit.value = "Show records Starting with '" + frmKB.KBnavFilter.value + "'";
	}
	if (objFormTextField.value.length > 2) {
		document.getElementById(sButtonID).innerHTML = "&nbsp;Show&nbsp;records&nbsp;Containing&nbsp;'" + sFilterText + "'&nbsp;";
		//frmKB.KBnavFilterSubmit.value = "Show records Containing '" + frmKB.KBnavFilter.value + "'";
	}
}
////////////////////////////////////////////////////////////


//////==========Unload call (onUnload Events)===========//////
//    Called on page unload to check for + save changes     //
//    sForm = The name of the form to be submitted          //
//    sURL = normally this page (accepts query data)        //
//    sKey = DB key of item / record to be updated / saved  //
//    sAction : delete = Just submit form, don't update     //
//              reload = No popup save box, target=_self    //
function fnUnload(sForm, sURL, sKey, sAction) {

	//--- Return nav button on topbar to up position ---
	var pageref = location.href.substring(location.href.lastIndexOf('/')+1).toLowerCase();
	if(pageref.indexOf("?")>-1) pageref=pageref.substr(0,pageref.indexOf("?")) //remove trailing querystring
	if(pageref.substr(pageref.length-4,4)==".asp") pageref=pageref.substr(0,pageref.length-4) //remove ".asp"
	if(pageref.substr(pageref.length-5,5)==".aspx") pageref=pageref.substr(0,pageref.length-5) //remove ".aspx"
	if(pageref.substr(pageref.length-4,4)==".htm") pageref=pageref.substr(0,pageref.length-4) //remove ".htm"
	if(pageref.substr(pageref.length-5,5)==".html") pageref=pageref.substr(0,pageref.length-5) //remove ".html"
	try{fnToggleControlNavButton(parent.frames['controlnavframe'].document, 'btn_'+pageref, 'out', sJSCSSkin, '');}catch(e){}
	//--------------------------------------------------
	var fSubmit;
	var fUpdatePage;
	var fPopWin;
	var sAnchor = "";
	window.onunload = ""; //Unset the onUnload event (set in Body tag) otherwise this func will be called again!
	if (sAction == 'delete') { //If user wants to delete then we don't want to check for changes
		fUpdatePage = false; //Don't update
		fPopWin = false; //Don't popup a save window
		fSubmit = true; //Do Submit the form
	}
	if (sAction.substr(0,6) == 'reload') {
		fSubmit = true; //As this is a reload we will always want to submit
		fPopWin = false; //No popup window for save on reload
		if(fnChangesMadeToPage()) { //Are there any changes
			fUpdatePage = confirm('Changes have been made to this page\nClick OK to Save Changes or CANCEL to discard them'); //Does user want to save changes?
			//fUpdatePage = true; //We do need to update
		}
		else { //No changes made
			fUpdatePage = false; //No updates required
		}
	}

	else { //unload, so navigating away from current page
		if (sAction != 'delete') {
			fPopWin = true; //Always want to popup save window if navigating away from page
			if(fnChangesMadeToPage()) { //Are there any changes
				fUpdatePage = confirm('Changes have been made to this page\nClick OK to Save Changes or CANCEL to discard them'); //Does user want to save changes?
				if(fUpdatePage) fSubmit = true; //As user agreed to save we will need to submit
			}
		}
	}
	
	//If url contains a '#' anchor at the end then we must strip and store this to reattach it at the end
	if (sURL.lastIndexOf('#') > -1) {
		sAnchor = sURL.substring(sURL.lastIndexOf('#'), sURL.length) //Get anchor from sURL
		sURL = sURL.substring(0, sURL.length-sAnchor.length) //strip anchor from sURL
	}

	//If fUpdatePage = true
	if (fUpdatePage) {
		var winleft = (screen.width - 200) / 2;
		var wintop = (screen.height - 100) / 2;
		//sURL = sURL + '&';
		
		//Does url contain querystring data already?
		if (sURL.indexOf('?') > -1) sURL = sURL + '&';
		else sURL = sURL + '?';
		//Add key to url and setup the update type to be populated below
		sURL = sURL + 'key=' + sKey + '&updatetype='
		//If fPopWin then reload this page and create popup.
		if  (fPopWin) {
			win=window.open('','update_win','directories=no,location=no,toolbars=no,menubar=no,resizable=no,scrollbars=no,status=no,width=200,height=100,left='+winleft+',top='+wintop);
			document[sForm].target ="update_win";
			document[sForm].action = sURL + "popup";
		}
		//Else if fPopWin is unset / false then no popup is required. We also pass updatetype=reload back to the page to NOT load the popup
		else {
			document[sForm].target ="_self";
			document[sForm].action = sURL + "reload" + sAnchor;
		}
	}
	else {
		if (fSubmit) document[sForm].action = sURL + sAnchor //No updates required, but any querydata must be put into the form's action
	}
	if (fSubmit) document[sForm].submit(); //Submit the page form
}
//////////////////////////////////////////////////////////////


//////================Date select boxes stuff==================///////
	function fnSetDateCompare(sForm, sThis, sCompare, sSpare, sMode) { 
		var sOperator = sCompare.substr(0,1);
		var sObjToCompareWith= sCompare.substr(2);
		var sCompareMode = sCompare.substr(1,1);
		if (sOperator == '<' || sOperator == '>' || sOperator == '{' || sOperator == '}') {
			if (document[sForm][sObjToCompareWith]) { //Does the form object we need to compare dates with exist?
				var aCompare = document[sForm][sObjToCompareWith].value.split('/');
			//	var aThisPrev = document[sForm][sThis].value.split('/');
				fnCheckDays(sForm, sThis, sMode); //Check no. of days is correct for the current date

				var iThisDay = parseInt(document[sForm]['selDay'+sThis].value)
				var iThisMonth = parseInt(document[sForm]['selMnth'+sThis].value)
				var iThisYear = parseInt(document[sForm]['selYear'+sThis].value)

				var iCompYear = parseInt(aCompare[2]*1)
				var iCompMonth = parseInt(aCompare[1]*1)
				var iCompDay = parseInt(aCompare[0]*1)
				
				var nowdate=new Date(iThisYear,iThisMonth-1,iThisDay); nowdate=new Date(nowdate.valueOf()+0*86400000);
				var nowdateplusday=new Date(nowdate.valueOf()+86400000);
				var nowdateminusday=new Date(nowdate.valueOf()-86400000);
				
				var compdate=new Date(iCompYear,iCompMonth-1,iCompDay); compdate=new Date(compdate.valueOf()+0*86400000);
			//	var compdateplusday=new Date(compdate.valueOf()+1*86400000);
			//	var compdateminusday=new Date(compdate.valueOf()-1*86400000);
				
			//	var nowprev=new Date(aThisPrev[0],aThisPrev[1]-1,aThisPrev[2]); nowprev=new Date(nowprev.valueOf()+0*86400000);
			//	var nowprevplusday=new Date(nowprev.valueOf()+(1*86400000));
			//	var nowprevminusday=new Date(nowprev.valueOf()-(1*86400000));
				
				if (sOperator == '<' || sOperator == '{') var datediff=parseInt( ((((compdate-nowdate)/1000)/60)/60)/24)
				else var datediff=parseInt( ((((nowdate-compdate)/1000)/60)/60)/24)
			//	alert(aCompare[2]+" / "+iCompMonth+" / "+iCompDay)
			//	alert(nowdate+' : '+compdate+' ~ '+datediff )
				
				if (datediff<1) {
					fnShowErrorIcon('Date ranges conflicted - The system has automatically reset dates to a non-conflicting range!');	//Set error flag on topbar
					
					if (sOperator=='<' || sOperator=='>') {
						document[sForm]['selDay'+sObjToCompareWith].value = String(nowdate.getUTCDate());
						document[sForm]['selMnth'+sObjToCompareWith].value = String(nowdate.getUTCMonth()+1);
						document[sForm]['selYear'+sObjToCompareWith].value = String(nowdate.getUTCFullYear());
						fnCheckDays(sForm, sObjToCompareWith, sCompareMode);//Check no. of days is correct for the compare date
						document[sForm]['selDay'+sObjToCompareWith].value = String(nowdate.getUTCDate());
						document[sForm]['selMnth'+sObjToCompareWith].value = String(nowdate.getUTCMonth()+1);
						document[sForm]['selYear'+sObjToCompareWith].value = String(nowdate.getUTCFullYear());
					}
					
					if (sOperator=='{') {
						document[sForm]['selYear'+sObjToCompareWith].value = String(nowdateplusday.getUTCFullYear());
						if(document[sForm]['selYear'+sObjToCompareWith].value!=String(nowdateplusday.getUTCFullYear())) {
							nowdateplusday=new Date(nowdateplusday.valueOf()-86400000);
							document[sForm]['selYear'+sObjToCompareWith].value = String(nowdateplusday.getUTCFullYear());
						}
						document[sForm]['selMnth'+sObjToCompareWith].value = String(nowdateplusday.getUTCMonth()+1);
						document[sForm]['selDay'+sObjToCompareWith].value = String(nowdateplusday.getUTCDate());
						fnCheckDays(sForm, sObjToCompareWith, sCompareMode);//Check no. of days is correct for the compare date
						document[sForm]['selDay'+sObjToCompareWith].value = String(nowdateplusday.getUTCDate());
						document[sForm]['selMnth'+sObjToCompareWith].value = String(nowdateplusday.getUTCMonth()+1);
						document[sForm]['selYear'+sObjToCompareWith].value = String(nowdateplusday.getUTCFullYear());
					}
					if (sOperator=='}') {
						document[sForm]['selYear'+sObjToCompareWith].value = String(nowdateminusday.getUTCFullYear());
						if(document[sForm]['selYear'+sObjToCompareWith].value!=String(nowdateminusday.getUTCFullYear())) {
							nowdateminusday=new Date(nowdateminusday.valueOf()+86400000);
							document[sForm]['selYear'+sObjToCompareWith].value = String(nowdateminusday.getUTCFullYear());
						}
						document[sForm]['selMnth'+sObjToCompareWith].value = String(nowdateminusday.getUTCMonth()+1);
						document[sForm]['selDay'+sObjToCompareWith].value = String(nowdateminusday.getUTCDate());
						fnCheckDays(sForm, sObjToCompareWith, sCompareMode);//Check no. of days is correct for the compare date
						document[sForm]['selDay'+sObjToCompareWith].value = String(nowdateminusday.getUTCDate());
						document[sForm]['selMnth'+sObjToCompareWith].value = String(nowdateminusday.getUTCMonth()+1);
						document[sForm]['selYear'+sObjToCompareWith].value = String(nowdateminusday.getUTCFullYear());
					}
					
				}
				
				//fnCheckDays(sForm, sObjToCompareWith, sCompareMode);//Check no. of days is correct for the compare date (ie 28/29 for feb etc)
				document[sForm][sObjToCompareWith].value=document[sForm]['selDay'+sObjToCompareWith].value+'/'+document[sForm]['selMnth'+sObjToCompareWith].value+'/'+document[sForm]['selYear'+sObjToCompareWith].value; //Update hidden value for compare date
			}
		}
		fnCheckDays(sForm, sThis, sMode); //Check no. of days is correct for the current date
		document[sForm][sThis].value=document[sForm]['selDay'+sThis].value+'/'+document[sForm]['selMnth'+sThis].value+'/'+document[sForm]['selYear'+sThis].value; //Update hidden value for this date
	}
	
	function fnCheckDays(sForm, sFormObj, sMode) {
		var fLeapYear = false;
		var sMth = document[sForm]['selMnth'+sFormObj].value
		if (sMth=='4' || sMth=='6' || sMth=='9' || sMth=='11') {//Apr, June, Sept, Nov (30 days)
			fnCreateDateDay(sForm, sFormObj,28); //if day 29 doesn't exist, create it
			fnCreateDateDay(sForm, sFormObj,29); //if day 30 doesn't exist, create it
			fnRemoveDateDay(sForm, sFormObj,30); //if day 31 exists remove it
		}
		//alert(sMth);
		else if (sMth=='1' || sMth=='3' || sMth=='5' || sMth=='7' || sMth=='8' || sMth=='10' || sMth=='12') {//Jan, Mar, May, July, Aug, Oct, Dec (31 Days)
			fnCreateDateDay(sForm, sFormObj,28); //if day 29 doesn't exist, create it
			fnCreateDateDay(sForm, sFormObj,29); //if day 30 doesn't exist, create it
			fnCreateDateDay(sForm, sFormObj,30); //if day 31 doesn't exist, create it
		}
		else if (sMth=='2') {//Feb
			if (document[sForm]['selDay'+sFormObj].options[30]) fnRemoveDateDay(sForm, sFormObj,30); //if day 31 exists remove it
			if (document[sForm]['selDay'+sFormObj].options[29]) fnRemoveDateDay(sForm, sFormObj,29); //if day 30 exists remove it
			//alert(document[sForm]['selYear'+sFormObj].value);
			if (parseInt(document[sForm]['selYear'+sFormObj].value) % 100 == 0) {
				if (parseInt(document[sForm]['selYear'+sFormObj].value) % 400 == 0) fLeapYear = true;
			}
			else {
				if (parseInt(document[sForm]['selYear'+sFormObj].value) % 4 == 0) fLeapYear = true;
			}
			if (!fLeapYear) { //Not a leap year
				if (document[sForm]['selDay'+sFormObj].options[28]) fnRemoveDateDay(sForm, sFormObj,28);//if day 29 exists remove it
				//fnColorCodeDays(sForm, sFormObj, 28);
			}
			else { //Is a leap year
				if (!document[sForm]['selDay'+sFormObj].options[28]) fnCreateDateDay(sForm, sFormObj,28); //if day 29 doesn't exists create it
				//fnColorCodeDays(sForm, sFormObj, 29); 
			}
		}
		//Make sure the days are populated with correct names and colors
		var sDate = new Date(parseInt(document[sForm]['selYear'+sFormObj].value), parseInt(document[sForm]['selMnth'+sFormObj].value)-1, 1);
		var iDay = sDate.getDay();
		var sSuffix = "th";
		var sLoop
		//alert(parseInt(document[sForm]['selDay'+sFormObj].length));
		for (var iLoop=0; iLoop<parseInt(document[sForm]['selDay'+sFormObj].length); iLoop++) {
			sLoop = String(iLoop+1)
			sSuffix = "th";
			if (sMode == "+") {
				var aDOW = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
				if(String(iLoop+1) == '1' || String(iLoop+1) == '21' || String(iLoop+1) == '31') sSuffix = "st";
				if(String(iLoop+1) == '2' || String(iLoop+1) == '22') sSuffix = "nd";
				if(String(iLoop+1) == '3' || String(iLoop+1) == '23') sSuffix = "rd";
				document[sForm]['selDay'+sFormObj].options[iLoop].text=aDOW[(iDay+iLoop) % 7]+" "+String(iLoop+1)+sSuffix;
			}
			else if(sMode == "c") {
				//var aDOW = new Array("s","m","t","w","t","f","s");
				document[sForm]['selDay'+sFormObj].options[iLoop].innerText=String(iLoop+1);
			}
			else if(sMode == "-") {
				var aDOW = new Array("sun","mon","tue","wed","thu","fri","sat");
				document[sForm]['selDay'+sFormObj].options[iLoop].innerText=String(iLoop+1)+" "+aDOW[(iDay+iLoop) % 7];
			}
			switch((iDay+iLoop) % 7) {
				case 0: //Sunday
					document[sForm]['selDay'+sFormObj].options[iLoop].style.backgroundColor="#FFDDDD";
					document[sForm]['selDay'+sFormObj].options[iLoop].style.color="#FF0000";
					break;
				case 6: //Saturday
					document[sForm]['selDay'+sFormObj].options[iLoop].style.backgroundColor="#BADEFF";
					document[sForm]['selDay'+sFormObj].options[iLoop].style.color="#000000";
					break;
				default: //Reset to white
					document[sForm]['selDay'+sFormObj].options[iLoop].style.backgroundColor="#FFFFFF";
					document[sForm]['selDay'+sFormObj].options[iLoop].style.color="#000000";
					break;
			}
		}
	}
		
	function fnCreateDateDay(sForm, sFormObj, iDay) {
		if (!document[sForm]['selDay'+sFormObj].options[iDay]) { //If this day doesn't already exist add it
			var addDay = document.createElement("OPTION")
			document[sForm]['selDay'+sFormObj].options.add(addDay);
			//addDay.innerText = sDay;
			addDay.value = iDay+1;
		}
	}
	
	function fnRemoveDateDay(sForm, sFormObj,iDay) {
		if (document[sForm]['selDay'+sFormObj].options[iDay]) { //If this day does exist remove it
			document[sForm]['selDay'+sFormObj].remove(iDay);
		}
	}
///////////////////////////////////////////////////////////////////////////////

	function fnShowErrorIcon(sMsg) {
		try {
			document.getElementById('controlerroricon').src = "/control_GLOBAL/shared/images/control_error_anim.gif";
			document.getElementById('controlerroricon').alt = sMsg;
			document.getElementById('controlerroricon').onclick = new Function('alert(\'Warning: '+sMsg+'\')'); //new Function('alert(\'hello js 2\')'); 
			if (sMsg.length > 0) {
				setTimeout("fnShowErrorIcon('')", 6000); //Error triangle stays for 6 seconds
			}
			else {
				document.getElementById('controlerroricon').src = "/control_GLOBAL/shared/images/spacer.gif";
				document.getElementById('controlerroricon').alt = "";
			}
		}
		catch(e) {}
	}
	
/////////////////////////////////
	// Changes the size of all images in a list by given factor
	// sItemID = The base image ID eg <img id="listimg<%=iLoop%>... set this to "listimg"
	// sSize   = 'normal' or 'small' for thumb sizes
	// iLBound = Range From this number (eg =<%=LBound(aList, 2)%> or if page divided with page numbers, then list displayed range)
	// iUBound = Range To this number (eg =<%=UBound(aList, 2)%>)
	// fClickButton = If this is an onload event to reset sizes, then false, if clickbutton to resize then true
	function fnChangeListImageSize(sItemID, sSize, iLBound, iUBound, fClickButton) {
		var i, iWidth
		var sCurrentSize = readCookie("IMGScale")
		if(sCurrentSize != "normal" && sCurrentSize != "small") {
			createCookie("IMGScale","normal",0); //If no cookie set, create a normal one!
			//alert("var at load="+sCurrentSize+"\n\n cookie now="+readCookie("IMGScale"));
			sCurrentSize = "normal";
		}

		if(sSize == "normal" && sCurrentSize == "small") {
			createCookie("IMGScale","normal",0);
			//Change size to normal
			for(var i=iLBound;i<=iUBound;i++) {
				try {
					var iWidth = document.getElementById(sItemID+i).width
					document.getElementById(sItemID+i).width*=2;
				}
				catch(e) { //If errors then this page probably doesn't have images on it and this code was called from onLoad event!
					return;
				}
			}
		}
		if((sSize == "small" && sCurrentSize == "normal") || (sSize == "small" && !fClickButton)) {
			createCookie("IMGScale","small",0);
			//Change size to small
			for(var i=iLBound;i<=iUBound;i++) {
				try {
					var iWidth = document.getElementById(sItemID+i).width
					document.getElementById(sItemID+i).width/=2;
				}
				catch(e) { //If errors then this page probably doesn't have images on it and this code was called from onLoad event!
					return;
				}
			}
		}
	}
	
	
	function zzvalidateEmail(addr,fMandatory,fShowAlert) {
		var i;
		if (addr == '' && fMandatory) {
		   if (fShowAlert) alert('email address is mandatory');
		   return false;
		}
		var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
		for (i=0; i<invalidChars.length; i++) {
		   if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
			  if (fShowAlert) alert('email address contains invalid characters');
			  return false;
		   }
		}
		for (i=0; i<addr.length; i++) {
		   if (addr.charCodeAt(i)>127) {
			  if (fShowAlert) alert("email address contains non ascii characters.");
			  return false;
		   }
		}
		
		var atPos = addr.indexOf('@',0);
		if (atPos == -1) {
		   if (fShowAlert) alert('email address must contain an @');
		   return false;
		}
		if (atPos == 0) {
		   if (fShowAlert) alert('email address must not start with @');
		   return false;
		}
		if (addr.indexOf('@', atPos + 1) > - 1) {
		   if (fShowAlert) alert('email address must contain only one @');
		   return false;
		}
		if (addr.indexOf('.', atPos) == -1) {
		   if (fShowAlert) alert('email address must contain a period in the domain name');
		   return false;
		}
		if (addr.indexOf('@.',0) != -1) {
		   if (fShowAlert) alert('period must not immediately follow @ in email address');
		   return false;
		}
		if (addr.indexOf('.@',0) != -1){
		   if (fShowAlert) alert('period must not immediately precede @ in email address');
		   return false;
		}
		if (addr.indexOf('..',0) != -1) {
		   if (fShowAlert) alert('two periods must not be adjacent in email address');
		   return false;
		}
		var suffix = addr.substring(addr.lastIndexOf('.')+1).toLowerCase();
		if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
		   if (fShowAlert) alert('invalid primary domain in email address');
		   return false;
		}
		return true;
	}
	
	function validateEmail(addr,fMandatory,fShowAlert) {

		if (addr == '' && fMandatory) {
		   if (fShowAlert) alert('email address is mandatory');
		   return false;
		}
		var regexp = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
		var match = regexp.exec(addr);
		if (match != null) {
			return true;
		} else {
			return false;
		}
	}

	function fnCheckCCnum(FormField) {
		// Check credit/Switch card number is in valid format
		var ccRE=/\W/gi;
		var CCnumber=FormField.value.replace(ccRE, "");
		if (isNaN(CCnumber)) {
			FormField.focus();
			return false
		}
		if (CCnumber.length<13) {
			FormField.focus();
			return false
		}
		iRem = ((CCnumber.length-1) % 2);
		var cardMath=0;
		for (i=CCnumber.length; i>0; i--) {
			if (i % 2 == iRem) {
				var doubled = "" + (parseInt(CCnumber.substring(i - 1, i)) * 2);
				if (doubled.length==2) {doubled = parseInt(doubled.substring(0,1)) + parseInt(doubled.substring(1,2))}
				cardMath += parseInt(doubled);
				}
			else {cardMath += parseInt(CCnumber.substring(i - 1, i))}
			}
			//alert(cardMath);
		if (cardMath % 10 != 0) {
			FormField.focus();
			return false
		}
		return true;
	}
	
	function fnPopInfoWin(sTxt) {
		var myregexp = /\[[\d]+\]/i; //Find 1st match of [xx] for new height in pixels
		var aMatch = myregexp.exec(sTxt);
		var iHeight="175";
		var iNewHeight = "";
		if(aMatch != null && aMatch.length>0) {
			sTxt=sTxt.replace(myregexp,''); //Remove 1st match of [xx]
			var iNewHeight=aMatch[0]
			iNewHeight=iNewHeight.replace(/\[/,'')
			iNewHeight=iNewHeight.replace(/\]/,'')
		}
		if(iNewHeight.length>0){
			if(isFinite(iNewHeight)) iHeight=parseInt(iNewHeight); //Replace height if exists
		}
		var iWidth=parseInt(iHeight/2)+130;
		var Win1 = window.open("", "helpoint", "toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=1, width="+iWidth+",height="+iHeight+", left="+(event.screenX+10)+", top="+(event.screenY+10));
		Win1.document.open();
		Win1.focus();
		Win1.document.write("<html><head>");
		
		Win1.document.write("<script>\n");
		Win1.document.write("function fnCheckOpenerValid() {\n");
		Win1.document.write("	try {\n");
		Win1.document.write("		if (opener.document.imgHelpPoint){}\n");
		Win1.document.write("		else {window.close();}\n");
		Win1.document.write("	}\n");
		Win1.document.write("	catch(e){window.close();}\n");
		Win1.document.write("}\n");
		Win1.document.write("setTimeout('fnCheckOpenerValid();', 1000);\n");
		Win1.document.write("</script>");
		
		Win1.document.write("<link rel='stylesheet' href='/control_GLOBAL/style-sheets_GLOBAL/control.css' type='text/css'><link rel='stylesheet' href='/control_GLOBAL/style-sheets_GLOBAL/cs_skin1.css' type='text/css'></head><body bgcolor='#FFFEF5'>");
		Win1.document.write("<table cellpadding='0' cellpadding='0' width='100%' height='100%'><tr valign='middle'><td>");
		Win1.document.write("	<table width='92%' bgcolor='#DFEEE8' style='border:#999999 1px solid;' cellpadding='2' align='center' class='control-norm'>");
		Win1.document.write("		<tr>");
		Win1.document.write("			<td align='center'>");
		Win1.document.write("				<table cellspacing='0' cellpadding='6' style='border:#999999 1px solid;' width='100%' bgcolor='#FFFCEB' class='control-norm'>");
		Win1.document.write("					<tr>");
		Win1.document.write("						<td align='center'><img src='/control_GLOBAL/shared/images/control_information_big.gif'></td>");
		Win1.document.write("						<td align='center'><strong>Help&nbsp;Point<hr size='1px' width='70' color='#999999'></strong></td>");
		Win1.document.write("					</tr>");
		Win1.document.write("				</table>");
		Win1.document.write("			</td>");
		Win1.document.write("		</tr>");
	
		Win1.document.write("		<tr>");
		Win1.document.write("			<td align='left' style='padding:8px;'><font color='#174533'>"+sTxt+"</font></td>");
		Win1.document.write("		</tr>");
		
		Win1.document.write("	</table></td></tr>");
		Win1.document.write("</table></body></html>");
		
		Win1.document.close();
	}

	//openerImgName = unique name of img tag on opener page (used for checking user hasn't moved from opener page)
	function fnPopDateSelector(fieldID, openerImgName, OpenDate, loDate, hiDate) {
		var Win2 = window.open("/control_GLOBAL/EventsDiary/popLKP-DateSelector.asp?fieldid="+fieldID+"&opendate="+OpenDate+"&lodate="+loDate+"&hidate="+hiDate+"&uniqueid="+openerImgName, "dateselector", "toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=0, resizable=0, width=220,height=220, left="+(event.screenX+10)+", top="+(event.screenY+10));
		Win2.focus();
	}
	
	
	function fnShowCookiesEnabledMsg() {
		createCookie('sescookiechecker','setok',0);
		if(!readCookie('sescookiechecker') || readCookie('sescookiechecker').length<1) {
			document.write("<tr><td align='center'><font class='ErrorRed'><hr size='1' style='color:#cc0000;'>WARNING!<br>Session Cookies have been blocked</font><br><span class='small'>You must enable browser session cookies to shop on this website</span><hr size='1' style='color:#cc0000;'></td></tr>");
		}
	}
	
	function fnCreateBookingPath(sForm, sArrDateField, sDepDateField, iBoxCount, iDayCount, iMonth, iYear, sCellColBooked, sCellColAvailable, sCellColPath) {
		var iStartingDateBoxID = document[sForm].SelectorFlagStartBox.value
		var iEndingDateBoxID = document[sForm].SelectorFlagEndBox.value
		var fBooked=false;
		if(iStartingDateBoxID=='-1' && iEndingDateBoxID=='-1') { //Selected from sidebar
			fnScrapOldBookingPath(sForm, sCellColAvailable, sCellColPath);
		}
		else {
			if(!iStartingDateBoxID || isNaN(iStartingDateBoxID)) { //No path started yet
				document[sForm].SelectorFlagStartBox.value=iBoxCount;
				document[sForm]['selDay'+sArrDateField].value=iDayCount;
				document[sForm]['selMnth'+sArrDateField].value=iMonth;
				document[sForm]['selYear'+sArrDateField].value=iYear;
				document[sForm][sArrDateField].value=iDayCount+'/'+iMonth+'/'+iYear;
				fnSetDateCompare(sForm, sArrDateField, '<-'+sDepDateField, 'undo', '-');
				document.getElementById(iBoxCount).style.backgroundColor=sCellColPath;
			}
			
			else if(!iEndingDateBoxID || isNaN(iEndingDateBoxID)) { //Path started, but not finished
				if(parseInt(iBoxCount)<=parseInt(iStartingDateBoxID)) {
					alert('Please click your Arrival date followed by your Departure date.');
					fnScrapOldBookingPath(sForm, sCellColAvailable, sCellColPath);
				}else{
					for(i=parseInt(iStartingDateBoxID); i<parseInt(iBoxCount)+1; i++){
						if(!document.getElementById(i)) fBooked=true; //if id not found then td has been marked as idxx 'booked'
					}
					if(!fBooked) {
						for(i=parseInt(iStartingDateBoxID); i<parseInt(iBoxCount)+1; i++){
							document.getElementById(i).style.backgroundColor=sCellColPath;
						}
						document[sForm]['selDay'+sDepDateField].value=iDayCount;
						document[sForm]['selMnth'+sDepDateField].value=iMonth;
						document[sForm]['selYear'+sDepDateField].value=iYear;
						document[sForm][sDepDateField].value=iDayCount+'/'+iMonth+'/'+iYear;
						fnSetDateCompare(sForm, sDepDateField, '>-'+sArrDateField, 'undo', '-');
						document[sForm].SelectorFlagEndBox.value=iBoxCount;
						fnToggleBookingButton(true);
					}
					else {
						alert('Unable to select these dates because of a prior booking!');
						fnScrapOldBookingPath(sForm, sCellColAvailable, sCellColPath);
					}
				}
			}
			
			else { //Scrap old path
				fnScrapOldBookingPath(sForm, sCellColAvailable, sCellColPath);
			}
		}
	}
	
	function fnCreateBookingSingleDay(sForm, sArrDateField, sDepDateField, iBoxCount, iDayCount, iMonth, iYear, sCellColBooked, sCellColAvailable, sCellColPath)  {
		if(document.getElementById(iBoxCount).style.backgroundColor!=sCellColBooked) {
			fnScrapOldBookingPath(sForm, sCellColAvailable, sCellColPath);
			document.getElementById(iBoxCount).style.backgroundColor=sCellColPath;
			document[sForm].SelectorFlagStartBox.value=iBoxCount;
		//	document[sForm]['selMnth'+sArrDateField].value=iMonth;
		//	document[sForm]['selDay'+sArrDateField].value=iDayCount;
		//	document[sForm]['selYear'+sArrDateField].value=iYear;
			document.getElementById(iBoxCount).style.backgroundColor=sCellColPath;
		//	fnSetDateCompare(sForm, sArrDateField, '+', 'undo', '+');
			document[sForm][sArrDateField].value=iDayCount+'/'+iMonth+'/'+iYear;
			fnToggleBookingButton(true);
		}
	}
	
	function fnScrapOldBookingPath(sForm, sCellColAvailable, sCellColPath) {
		for(i=0; i<367; i++){
			//if(i<50 && document.getElementById(i))alert(document.getElementById(i).style.backgroundColor+'~'+sCellColPath);
			if(document.getElementById(i) && document.getElementById(i).style.backgroundColor.toLowerCase==sCellColPath.toLowerCase)document.getElementById(i).style.backgroundColor=sCellColAvailable;
		}
		document[sForm].SelectorFlagStartBox.value='';
		document[sForm].SelectorFlagEndBox.value='';
		fnToggleBookingButton(false);
	}

	function fnToggleBookingButton(fSwitchOn) {
		if(frmSelDate.ArrSelDate.value.length>0) {
			if(fSwitchOn==true) {
				var dtmDepDate = frmSelDate.ArrSelDate.value
				if(frmSelDate.DepSelDate) dtmDepDate = frmSelDate.DepSelDate.value
				document.getElementById("IDbookingbooknow").innerHTML='&nbsp;BOOK<br>Now';
				document.getElementById("IDbookingbooknow").style.filter='alpha(style=0,opacity=100)';
				document.getElementById("IDbookingbooknow").style.opacity='1';
				document.getElementById("IDbookingbooknow").style.cursor='pointer';
				document.getElementById("IDbookingbooknow").onclick=function(){frmSelDate.action='booking.asp'; createCookie('basketitems',frmSelDate.SelSetProp.value+','+frmSelDate.ArrSelDate.value+','+dtmDepDate,0); frmSelDate.submit();};
			}
			else {
				document.getElementById("IDbookingbooknow").innerHTML='&nbsp;Check<br>Availability';
				document.getElementById("IDbookingbooknow").style.filter='alpha(style=0,opacity=75)';
				document.getElementById("IDbookingbooknow").style.opacity='0.75';
				eraseCookie('basketitems');
				document.getElementById("IDbookingbooknow").onclick=function(){frmSelDate.action=''; frmSelDate.submit();};
			}
		} else {
			document.getElementById("IDbookingbooknow").innerHTML='Select<br>&nbsp;Date&nbsp;';
			document.getElementById("IDbookingbooknow").style.filter='alpha(style=0,opacity=75)';
			document.getElementById("IDbookingbooknow").style.opacity='0.4';
			eraseCookie('basketitems');
			document.getElementById("IDbookingbooknow").onclick=function(){};
		}
	}
	
	//Function to check (in registry) if site is trusted or not
	function fnCheckSiteIsTrusted() {
		var splithosttxt = document.location.host.split(".");
		var iRegValue = null;
		if (splithosttxt.length == 5) { //eg control.abc.me.uk.com
			var domaintxt = splithosttxt[1] + "." + splithosttxt[2]+"."+splithosttxt[3]+"."+splithosttxt[4] ;
		} else if (splithosttxt.length == 4) { //eg control.abc.co.uk
			var domaintxt = splithosttxt[1] + "." + splithosttxt[2]+"."+splithosttxt[3] ;
		} else { //eg control.abc.com
			var domaintxt = splithosttxt[1] + "." + splithosttxt[2] ;
		}
			var subdomaintxt = splithosttxt[0];
		try {
			var WRT = new ActiveXObject("WScript.Shell");
		}
		catch(e){return null;}
		try {
			iRegValue = WRT.RegRead("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ZoneMap\\Domains\\"+domaintxt+"\\"+subdomaintxt+"\\http");
			}
		catch(e) {}

		if (iRegValue && iRegValue!=null) {
			return true
		} else {
			return false
		}
	}
	
	//=== Handler for Ajax ===
	function fnRQDGetXmlHttpObject(handler) { 
		var objXmlHttp=null;
		if (navigator.userAgent.indexOf("MSIE")>=0) { 
			var strName="Msxml2.XMLHTTP";
			if (navigator.appVersion.indexOf("MSIE 5.5")>=0) {strName="Microsoft.XMLHTTP";} 
			try { 
				objXmlHttp=new ActiveXObject(strName);
				objXmlHttp.onreadystatechange=handler;
				return objXmlHttp;
			} 
			catch(e) {return;} 
		}
		if (navigator.userAgent.indexOf("Mozilla")>=0) {
			objXmlHttp=new XMLHttpRequest();
			objXmlHttp.onload=handler;
			objXmlHttp.onerror=handler;
			return objXmlHttp;
		}
	}
	function fnGetData(obj, sInstance, sData) {
		var aData = sData.split(',');   
		var url = aData[0];
		var RQD_Querydata = "RQD_Querydata="+encodeURIComponent(obj.value); //Replaces escape() as new URI also replaces '+'
		RQD_Querydata+="&RQD_Formname="+obj.form.name;
		RQD_Querydata+=aData[1];
		RQD_Querydata+="&RQD_sRQDName=" + sInstance;
		eval("xmlHttp=fnRQDGetXmlHttpObject(fnXMLstateChanged"+sInstance+")");
		xmlHttp.open("POST", url, true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", RQD_Querydata.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(RQD_Querydata);
	}
	
//	var iRQDCursorLoc = -1;
//	var fRQDCursorKeyStrike = false;
	function fnKeyUp(obj, sInstance, sData, sReload, sReturnField) {
		switch(window.event.keyCode) {
			case 40: //Key down
				try {
					fRQDCursorKeyStrike=true;
					document.getElementById('td'+sInstance+(iRQDCursorLoc+1)).className='control-link-sm-hover';
					iRQDCursorLoc+=1;
					document.getElementById('td'+sInstance+(iRQDCursorLoc-1)).className='control-link-sm';
				}
				catch(e){}
				break;
			case 38: //Key up
				try {
					fRQDCursorKeyStrike=true;
					document.getElementById('td'+sInstance+iRQDCursorLoc).className='control-link-sm';
					iRQDCursorLoc-=1;
					document.getElementById('td'+sInstance+iRQDCursorLoc).className='control-link-sm-hover';
				}
				catch(e){}
				break;
			case 37: break; //Key left
			case 39: break; //Key right
			case 13: //Enter key
				if(fRQDCursorKeyStrike) { //only try submitting on return if user has used cursor keys to get there!
					if(sReturnField && !sReturnField.length>0) sReturnField='hdnItemKey';
					try{
						obj.value=unescape(document.getElementById('td'+sInstance+iRQDCursorLoc).name.split(',')[1]);
						obj.form[sReturnField].value='RQD'+document.getElementById('td'+sInstance+iRQDCursorLoc).name.split(',')[0];
						setTimeout("document.getElementById('Div"+sInstance+"').innerHTML=''",350);
						
					}
					catch(e){}
					eval(unescape(sReload));
				}
				break; //return key
			default : //Case else
				iRQDCursorLoc=-1; //reset scroller
				fnGetData(obj, sInstance, sData);
		}
	}
	function fnRQDBlur(sInstance) {
		setTimeout("document.getElementById('Div"+sInstance+"').innerHTML=''",750);
	}
	
	
	
	
	//--- JQuery Functions for AJAX ---//
	var iRQDCursorLoc = -1;
	function fnAjaxListKeyUp(keypress, oTextField, sDivID, oToReturnKeyTo, sDBConn, sStyle) {
		var ikeyFL;
		//alert(keypress)
		switch(keypress) {
			case 40: //Key down
				try{document.getElementById(sDivID+'td'+(iRQDCursorLoc+1)).className=sStyle+'_SearchDDListItem_hover';}catch(e){}
					iRQDCursorLoc+=1;
				try{ikeyFL=document.getElementById(sDivID+'td'+iRQDCursorLoc).getAttribute('name').split(',')[1];}catch(e){iRQDCursorLoc-=1}
				try{document.getElementById(sDivID+'td'+(iRQDCursorLoc-1)).className=sStyle+'_SearchDDListItem';}catch(e){}
					fnAjaxListChangeImg(ikeyFL,sDivID,sDBConn)
				
				break;
			case 38: //Key up
				try {
					document.getElementById(sDivID+'td'+iRQDCursorLoc).className=sStyle+'_SearchDDListItem';
					iRQDCursorLoc-=1;
					document.getElementById(sDivID+'td'+iRQDCursorLoc).className=sStyle+'_SearchDDListItem_hover';
					ikeyFL=document.getElementById(sDivID+'td'+iRQDCursorLoc).getAttribute('name').split(',')[1];
					fnAjaxListChangeImg(ikeyFL,sDivID,sDBConn)
				}
				catch(e){fnAjaxListChangeImg(-1,sDivID,'');fnAjaxListToggleListBox(false,sDivID,0,0,true);}
				break;
			case 37: break; //Key left
			case 39: break; //Key right
			case 13: //Enter key
				try {
					//oTextField.value=unescape(document.getElementById(sDivID+'td'+iRQDCursorLoc).getAttribute('name').split(',')[2]);
					var ikeyFL=document.getElementById(sDivID+'td'+iRQDCursorLoc).getAttribute('name').split(',')[1];
					fnAjaxListToggleListBox(false,sDivID,0,0,true); //Hide (animated) the list box
				}
				catch(e) {}
				try {oToReturnKeyTo.value=document.getElementById(sDivID+'td'+iRQDCursorLoc).getAttribute('name').split(',')[0];}catch(e){}
				break; //return key
		}
	}
	
	//sDivID can be a single val or Array of 2 values representing form elements to return the list name to
	function fnAjaxListGetList(sDivID, sDBConn, iLangKey, oToReturnKeyTo, sSQLToUse, sStyle, fSubmitForm) {
		iRQDCursorLoc=-1; //reset scroller
		var fReturnToTwoVals=false;
		if (sDivID.constructor.toString().indexOf("Array") != -1) { //Is Array
			sDivID2=sDivID[1]+"";
			sDivID=sDivID[0];
			if(sDivID2.length>0)fReturnToTwoVals=true;
		}
		var iIEHeight = (navigator.userAgent.indexOf("MSIE")==-1 || sStyle=='control')?0:7; //Additional div list height form MS IE
		if(!$('#'+sDivID+'Txt').val().length>0){
			fnAjaxListToggleListBox(false,sDivID,0,0,true); //Hide (animated) the list box
		} else {
			clearTimeout(algl);
			
			algl=setTimeout(function(){
				$.ajax({
					error: function(xhr, desc, exceptionobj) {
						alert(xhr.responseText);
					},
					type: "GET",
					url: "/control_GLOBAL/shared/AjaxFetchList.asp",
					data: "d="+encodeURIComponent($('#'+sDivID+'Txt').val())+"&c="+sDBConn+"&l="+iLangKey+"&s="+sSQLToUse,
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function(response) {
						$('#'+sDivID).empty();
						var sBox='';
						if(response.aList.length>0) { //Do we have any results from search?
						
							var sList = (typeof response.aList)=='string'? eval('(' + response.aList + ')') : response.aList;
							//Get max widths for box size
							var iMaxStrLen=0; for(i=0;i<sList.length;i++) {if(iMaxStrLen<unescape(sList[i].title).length) iMaxStrLen=unescape(sList[i].title).length;}
							var iListHeight=iIEHeight+parseInt((sList.length)*14);
							var iListWidth=parseInt((iMaxStrLen*5)+50);
							
							//Loop all returned list items and build box contents
							sBox+='<table width="100%" cellpadding="0" cellspacing="0" border="0">';
							for(i=0;i<sList.length;i++) {
								sBox+='<tr>';
								var sBoxClick=""; 
								if(sStyle=='control'){ //cs side
									sBoxClick+="try{"+oToReturnKeyTo+".value='"+sList[i].key+"';}catch(e){};";
									sBoxClick+="frmMainForm."+sDivID+"Txt.value=unescape('"+sList[i].title+"');";
									if(fReturnToTwoVals) sBoxClick+="frmMainForm."+sDivID2+".value=unescape('"+sList[i].title+"');";
									if(fSubmitForm) sBoxClick+="document.forms[0].submit();"
								} else { //website side
									sBoxClick="try{document.frmShopNavBar.srch.value=document.getElementById('"+sDivID+"Txt').value;}catch(e){alert('report to evisk'+e)}";
									sBoxClick+="try{"+oToReturnKeyTo+".value='"+sList[i].key+"';}catch(e){alert('report to evisk'+e)};";
									if(fSubmitForm) sBoxClick+="document.frmShopNavBar.submit();"
								}
								if(!sList[i].keyFL.length>0) sList[i].keyFL=-1;
								sBox+='<td id="'+sDivID+'td'+i+'" name="'+sList[i].key+','+sList[i].keyFL+','+sList[i].title+'" class="'+sStyle+'_SearchDDListItem" style="cursor:pointer;" onClick="'+sBoxClick+'" onmouseover="try{document.getElementById(\''+sDivID+'td\'+eval(iRQDCursorLoc)).className=\''+sStyle+'_SearchDDListItem\';}catch(e){}; iRQDCursorLoc='+i+'; fnAjaxListChangeImg('+sList[i].keyFL+',\''+sDivID+'\',\''+sDBConn+'\'); this.className=\''+sStyle+'_SearchDDListItem_hover\';" onmouseout="this.className=\''+sStyle+'_SearchDDListItem\';">'
								sBox+=unescape(sList[i].title);
								sBox+='</td></tr>';
							}
							sBox+='</table>';
							$('#'+sDivID).append(sBox); //Apply new list to div box
							
							fnAjaxListToggleListBox(true,sDivID,iListHeight, iListWidth, true); //Show (animate) the now populated list box
	
						} else { //Nothing returned, so pop nothing box
							sBox+="<span class='"+sStyle+"_SearchBoxNothingFound'>nothing found</span>";
							$('#'+sDivID).append(sBox);
							fnAjaxListToggleListBox(true,sDivID,12+iIEHeight, 80, false); //Show (animate) the now populated list box
						}
					}
				})
			},200);
		}
	}

	//Get image from Ajax JQuery and AjaxFetchImg.asp and display in side box
	function fnAjaxListChangeImg(ikeyFL, sDivID, sDBConn){
		if(ikeyFL>-1) {
			$.ajax({
				error: function(xhr, desc, exceptionobj) {
			//		alert(xhr.responseText);
				},
				type: "GET", url: "/control_GLOBAL/shared/AjaxFetchImg.asp",
				data: "k="+ikeyFL+"&c=" + sDBConn,
				contentType: "application/json; charset=utf-8", dataType: "text",
				success: function(response) {document.getElementById(sDivID+'Img').innerHTML=response;}
			});
		} else {
			try {document.getElementById(sDivID+'Img').innerHTML='';}catch(e){}
		}
	}
	
	//function to open / close list and img pane (animated)
	function fnAjaxListToggleListBox(fToggle, sDivID, iListHeight, iListWidth, fToggleImgPane) {
		var iOpenStateOpacity = 0.95 //0.90 = 90% 0.50 = 50% etc
		if(fToggle) { //open
			try{document.getElementById('divshoppagenav').style.visibility = 'hidden';}catch(e){} //Just for shop, kill the page drop-down

			$('#'+sDivID).animate({opacity: iOpenStateOpacity, height: iListHeight+'px', width: iListWidth+'px'},500);
			if(fToggleImgPane) {
				$('#'+sDivID+'Img').animate({opacity: iOpenStateOpacity, height: '98px'},500);
			} else { //close img incase it's open
				fnAjaxListChangeImg(-1,sDivID,'') //Blank Img box
				$('#'+sDivID+'Img').animate({opacity: 0, height: iListHeight+'px'},500);
			}
		} else { //close
			//iRQDCursorLoc=-1;
			try{document.getElementById('divshoppagenav').style.visibility = 'visible';}catch(e){} //Just for shop, re-shown the page drop-down
			$('#'+sDivID).animate({opacity: 0, height: iListHeight+'px', width: iListWidth+'px'},500);
			fnAjaxListChangeImg(-1,sDivID,'') //Blank Img box
			if(fToggleImgPane)$('#'+sDivID+'Img').animate({opacity: 0, height: iListHeight+'px'},500);
		}
	}
	//---------------------------------//
	
	
	
	
	//--- JS for the dropdown menu ---
	var ddmenu=function(){
	var t=13,z=50,iSpeed=6,a;
	function fnMenuDropDown(n){this.n=n; this.iHeight=[]; this.c=[]}
	fnMenuDropDown.prototype.init=function(p,c){
		a=c; var ULitem=document.getElementById(p), ListItem=ULitem.getElementsByTagName('ul'), iListItemCount=ListItem.length, i=0;
		for(i;i<iListItemCount;i++){
			var iHeight=ListItem[i].parentNode; this.iHeight[i]=iHeight; this.c[i]=ListItem[i];
			iHeight.onmouseover=new Function(this.n+'.st('+i+',true)');
			iHeight.onmouseout=new Function(this.n+'.st('+i+')');
		}
	}
	fnMenuDropDown.prototype.st=function(x,f){
		var c=this.c[x], iHeight=this.iHeight[x], p=iHeight.getElementsByTagName('a')[0];
		clearInterval(c.t); c.style.overflow='hidden';
		if(f){
			p.className+=' '+a;
			if(!c.mh){c.style.display='block'; c.style.height=''; c.mh=c.offsetHeight; c.style.height=0}
			if(c.mh==c.offsetHeight){c.style.overflow='visible'}
			else{c.style.zIndex=z; z++; c.t=setInterval(function(){fnDDMenuFade(c,1)},t)}
		}else{p.className=p.className.replace(a,''); c.t=setInterval(function(){fnDDMenuFade(c,-1)},t)}
	}
	function fnDDMenuFade(c,f){
		var iHeight=c.offsetHeight;
		if((iHeight<=iSpeed+1&&f!=1)||(iHeight>=c.mh&&f==1)){
			if(f==1){
				c.style.filter=''; c.style.opacity=1; c.style.overflow='visible'
			} else {
				c.style.opacity=0; c.style.filter='alpha(opacity=0)';
			}
			clearInterval(c.t); return
		}
		var d=(f==1)?Math.ceil((c.mh-iHeight)/iSpeed):Math.ceil(iHeight/iSpeed), iOpacity=iHeight/c.mh;
		c.style.opacity=iOpacity;
		c.style.filter='alpha(opacity='+(iOpacity*100)+')';
		c.style.height=iHeight+(d*f)+'px'
	}
	return{fnMenuDropDown:fnMenuDropDown}
}();
	//----------------------------------



function fnGreyOutScreenWithMsg(vis, sMsg, iDelayToKillBlackout, options) {
	// Pass true to gray out screen, false to ungray
	// options are optional.  This is a JSON object with the following (optional) properties
	// opacity:0-100
	// Lower number = less greyout higher = more of a blackout
	// zindex: #
	// HTML elements with a higher zindex appear on top of the gray out
	// bgcolor: (#xxxxxx)
	// Standard RGB Hex color code
	// fnGreyOutScreenWithMsg(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
	// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
	// in any order.  Pass only the properties you need to set.
	var options = options || {};
	var zindex = options.zindex || 50;
	var opacity = options.opacity || 70;
	var opaque = (opacity / 100);
	var bgcolor = options.bgcolor || '#000000';
	var col =  options.col || '#ffffff';
	var fnt =  options.fnt || 'Arial, Helvetica, sans-serif;';
	var fontsz =  options.fontsz || '12px';
	var dark=document.getElementById('darkenScreenObject');
	if (!dark) {
		// The dark layer doesn't exist, it's never been created.  So we'll
		// create it here and apply some basic styles.
		// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
		var tbody = document.getElementsByTagName("body")[0];
		var tnode = document.createElement('div');
		// Create the layer.
		tnode.style.position='absolute';
		// Position absolutely
		tnode.style.top='0px';
		// In the top
		tnode.style.left='0px';
		// Left corner of the page
		tnode.style.overflow='hidden';
		// Try to avoid making scroll bars
		tnode.style.display='none';
		// Start out Hidden
		tnode.id='darkenScreenObject';
		
		tnode.style.color=col;
		tnode.style.fontFamily=fnt;
		tnode.style.fontSize=fontsz;
		tnode.innerHTML = "<div align='center'>"+sMsg+"</div>";
		
		//tnode.attachEvent("onclick", "setTimeout('alert(\'Surprise!\')', 5000)"); 
		
		// Name it so we can find it later
		tbody.appendChild(tnode);
		// Add it to the web page
		dark=document.getElementById('darkenScreenObject');
		dark.onclick=function(){fnGreyOutScreenWithMsg(false, '','');};
		if(iDelayToKillBlackout<1) {
			setTimeout('fnGreyOutScreenWithMsg(false, \'\', \'\')', 500); //Kill the blackout in x seconds
		} else {
			setTimeout('fnGreyOutScreenWithMsg(false, \'\', \'\')', parseInt(iDelayToKillBlackout)*1000); //Kill the blackout in x seconds
		}
		// Get the object.
	}
	if (vis) {
		// Calculate the page width and height
		if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
			var pageWidth = document.body.scrollWidth+'px';
			var pageHeight = document.body.scrollHeight+'px';
		} else if( document.body.offsetWidth ) {
			var pageWidth = document.body.offsetWidth+'px';
			var pageHeight = document.body.offsetHeight+'px';
		} else {
			var pageWidth='100%';
			var pageHeight='100%';
		}
		//set the shader to cover the entire page and make it visible.
		dark.style.opacity=opaque;
		dark.style.MozOpacity=opaque;
		dark.style.filter='alpha(opacity='+opacity+')';
		dark.style.zIndex=zindex;
		dark.style.backgroundColor=bgcolor;
		dark.style.width= pageWidth;
		dark.style.height= pageHeight;
		dark.style.display='block';
	} else {
		dark.style.display='none';
	}
}

					
	function fnTimeNow() {
		var currentTime = new Date()
		var hours = currentTime.getHours()
		var minutes = currentTime.getMinutes()
		if (hours < 10) hours = "0" + hours
		if (minutes < 10) minutes = "0" + minutes
		return hours+":"+minutes
	}

