///////////////////////////////////////////////////////////////////////////
// This system include contains the following functions:                 //
//                                                                       //
// setOnChange()       set onchange handler for forms                    //
// openPopup()         open a modal dialog box                           //
// openMessage()       open generic OK message box                       //
// Installer updated:  Thu Sep 18 09:34:58 SAST 2003                     //
///////////////////////////////////////////////////////////////////////////

/*----------------------------------------------------------------------------------------------
  NOTE: The lines starting with '//UNCOMMENT' comment out the error trapping for debug purposes.
        The upgrade script will uncooment these before upload
        Do not touch these lines!
  ----------------------------------------------------------------------------------------------*/
//UNCOMMENTwindow.onerror = handleError;
//UNCOMMENTfunction handleError(){window.status = ""}
//window.onerror = handleError;
//function handleError(){window.status = ""}

//document.oncontextmenu = handleRightClick;
//function handleRightClick(){return false}

var isToolBarPage = false;
var monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"];
var saved_date;
var mainWindowPage;
var selectedProperties = "";
var selectedPropertyNames = "";
var selectedStatuses = "0:0:1:1:0";
var inputchange = false;        // Flag to test for field changes on a form
var savePressedButton = "";     // Save the putton pressed - used if save prompt triggered on toolbar
var saveURL = "";               // Save the menu URL - used if save prompt triggered on menu
var infoPopup = false;					// Popup window handle
var screenWidth=screen.availWidth;
var screenHeight=screen.availHeight;
var flag;
var flagSrc;
var timerID = "";
var infoTimer;
var delay = 800;
var popCal;
var pasteFieldId = false;                    // Id of focussed field into which 'Paste' toolbutton will paste
var dateElement;
var gotoCal = "";                            // Used to force goto Occ Cal from menu (see buttonPressGeneric_continue in tolbar.js)
var serverLocationLabel = "local";
var is_ie = document.all ? true : false;
var responseFunctions = new Array("processResponse");
var confirmAction = "";

//////////////////////////////////////////////////////////////////////////
// initialisePage() is called onLoad of all forms in system              //
// - setup toolbar image arrays and disable initial buttons              //
///////////////////////////////////////////////////////////////////////////
function initTop() {  
	var hostName				= parent.location.hostname;
	var hostNameArray		= hostName.split(".");
	var serverLocation	= hostNameArray[1];

	// Setup the URL links in the country drop-downs
	// to take the user to the correct client on the web
	if(id("serverSelect") ) {
		if(hostNameArray.length > 2) {
			id("serverSelect").options[1].value = SAServer;
			id("serverSelect").options[2].value = USServer;
		} else {
			id("serverSelect").options[0].value = "";
			id("serverSelect").options[1].value = SAServer;
			id("serverSelect").options[2].value = USServer;
		}
	}
  
	// If we are !localhost then remove "local" option
	// Else set local option and flag
	if(hostNameArray.length > 2) {
		if(id("serverSelect")) {
			id("serverSelect").remove(0);
		}
    
		switch ( serverLocation ) {
		case "us":
			serverLocationLabel = "US";
			id("flag").src = "images/top_usaflag.gif";
			if(id("serverSelect")) {
				id("serverSelect").selectedIndex = 1;
			}
			break;
		case "eu":
			serverLocationLabel = "EU";
			id("flag").src = "images/top_euflag.gif";
			if(id("serverSelect")) {
				id("serverSelect").selectedIndex = 2;
			}
			break;
		case "za":
			serverLocationLabel = "ZA";
			id("flag").src = "images/top_saflag.gif";
			if(id("serverSelect")) {
				id("serverSelect").selectedIndex = 0;
			}
			break;
		default:
			id("flag").src = "images/top_saflag.gif";
			if(id("serverSelect")) {
				id("serverSelect").selectedIndex = 0;
			}
		}
	} else {
		id("flag").src = "images/top_localflag.png";
		if(id("serverSelect")) {
			id("serverSelect").selectedIndex = 0;
		}
	}

	if(parent.LastUpdateDash) {
		/* Logged by MDB - (3/8/2004) ***********************************************
		The variable 'LastUpdate' has been changed to '01 Jan 2004' format
		'LastUpdateDash' is in 'DD-MM-YYYY' format.
		this is set up in reservation.php
		************************************************************************** */
		var _year = parent.LastUpdateDash.substr(0,4);
		var _month = parseInt(parent.LastUpdateDash.substr(5,2),10)-1;
		var _day = parent.LastUpdateDash.substr(8,2);
		var _time = parent.LastUpdateDash.substr(11,5);
	}
	if(id("top_clientlogo")) {
		id("top_clientlogo").src = LogoSrc;
	}
}

/*function showHideBrowser() {
	alert();
  //id("getBrowser").style.visibility = "hidden";
}*/

function concatElements() {
	for ( count = 0; count < arguments.length; count++ ) {
		elementNodeList = document.getElementsByTagName(arguments[count]);
		var nodeLength = elementNodeList.length;
		
		for ( countNode = 0; countNode < nodeLength; countNode++ ) {
			var sItem = elementNodeList.item(countNode);
			if ( !sItem.onchange ) {
				try {
					sItem.onchange = function() { inputchange = -1; };
				} catch(xxx) {}
			}
			
			if ( !sItem.onfocus ) {
				try {
					sItem.onfocus = function() { pasteFieldId = this.id; };
				}catch(xxx){}
			}
		}
	}
}

///////////////////////////////////////////////////////////////////////////
// This function will set the onchange event for all                     //
// input and select fields on a document                                 //
///////////////////////////////////////////////////////////////////////////
function setOnChange(){
   inputchange = false;
	concatElements('input', 'textarea', 'select');
}

///////////////////////////////////////////////////////////////////////////
// Open a popup window based on a set of parameters                      //
// passed                                                                //
///////////////////////////////////////////////////////////////////////////
var dialogWin = {};
dialogWin.dialogList = [];

if ( is_ie ) {
	if ( opener && !opener.closed && opener.dialogWin ) {
		dialogWin.topWindow = opener.dialogWin.topWindow;
	} else {
		dialogWin.topWindow = window;
		//window.onfocus = checkModalTop;
		//document.onclick = checkModalTop;
	}
}

var busyFocus = 0;

function checkModal() {
	if ( !opener || opener.closed ) {
		return true;
	}

  if ( dialogWin.topWindow.busyFocus === false ) {
		dialogWin.topWindow.focus();
    return true;
	}

  if ( !dialogWin.win || dialogWin.win.closed ) {
		dialogWin.topWindow.busyFocus = false;
    current = window;
    //current.doneFocus = false;
		while ( current.opener && !current.opener.closed ) {
			current.doneFocus = false;
      current = opener;
		}
    dialogWin.topWindow.doneFocus = false;
			return true;
		}

		if ( dialogWin.win.doneFocus !== true ) {
   		// setTimeout("dialogWin.win.doneFocus = true; dialogWin.win.focus();",200);
      dialogWin.win.focus();
   	}
	return true;
}

function checkModalTop() {
	if ( busyFocus ) {
		return false;
  }
  busyFocus = true;

	if ( !dialogWin || !dialogWin.win || dialogWin.win.closed ) {
		busyFocus = false;
    return true;
	}

	if ( dialogWin.win.doneFocus !== true ) {
		// setTimeout("dialogWin.win.doneFocus = true; dialogWin.win.focus();",217);
		dialogWin.win.focus();
	}
	return true;
}

//**************************
//  END MODAL DIALOG CODE
//**************************

// In order for the modal popups to work, the master window must have ONFOCUS set to 'checkModalTop',
// while the popup windows must have ONFOCUS set to 'checkModal'.

function closeAll() {
  //alert("removing " + dialogWin.dialogList.length + " windows");
  //alert(event.type + " is the type");
  //alert(dialogWin.topWindow.url + " to " +  dialogWin.topWindow.location);
	if ( !dialogWin.topWindow.closed ) {
		return false;
  }
  
	for ( count = 0; count < dialogWin.dialogList.length; count++ ) {
		try {
    	dialogWin.dialogList[count].close();
		} catch(xxx) {}
	}
	return true;
}

function closeCheck() {
	if ( !opener || opener.closed ) {
		window.close();
	} else {
  	setTimeout("closeCheck();",100);
	}
}

function openPopup(url,w,h,x,y,scroll,resize,name,onactivate,recheckDisabled) {
	var funcCheck;
	try { 
		funcCheck = (eval("nd instanceof Function"));
	} catch(xxx){}
	if ( funcCheck ) {
		nd();
	}

	if(!w) {w=300;}                          // Default width is 300px
	if(!h) {h=150;}                          // Default height is 150px
	if(!x) {x=screen.availWidth/2 - w/2;}    // X co-ord to center screen horizontally
	if(!y) {y=screen.availHeight/2 - h/2;}   // X co-ord to center screen virtically
	if(!name) {name="";}
	if(!onactivate) {onactivate="";}

	var sFeatures = "fullscreen=0,width=" + w + ",height=" + h + ",top=" + y + ",left=" + x + ",screenX=" + x + ",screenY=" + y;

	if(scroll) { sFeatures += ",scrollbars=yes"; }

	if(resize) { sFeatures += ",resizable=yes"; }

	if(is_ie) {
		if ( opener && !opener.closed && opener.dialogWin ) {
			dialogWin.topWindow = opener.dialogWin.topWindow;
		} else {
			dialogWin.topWindow = window;
		}
	}

	dialogWin.win = window.open(url,name,sFeatures);
	dialogWin.win.name = name;

	if ( !recheckDisabled ) {
		if ( is_ie ) {
			try {
				dialogWin.win.setTimeout("function window.reCheck() { var ccType=false; try { ccType = (closeCheck instanceof Function); } catch(xxx){} if( ccType == true) { if(opener && !opener.closed){ if(opener.nd) { try{ opener.nd(); } catch(xxx){} } } closeCheck(); "+ onactivate +"} else { setTimeout('window.reCheck();',400); } } window.reCheck();",400);
			} catch(xxx) {}
		} else {
			dialogWin.win.setTimeout("function reCheck() { var ccType=false; try { ccType = (closeCheck instanceof Function); } catch(xxx){} if( ccType == true) { if(opener && !opener.closed){ if(opener.nd) { try{opener.nd();} catch(xxx){} } } closeCheck(); "+ onactivate +"} else { setTimeout('reCheck();',400); } } reCheck();",400);
		}
	}
	return dialogWin.win;
}

///////////////////////////////////////////////////////////////////////////
// Close message window                                                  //
//                                                                       //
///////////////////////////////////////////////////////////////////////////
function closePopup(){
   try { opener.document.body.releaseCapture(); } catch(xxx) {}
   window.close();
}

///////////////////////////////////////////////////////////////////////////
// Open a modal message box (with OK button only)                        //
// openMessage (message,height,type,x-coord,ycoord)                      //
///////////////////////////////////////////////////////////////////////////
function openMessage(message,type,h,x,y) {
  var w = 318;                             // Width is 318px
  
	// Default height
	if ( !h ) {
		h = 120;
	}                           
  
	// Default to info box (as opposed to alert box)
	if ( !type ) {
		type = "i";
	}                     
	return openPopup("prompt.php?type=" + type + "$message=" + message,318,h);
}

function gotoMessage(message,type) {
	// Default to info box (as opposed to alert box)
	if ( !type ) {
		type = "i";
	}
  window.location = "prompt.php?type=" + type + "$message=" + message;
}

///////////////////////////////////////////////////////////////////////////
// Open a modal message box (with OK button only)                        //
// openMessage (message,height,type,x-coord,ycoord)                      //
///////////////////////////////////////////////////////////////////////////
function openConfirm(message,w,h) {
	
	if ( !w ) {
		w = 308;
	}
  
	if ( !h ) {
		h = 155;
	}                           
	return openPopup("confirm_yn.php?message=" + message,w,h);
}

///////////////////////////////////////////////////////////////////////////
// Add new contact - open type select (org/ind)                          //
///////////////////////////////////////////////////////////////////////////
function showContactType() {
	if ( inputchange ) {
		savePressedButton = "newContact";
		openPopup("savechanges.htm");
	} else {
  	openPopup('contact_orgind.htm',358,180);
	}
}

function Get_Cookie(name) {
	var start = document.cookie.indexOf(name+"=");
  var len = start+name.length+1;
  
	if ( (!start) && (name != document.cookie.substring(0,name.length)) ) {
		return null;
	}
  
	if (start == -1) {
		return null;
	}
  
	var end = document.cookie.indexOf(";",len);
  
	if (end == -1) {
		end = document.cookie.length;
	}
  return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
	document.cookie = name + "=" +escape(value) +
  
	((expires) ? ";expires=" + expires.toGMTString() : "") +
  ((path) ? ";path=" + path : "") +
	((domain) ? ";domain=" + domain : "") +
  ((secure) ? ";secure" : "");
}

///////////////////////////////////////////////////////////////////////////
// yesNoCancel() is called when a change is made on a form and the user  //
// tries to leave that form.                                             //
///////////////////////////////////////////////////////////////////////////
function yesNoCancel(returnValue) {
	switch(returnValue) {
  case "yes":
  	inputchange = 0;
    if ( savePressedButton !== "" ) {
			Set_Cookie("savePressedButton",savePressedButton);
		}
    
		if ( saveURL !== "" ) {
			Set_Cookie("saveURL",saveURL);
		}
    
		buttonPressGeneric_continue("Save");
    break;
	
	case "no":
  	inputchange = 0;
    if ( savePressedButton !== "" ) {
			buttonPressGeneric_continue(savePressedButton,false,"");
		}
    
		if ( saveURL !== "" ) {
			window.location = saveURL;
		}
		break;
	
	case "cancel":
  	saveURL = "";
    break;
	}
}

function showAbout() {
	openPopup('about.php',430,510);
}

///////////////////////////////////////////////////////////////////////////
// mainWindowFocus() - make sure popup is always in focus                //
// popupFocus() - focus the main window then the popup                   //
///////////////////////////////////////////////////////////////////////////
function mainWindowFocus(){
   // Turn this code below on to enable popup autofocus (and in popupFocus() )
   /*
   checkModalTop();
   */
   // END
   return true;
}

var oldActive;

function popupFocus(e){
// Turn this code below on to enable popup autofocus (and in mainWindowFocus() )
   /*
   checkModal();
   if(document.activeElement.tagName != "BODY") {
      oldActive = document.activeElement;
      setTimeout("oldActive.setActive(); oldActive.focus();",100);
   }
   */
// END
   return true;
}

function popupUnload(){
   try { opener.document.body.releaseCapture(); } catch(xxx) {}
}

function openInfoPop(url,e,w,h,x,y){
  if ( !w ) { w = 500; }            // Default width
  if ( !h ) { h = 370; }            // Default height
	if ( !x ) { x = e.screenX; }     // Default Mouse Position
   
	if ( !y ) {
		y = e.screenY;
  	if ( (y+h) > window.screen.height ) {
			y = window.screen.height - (h + 50);
		}
	}
  infoTimer = setTimeout("openInfoPop_timeout('"+url+"',"+w+","+h+","+x+","+y+")",delay);
}

function closeInfoPop() {
   //if(event.srcElement instanceof Object) {
   // alert(event.srcElement.id);
   //}
   window.close();
}

function setupInfoPop() {
   // This is for use later to get onblur closure of the info popup
/*
   document.onblur = closeInfoPop;
   document.onmouseout = closeInfoPop;
   onblur = closeInfoPop;
   onmouseout = closeInfoPop;
*/
}

function openInfoPop_timeout(url,w,h,x,y){
	infoPopup = openPopup(url,w,h,x+20,y+20,0,0,"infoPopup");
  infoPopup.focus();
  dialogWin.win.setTimeout("function window.reCheckInfoPop() { var ccType=false; try { ccType = (setupInfoPop instanceof Function); } catch(xxx){} if( ccType == true) { setupInfoPop(); } else { setTimeout('window.reCheckInfoPop();',100); } } window.reCheckInfoPop();",100);
}

function cancelTimer(){
	clearTimeout(infoTimer);
}

function windowUnload(){
	// Called by most forms on unload
}

/////////////////////////////////////////////////////////////
// Function to open menu link                              //
/////////////////////////////////////////////////////////////
function gotoLink(URL) {
	if ( inputchange ) {
		saveURL = URL;
    openPopup("savechanges.htm");
    return true;
	}

  // If we are going to Occ Cal then check if we must filter by agent
  if ( URL == "reservation.php?29" ) {
		window.location = "reservation.php?29";
    return true;
	}
  
	// DEBUG - cludge for 'About resrequest.com'
  if ( URL == "reservation.php?533" ) {
		openPopup(URL,400,450);
		return true;
	}

	window.location = URL;
  return true;
}

function dataTransfer() {
	openPopup('reservation.php?128',358,270);
}

function dbStatusChange(job) {
	switch (job) {
	case 4:
   	openPopup('reservation.php?704',358,213);
     break;

	case 3:
  	openPopup('reservation.php?703',358,213);
		break;

	case 2:
  	openPopup('reservation.php?702',358,213);
    break;

	default:
  	openPopup('reservation.php?701',358,213);      
	}
}

function cacheClear() {
	openPopup('reservation.php?263',358,213);
}

function visitWebsite() {
	window.open(sysURL,'website','resizable=yes');
}

function visitOnlineSurvey() {
	window.open('http://www.divtech.co.za/bizapp/login.cfm','onlinesurvey','resizable=yes');
}

function visitAnalytics() {
	window.open('http://analytics.google.com','analytics','resizable=yes');
}


/////////////////////////////////////////////////////////////
// Date picker window                                      //
/////////////////////////////////////////////////////////////
function openCalendar(srcForm,dateEl,w,h) {
	// Save a pointer to the date drop-down we want to set
	// Used for reports with more than one date select on screen
  dateElement = dateEl;
	var form;

	if ( publicPage === true ) {
		form = document.forms[1];
	} else {
  	form = document.forms[0];
	}

	switch ( dateElement ) {
	case 'start':
  	document.forms[0].selectDay.value		= document.forms[0].startday.selectedIndex;
    document.forms[0].selectMonth.value	= document.forms[0].startmonth.selectedIndex;
    document.forms[0].selectYear.value	= document.forms[0].startyear.value;
    break;
	
	case 'end':
  	document.forms[0].selectDay.value		= document.forms[0].endday.selectedIndex;
    document.forms[0].selectMonth.value	= document.forms[0].endmonth.selectedIndex;
    document.forms[0].selectYear.value	= document.forms[0].endyear.value;
		break;

	case 'quickstart':
  	document.forms[0].selectDay.value		= id("select_day").selectedIndex;
    document.forms[0].selectMonth.value	= id("select_month").selectedIndex;
    document.forms[0].selectYear.value	= id("year").value;
    break;
	
	default:
  	document.forms[0].selectDay.value		= document.forms[0].select_day.selectedIndex;
    document.forms[0].selectMonth.value	= document.forms[0].select_month.selectedIndex;
    document.forms[0].selectYear.value	= document.forms[0].year.value;
	}

	if ( isNaN(document.forms[0].selectYear.value) || document.forms[0].selectYear.length < 4 ) {
		openMessage("Please enter a valid year");
    return 0;
	}

	var screenWidth		= screen.availWidth;
  var screenHeight	= screen.availHeight;

	// Horribly non-cross-browser friendly. Let's just ignore.
	// screenPosX = event.screenX;
	// screenPosY = event.screenY;
  
	openPopup(srcForm,170,170);//,screenPosX,screenPosY);
}

function setSelectedDate(date) {
   var dateArray = date.split("-");
   
	 var year		= dateArray[0];
   var month	= dateArray[1];
   var day		= dateArray[2];
	 
	 var form;

	if ( publicPage === true ) {
		form = document.forms[1];
	} else {
  	form = document.forms[0];
	}
	
	switch ( dateElement ) {
	case 'start':
  	document.forms[0].startday[day].selected			= true;
    document.forms[0].startmonth[month].selected	= true;
    document.forms[0].startyear.value							= year;
    break;

	case 'end':
  	document.forms[0].endday[day].selected			= true;
    document.forms[0].endmonth[month].selected	= true;
    document.forms[0].endyear.value							= year;
		break;

	case 'quickstart':
  	changed_date = year + "-" + month + "-" + day;
    gotoQuick(changed_date);
		//return 0;
		break;

	default:
  	if ( mainWindowPage != "reportExtra" && mainWindowPage != "resExtras"  && mainWindowPage != "wizard_step_2_int" && mainWindowPage != "reportSurvey" && mainWindowPage != "reviewSurvey"  && mainWindowPage != "wizard_step_2_int" && mainWindowPage != "quickExtrasEntry" && mainWindowPage != "roomExtrasEntry" && mainWindowPage != "rep_guest_history"  && mainWindowPage != "invoice_report" && mainWindowPage != "contactCRM_pop"   && mainWindowPage != "rep_crm_custom"  && mainWindowPage != "tax_analysis_report" && mainWindowPage != "discrepancy_report") {
		document.forms[0].select_day[day].selected			= true;
      document.forms[0].select_month[month].selected	= true;
      document.forms[0].year.value										= year;
		} else {
			id(dateObj+"Day").selectedIndex		= day;
      id(dateObj+"Month").selectedIndex = month;
      id(dateObj+"Year").value					= year;
	  if( mainWindowPage == "resExtras" || mainWindowPage == "wizard_step_2_int") {
		 setArrDepDate(dateObj);
	  }
		}
	}
  
	if ( mainWindowPage != "reportExtra" && mainWindowPage != "resExtras" && mainWindowPage != "wizard_step_2_int" && mainWindowPage != "reportSurvey" && mainWindowPage != "reviewSurvey" && mainWindowPage != "quickExtrasEntry" && mainWindowPage != "roomExtrasEntry"  && mainWindowPage != "rep_guest_history" && mainWindowPage != "invoice_report" && mainWindowPage != "contactCRM_pop"   && mainWindowPage != "rep_crm_custom" && mainWindowPage != "codePeriodDates"  && mainWindowPage != "tax_analysis_report" && mainWindowPage != "discrepancy_report") {
		reloadPage();
	}
	
	try {
		document.body.releaseCapture(); 
	} catch(xxx) {}
}

function openHelp() {
	openPopup('help/help_frame.htm',690,430,120,100,1,1,'Help_Window');
}

function openHelpdesk() {
	var url				= "http://helpdesk.resrequest.com";
	var name			= "Helpdesk";
	var sFeatures = "fullscreen=0,width=700,height=500,top=100,left=100,screenX=100,screenY=100,scrollbars=yes,resizable=yes";
	var helpdesk	= window.open(url,name,sFeatures);
}

/////////////////////////////////////////////////////////////
// Date manipulation functions                             //
/////////////////////////////////////////////////////////////
function DayAdd(startDate,numDays) {
	return DateAdd(startDate,numDays,0,0);
}

function DateAdd(startDate,numDays,numMonths,numYears) {
	var returnDate	= new Date(startDate.getTime());
  var yearsToAdd	= numYears;
	var month 			= returnDate.getMonth() + numMonths;
  
	if ( month > 11 ) {
		yearsToAdd	= Math.floor((month+1)/12);
    month				-= 12*yearsToAdd;
    yearsToAdd	+= numYears;    
	}
   
	returnDate.setMonth(month);
  returnDate.setFullYear(returnDate.getFullYear() + yearsToAdd);
  returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);

  return returnDate;
}

function chngDate(startDate) {
	var dateArray = startDate.split("-");
  
	newY = parseInt(dateArray[0],10);
  newM = parseInt(dateArray[1],10);
  newD = parseInt(dateArray[2],10);
  newMonth = monthNames[newM-1];
  newDate = newD + " " + newMonth + " " + newY;
	
	return newDate;
}

/////////////////////////////////////////////////////////////
// Calculates valid days in a month/year combo             //
// (includes leap year support)                            //
/////////////////////////////////////////////////////////////
function getMonthDays(month,year) {
	if ( month == "2" ) {
		daysTmp = "28";    
		if ( year % 100 == "0" ) {			
			if ( year % 400 == "0" ) {
				daysTmp = 29;
			}
		} else {
    	if ( year % 4 == "0" ) {
				daysTmp = 29;
			}
		}
	} else if (month == "4" || month == "6" || month == "9" || month == "11") {
		daysTmp = "30";
	} else {
  	daysTmp = "31";
	}
  return parseInt(daysTmp,10);
}

/////////////////////////////////////////////////////////////
// Sets a day dropdown depending on the month/year combo   //
/////////////////////////////////////////////////////////////
function setDayList(dayObject,month,year) {
	daysTmp = getMonthDays(month,year);

  day = dayObject.selectedIndex;  
	dayObject.options.length = 0;
  dayObject.options[0] = new Option("",0);

	for ( i = 1; i < daysTmp + 1; i++ ) {
		dayObject.options[i] = new Option((i<10?"0"+i.toString():i),i);
	}
  if ( day > daysTmp ) {
		day = daysTmp;
	}
  dayObject.selectedIndex = day;
}

function setDayList2(dayObject,month,year) {
	daysTmp = getMonthDays(month,year);

	day = dayObject.selectedIndex;
  dayObject.options.length = 0;
  
	for ( i = 1; i < daysTmp + 1; i++ ) {
		dayObject.options[i-1] = new Option((i<10?"0"+i.toString():i),i);
	}
  
	if ( day > daysTmp ) {
		day = daysTmp;
	}
	dayObject.selectedIndex = day;
}

/////////////////////////////////////////////////////////////
// Shortening for document.getElementById(tagID)           //
/////////////////////////////////////////////////////////////
function id(tagId) {
	return (document.getElementById) ? document.getElementById(tagId) : document.all[tagId];
}

function selIndex(objectId) {
	return id(objectId).options[id(objectId).selectedIndex].index;
}

function selValue(objectId) {
	return id(objectId).options[id(objectId).selectedIndex].value;
}

function selLabel(objectId) {
	return id(objectId).options[id(objectId).selectedIndex].innerHTML;
}

function selMIndex(objectId) {
	var result = [];
	var element = id(objectId).options;
	
	for ( i = 0; i < element.length; i++ ) {
		if ( element[i].selected ) {
			result[result.length] = element[i].index;
		}
	}
	return result;
}

function selMValue(objectId) {
	var result = [];
  var element = id(objectId).options;
  
	for ( i = 0; i < element.length; i++ ) {
		if ( element[i].selected ) {
			result[result.length] = element[i].value;
		}
	}
  return result;
}

function selMLabel(objectId) {
	var result = [];
  var element = id(objectId).options;
  
	for ( i = 0; i < element.length; i++ ) {
		if ( element[i].selected ) {
			result[result.length] = element[i].innerHTML;
		}
	}
  return result;
}

/////////////////////////////////////////////////////////////
// Check an input for 2 decimal places                     //
/////////////////////////////////////////////////////////////
function checkDecimal(obj) {
	if ( obj.value.search(/\.\d{3,}$/) != -1 ) {
		obj.focus();
    openMessage("Please enter a" + (name.substr(0,1).search(/[aeiouAEIOU]/)?"":"n") + " " + name + " with only 2 decimal places");
		return false;
	}
  return true;
}

/////////////////////////////////////////////////////////////
// Check an input for a percentage with 2 decimal places   //
/////////////////////////////////////////////////////////////
function checkPercent(obj,name,range) {
	if ( !range ) {
		range = "";
	}
  
	obj.value = obj.value.replace(/\s+/g,"");
  
	if ( checkDecimal(obj) === false ) {
		return false;
	}
  
	if ( obj.value.search(/^\d{1,3}(\.\d{1,2})*$/) == -1 ) {
		obj.focus();
    openMessage("Please enter a"+(name.substr(0,1).search(/[aeiouAEIOU]/)?"":"n")+" "+name+" "+range);
    return false;
	}
  
	if ( obj.value < 0 || obj.value > 100 ) {
		obj.focus();
    openMessage("Please enter a" + (name.substr(0,1).search(/[aeiouAEIOU]/)?"":"n") + " " + name + " " + range);
    return false;
	}
	return true;
}

/////////////////////////////////////////////////////////////
// Check an input for a number with 2 decimal places       //
/////////////////////////////////////////////////////////////
function checkNumber(obj,name) {
	obj.value = obj.value.replace(/\s+/g,"");
  
	if ( checkDecimal(obj) === false ) {
		return false;
	}
  
	if ( obj.value.search(/^\d+(\.\d+)*$/) == -1 ) {
		obj.focus();
		openMessage("Please enter a valid "+name);
    return false;
	}
	return true;
}

/////////////////////////////////////////////////////////////
// Clear date slect boxes                                  //
/////////////////////////////////////////////////////////////
function resetDate() {
	id("select_day").selectedIndex = 0;
  id("select_month").selectedIndex = 0;
  id("year").value = "";
  inputchange = -1;
}

function getBrowserVersion() {
	// convert all characters to lowercase to simplify testing
  var agt = navigator.userAgent.toLowerCase();

	// *** BROWSER VERSION ***
  // Note: On IE5, these return 4, so use is_ie5up to detect IE5.
  var is_major = parseInt(navigator.appVersion,10);
  var is_minor = parseFloat(navigator.appVersion);

  var is_ie     	= ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
  var is_ie3    	= (is_ie && (is_major < 4));
  var is_ie4    	= (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
  var is_ie5    	= (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
  var is_ie5_5up	= (is_ie && !is_ie3 && !is_ie4 && !is_ie5);

	if ( !is_ie ) {
		return "nav";
	}

	if ( is_ie5_5up ) {
		return true;
	} else {
		return false;
	}
}

var browserVersion = getBrowserVersion();

// [MN] - toggleColumn()
// If showHide is true -> Expand Columns
// If showHide is false -> Collapse Column
// Must have: 2 showHide buttons by the names of showBut & showBut2
// Rows to have NAME='x' AND ID='x'
// Header to have NAME='xHeader' ID='xHeader'
// Footer (bottom border) to have NAME='xFooter' ID='xFooter'
// Add '<td id="extraCol" style="width:0;"></td>' in header row and rows as last <td>

//NOTE: Need to handle columns with class that give a bgcolor.
//eg. Comm columns on the extras report, onclick of 'show all' the bgcolor class was replaced by txt
function toggleColumn(showHide) {
	extraCols = document.getElementsByName("extraCol");
  if ( showHide === true ) {
		for ( i = 0; i < extraCols.length; i++ ) {
			extraCols[i].style.width = 0;
		}
    headClass = "outLt";
    rowClass = "txt";
  
    footClass = "bt";
    id("showBut").className		= "collapse printCollapse";
    id("showBut2").className	= "collapse printCollapse";
	} else {
		headClass = rowClass	= footClass = "collapse printCollapse";
  	
		id("showBut").className		= "button bArrDes";
  	id("showBut2").className	= "button bArrDes";
	}
	
	for ( i = 1; i < arguments.length; i++ ) {
		headList = document.getElementsByName(arguments[i]+"Header");
    footList = document.getElementsByName(arguments[i]+"Footer");
    
		for ( l = 0; l < headList.length; l++ ) {
			headList[l].className = headClass;
		}
    
		for ( l = 0; l < footList.length; l++ ) {
			footList[l].className = footClass;
		}
    
		if ( showHide !== true ) {
			for ( e = 0; e < extraCols.length; e++ ) {
				extraCols[e].style.width = parseInt(extraCols[e].style.width,10) + parseInt(headList[0].offsetWidth,10);
        if ( parseInt(extraCols[e].style.width,10) > 130 ) {
					extraCols[e].style.width = 130;
				}
			}
		}
    itemList = document.getElementsByName(arguments[i]);
    
		for (l = 0; l < itemList.length; l++ ) {
			itemList[l].className = rowClass;
		}
	}
}

// Function set the amount of decimal places on a number
// Takes 'val' and ensures that is has 'num' decimal places
function fixAmtDisplay(val, num) {
  if ( isNaN(val) ) {
		return false;
	}

  if ( !num ) {
	 	num = 2;
	}

	// Round off any extra decimal places
  val = ( Math.round(parseFloat(val) * Math.pow(10,num)) / Math.pow(10,num) ).toString();

  // Add any extra decimal places required
  list = val.split(".");
  
	if ( list.length == 1 ) {
		list[1] = "";
	}
	
	diff = num - list[1].length;
  
	for ( c = 0; c < diff; c++ ) {
		list[1] += "0";
	}
  return list.join(".");
}

var mnuSelectArray = []; // Name needs to be changed at some stage

function buildSelectArray() {
  mnuSelectArray = [];
  selectList = document.getElementsByTagName("SELECT");
   
	for ( var count = 0; count < selectList.length; count++ ) {
  	selectList[count].startClass = selectList[count].className;
		currElement = selectList[count];
		currLeft = 0;
		currTop = 0;
      
		while ( currElement ) {
			currLeft			+= currElement.offsetLeft;
			currTop 			+= currElement.offsetTop;
			currElement	= currElement.offsetParent;
		}

		selectItem = {};
		selectItem.left			= currLeft;
		selectItem.top			= currTop;
		selectItem.width		= selectList[count].offsetWidth;
		selectItem.height		= selectList[count].offsetHeight;
		selectItem.right		= currLeft + selectList[count].offsetWidth;
		selectItem.bottom		= currTop + selectList[count].offsetHeight;
		selectItem.element	= selectList[count];

		mnuSelectArray[mnuSelectArray.length] = selectItem;
	}
}

function openPaxMenu() {
	var startDate = "";
	openPopup('reservation.php?736+'+startDate,648,294);
}

function getLeft(obj) {
	curr = obj;
	currLeft = 0;
	while(curr && curr.tagName != "BODY") {
		currLeft += curr.offsetLeft;
		curr = curr.offsetParent;
	}
	return currLeft;
}


function getTop(obj) {
	curr = obj;
	currTop = 0;
	while(curr && curr.tagName != "BODY") {
		currTop += curr.offsetTop;
		curr = curr.offsetParent;
	}
	return currTop;
}

function _getLeft(obj) {
	curr = obj;
	currLeft = 0;
	while(curr && curr.tagName != "BODY") {
		currLeft += curr.offsetLeft;
		curr = curr.offsetParent;
	}
	return currLeft;
}


function _getTop(obj) {
	curr = obj;
	currTop = 0;
	while(curr && curr.tagName != "BODY") {
		currTop += curr.offsetTop;
		curr = curr.offsetParent;
	}
	return currTop;
}

function setRowHover(obj) {
	obj.style.backgroundColor = '#CCFFCC';
}

function clearRowHover(obj) {
	obj.style.backgroundColor = '';
}

function chngBox(boxId){
	var box = id(boxId);
  
	if ( box.getAttribute("type") == "checkbox" ) {
		box.checked = !box.checked;
	} else {
  	box.checked = true;
	}
}

function showMessage(sMessage,sTitle,sWidth,sHeight) {
	if(!sTitle) { sTitle = "Notice"; }
	if(!sWidth) { sWidth = 300; }
	var tempDiv = document.createElement("div");
	tempDiv.id = "tempMessageDiv";
	tempDiv.style.width = sWidth;
	if(sHeight) {
		tempDiv.style.height = sHeight;
	}
	tempDiv.style.position = "absolute";
	tempDiv.innerHTML = 
		
		"<table class=\"outLtt bAll\" width=\"100%\">" +
		"<tr><td class=\"outLt txtb\" align=\"center\">" + sTitle + "</td></tr>" +
		"<tr><td align=\"center\">" + sMessage + "</td></tr>" +
		"<tr><td height=\"5\"><img src=\"images/1x1.gif\"></td></tr><tr><td align=\"center\"><input type=\"button\" class=\"button\" value=\" Ok \" onclick=\"destroyShowMessage();\"></td></tr><tr><td height=\"5\"><img src=\"images/1x1.gif\"></td></tr>" +
		"</table>";
	document.body.appendChild(tempDiv);
	tempDiv.style.left = document.body.offsetWidth / 2 - tempDiv.offsetWidth / 2;
	tempDiv.style.top = document.body.offsetHeight / 2 - tempDiv.offsetHeight / 2;
}

function destroyShowMessage() {
	document.body.removeChild(document.body.childNodes[document.body.childNodes.length-1]);	
}

function showList(sList,sTitle,sWidth,sHeight) {
	if(!sTitle) { sTitle = "Notice"; }
	if(!sWidth) { sWidth = 300; }
	if(!sHeight) { sHeight =  200; }
	var tempDiv = document.createElement("div");
	tempDiv.id = "tempListDiv";
	tempDiv.style.width = sWidth;
	if(sHeight) {
		tempDiv.style.height = sHeight;
	}
	tempDiv.style.position = "absolute";
	listRows = "";
	for(count = 0; count < sList.length; count++) {
		listRows += "<tr><td>" + sList[count] + "</td></tr>";
	}
	tempDiv.innerHTML = 
		
		"<table class=\"outLtt bAll\" width=\"100%\">" +
		"<tr><td class=\"outLt txtb\" align=\"center\">" + sTitle + "</td></tr>" +
//		"<tr><td align=\"center\">" + sMessage + "</td></tr>" +
		"<tr><td><div class=\"bAll\" style=\"width: " + sWidth + "; height: " + sHeight + "; overflow-y: scroll; background-color: #ffffff;\">" +
		"<table width=\"100%\">" + listRows + "</table></div></td></tr>" + 
		"<tr><td height=\"5\"><img src=\"images/1x1.gif\"></td></tr><tr><td align=\"center\"><input type=\"button\" class=\"button\" value=\" Ok \" onclick=\"destroyShowList();\"></td></tr><tr><td height=\"5\"><img src=\"images/1x1.gif\"></td></tr>" +
		"</table>";
	document.body.appendChild(tempDiv);
	tempDiv.style.left = document.body.offsetWidth / 2 - tempDiv.offsetWidth / 2;
	tempDiv.style.top = document.body.offsetHeight / 2 - tempDiv.offsetHeight / 2;
}

function destroyShowList() {
	// IE only... id("tempListDiv").removeNode(true);
	document.body.removeChild(document.body.childNodes[document.body.childNodes.length-1]);
}


function checkEmail(cEmail) {
	return (/^\w+([\.\+-]?\w+)*@\w+([\.-]?\w+)*$/.test(cEmail));
}

function windowWidth() {
	if ( self.innerWidth ) {	// All browsers except Explorer
		frameWidth = self.innerWidth;
	}	else if (document.documentElement && document.documentElement.clientWidth) {	// IE 6 Strict mode
		frameWidth = document.documentElement.clientWidth;
	} else if (document.body) {	// All other IE versions
		frameWidth = document.body.clientWidth;
	} else {
		return;
	}

	return frameWidth;

}

function windowHeight() {
	if ( self.innerHeight ) {	// All browsers except Explorer
		frameHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {	// IE 6 Strict mode
		frameHeight = document.documentElement.clientHeight;
	} else if (document.body) {	// All other IE versions
		frameHeight = document.body.clientHeight;
	} else {
		return;
	}
	return frameHeight;
}

function windowResize(w,h) {
	window.resizeTo(w,h);
	var extraWidth = w - windowWidth() ;
	var extraHeight = h - windowHeight();
	
	if ( extraWidth < 0 ) {
		extraWidth = 0;
	}
	
	if ( extraHeight < 0 ) {
		extraHeight = 0;
	}
	window.resizeTo(w+extraWidth,h+extraHeight);
}

// Returns the height of the entire HTML page
// i.e. including areas outside the viewport
function pageHeight() {
	var docHeight;

	if ( typeof document.height != 'undefined' ) {
		docHeight = document.height;
	} else if ( document.compatMode && document.compatMode != 'BackCompat' ) {
		docHeight = document.documentElement.scrollHeight;
	} else if ( document.body && typeof document.body.scrollHeight != 'undefined' ) {
		docHeight = document.body.scrollHeight;
	}
	
	return docHeight;
}

function applyTrans(i) {
	var docHeight = pageHeight();
	
	
	// If docHeight < windowHeight, we're going to look a bit stupid, so make sure
	// it is at least the same as the window height
	if ( docHeight < windowHeight() ) {
		docHeight = windowHeight();
	}

	if ( !id("trans") ) {
		// The transparent div doesn't exist, so bung it in
		var transDiv;

		transDiv = document.createElement("DIV");

		transDiv.id							= "trans";		
		transDiv.style.display	= "none";
		transDiv.className			= "lightbox";
	
		document.body.appendChild(transDiv);
	}


	// Find all the select elements that IE6 will display through any divs
	var s;
	s = document.getElementsByTagName("SELECT");
	var count;

	if ( i > 0 ) {
		for ( count = 0; count < s.length; count++ ) {
			if ( s[count].style.zIndex < 99 && s[count].style.display != "none" && s[count].style.visibility != "hidden" ) {
				s[count].style.display = "none";
			}			
		}
		
		id("trans").style.height	= docHeight + "px";
		id("trans").style.width		= windowWidth() + "px";
		
		id("trans").style.display = "";
	} else {
		for ( count = 0; count < s.length; count++ ) {
			if ( s[count].style.zIndex < 99 ) {
				s[count].style.display = "";
			}			
		}
		id("trans").style.display = "none";
	}
}

function centerDivOnPage(aID) {
	id(aID).style.display = "";
	divWidth	= parseInt(id(aID).style.width,10);
	divHeight = parseInt(id(aID).offsetHeight,10);

	// Hide while moving to avoid IE bug
	id(aID).style.display = "none";
	id(aID).style.top = (windowHeight()-divHeight)/2 + f_scrollTop() + "px";
	id(aID).style.left = (windowWidth()-divWidth)/2 + "px";
	id(aID).style.display = "";
}

function getClickPosition(e,axis) {
	var posx = 0;
	var posy = 0;

	if (!e) {
		e = window.event;
	}

	if ( e.pageX || e.pageY ) 	{
		posx = e.pageX;
		posy = e.pageY;
	}	else if ( e.clientX || e.clientY ) 	{
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}
	if ( axis == "x" ) {
		return posx;
	} else {
		return posy;
	}
}

function getEventTarget(e) {
	if (!e) {
		e = window.event;
	}

	if ( e.target ) {
		targ = e.target;
	}  else if ( e.srcElement ) {
		targ = e.srcElement;
	}

	if ( targ.nodeType == 3 ) {
		// defeat Safari bug
		targ = targ.parentNode;
	}
	return targ;
}

function stopBubble(e) {
	if ( !e ) {
		e = window.event;
	}
	e.cancelBubble = true;
	if (e.stopPropagation) {
		e.stopPropagation();
	}
}

/* 
	URL encoding and decoding functions to be used instead of "escape" to match up with
	the php urlencode and urldecode functions.

	Source: http://cass-hacks.com/articles/code/js_url_encode_decode/ 
*/
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match !== null && match.length > 1 && match[1] !== '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ') {
    		output += '+';
			} else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
		if(hexVal.length == 1) {
			hexVal = "0" + hexVal;
		}
        output += '%' + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[0-9ABCDEFabcdef]{2})/;
  while ((match = myregexp.exec(output)) !== null
             && match.length > 1
             && match[1] !== '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

	
function alignDivToElement(aElm, tElm, x, y, extraX, extraY) {
// PARAMETERS /////////////////////////////////////////////////////////////////
//	aElm: string id of element you want to align                             //
//	tElm: string id of element you want to align to                          //
//	x: string "left" or "right"                                              //
//	y: string "top" or "bottom"                                              //
//	extraX: integer value for any extra horizontal positioning in pixels     //
//	extraY: integer value for any extra vertical positioning in pixels       //
///////////////////////////////////////////////////////////////////////////////
	if ( !x )				{ x = "left"; }
	if ( !y )				{ y = "bottom"; }
	if ( !extraX )	{ extraX = 0; }
	if ( !extraY )	{ extraY = 0; }

	// Get the target element's position
	tPos = findPos(id(tElm));

	if ( x == "left" ) {
		id(aElm).style.left = tPos[0] + extraX;
	} else {
		id(aElm).style.left = id(tElm).offsetWidth + tPos[0] + extraX;
	}

	if ( y == "top" ) {
		id(aElm).style.top = tPos[1] - id(aElm).offsetHeight + extraY;
	} else {
		id(aElm).style.top = id(tElm).offsetHeight + tPos[1] + extraY;
	}
}

function findPos(obj) {
	var curleft	= 0;
	var curtop	= 0;

	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;

		// This is NOT an error!
		while ( obj = obj.offsetParent ) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}


// START - Input number handling routines
function isInteger(e,max) {
	var result = false;
	var code = e.keyCode;

	isAllowed = (code < 47) || (code > 111 && code < 124); // Control keys and F keys

	if(isAllowed) {
		result = true;
	} else {
		if(code >= 96 && code <= 105) code -= 48; // Fix numeric pad 0-9
		var codeChar = String.fromCharCode(code);
		var codeNum = parseInt(codeChar,10);		
		var targ;
		if (e.target) {
			targ = e.target;
		} else if (e.srcElement) {
			targ = e.srcElement;
		}

		if (targ.nodeType == 3) targ = targ.parentNode;

		var val = targ.value.toString();
		
		if(codeNum >= 0 && codeNum <= 9 && (val.length < max || !max)) {
			result = true;
		} else {
			result = false;
		}

	}
	e.returnValue = result;
	return result;
}


function isFloat(e, max) {
	var result = false;
	var code = e.keyCode;

	isAllowed = (code < 47) || (code > 111 && code < 124); // Control keys and F keys

	if(isAllowed) {
		result = true;
	} else {
		if(code >= 96 && code <= 105) code -= 48; // Fix numeric pad 0-9
		if(code == 110) code = 190; // Fix numeric pad .
		if(code == 189) code = 109; // Fix -
		var codeChar = String.fromCharCode(code);
		var codeNum = parseInt(codeChar,10);
		// Code to compensate for the broken fromCharCode / keyCode routines.
		var period = 190;
		var dash = 109;

		var targ;
		if (e.target) {
			targ = e.target;
		} else if (e.srcElement) {
			targ = e.srcElement;
		}

		if (targ.nodeType == 3) targ = targ.parentNode;

		var val = targ.value.toString();

		if(is_ie) {
			targ.focus();
			var range = document.selection.createRange();
			range.text = String.fromCharCode(code);
			var new_val = targ.value.toString();
		} else {
			var start = targ.selectionStart; 
			var end = targ.selectionEnd;
			if(start == 0) {	
				var new_val = String.fromCharCode(code) + val;
			} else {
				var new_val = val.slice(0,start) + String.fromCharCode(code) + val.slice(end-1,val.length-1);
			}
		}
		
		if(
			(codeNum >= 0 && codeNum <= 9) ||
			(code == period && val.indexOf(".") == -1) ||
			(code == dash && val.indexOf("-") == -1)
		) {
			if( (new_val.indexOf(".") != -1 && new_val.substr(new_val.indexOf(".")+1).length <= max) || new_val.indexOf(".") == -1 || !max) {
				if(code == dash && new_val.charAt(0) != String.fromCharCode(dash)) {
					result = false;
				} else {
					result = true;
				}
			} else {
				result = false;
			}
		}
		if(is_ie) {
			if(document.selection.type != "None") {
				document.selection.clear();
				targ.value = new_val;
			}
			if(result && codeNum >= 0 && codeNum <= 9) {
				result = false;
			} else {
				if(result && code == dash) {
					targ.value = new_val.replace(String.fromCharCode(dash),"-");
					result = false;
				} else if(result && code == period) {
					targ.value = new_val.replace(String.fromCharCode(period),".");
					result = false;
				} else {
					targ.value = val;
				}
			}
		}
	}
	e.returnValue = result;
	return result;
}

function checkInteger(e,min) {
	var targ	= getEventTarget(e);
	var val		= parseInt(targ.value.toString(),10);
	if(val < min || isNaN(val)) {
		val = min;
	}
	targ.value = val;
	return true;
}

function checkFloat(e,max) {
	var targ = getEventTarget(e);
	if ( !max ) {
		max = 2;
	}
	val = parseFloat(targ.value.toString());
	if ( isNaN(val) ) {
		val = "0";
	}

	val = val.toString();

	if ( val.indexOf(".") == -1 ) {
		val += ".";
		for ( count = 0; count < max; count++ ) {
			val += "0";
		}
	} else {
		var upper = max - (val.substr(val.indexOf(".")+1).length);
		for ( count = 0; count < upper; count++ ) {
			val += "0";
		}
	}
	targ.value = val;
}
// END - Input number handling routines

function collapseCol(colID,mode) {
	var column_display;
	var colArray = [];

	if ( !mode ) {
		mode = 0;
	}

	if ( mode > 0 ) {
		column_display = "";
	} else {
		column_display = "none";
	}

	if ( id(colID) ) {
		id(colID).style.display = column_display;
	}

	var colArray = document.getElementsByName(colID);
	for ( var i = 0; i < colArray.length; i++ ) {
		colArray[i].style.display = column_display;
	}
}

function getNextSibling(aID) {
	var n = id(aID);
	do n = n.nextSibling;
	while (n && n.nodeType != 1);
	return n;
}

// This function inserts myValue at the cursor position inside myField.
function insertAtCursor(myField, myValue) {
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
}

function openPreferences(w,h) {
	var funcCheck;
	try { 
		funcCheck = (eval("nd instanceof Function"));
	} catch(xxx){}
	if ( funcCheck ) {
		nd();
	}

	if(!w) {w=300;}                          // Default width is 300px
	if(!h) {h=150;}                          // Default height is 150px
	x=screen.availWidth/2 - w/2;    // X co-ord to center screen horizontally
	y=screen.availHeight/2 - h/2;   // X co-ord to center screen virtically

	var sFeatures = "fullscreen=0,width=" + w + ",height=" + h + ",top=" + y + ",left=" + x + ",screenX=" + x + ",screenY=" + y;

	if(is_ie) {
		if ( opener && !opener.closed && opener.dialogWin ) {
			dialogWin.topWindow = opener.dialogWin.topWindow;
		} else {
			dialogWin.topWindow = window;
		}
	}
	
	referringJob = escape(window.location.search.substr(1,3));

	dialogWin.win = window.open("reservation.php?780+"+referringJob,'',sFeatures);
	dialogWin.win.name = name;

	if ( is_ie ) {
		try {
			dialogWin.win.setTimeout("function window.reCheck() { var ccType=false; try { ccType = (closeCheck instanceof Function); } catch(xxx){} if( ccType == true) { if(opener && !opener.closed){ if(opener.nd) { try{ opener.nd(); } catch(xxx){} } } closeCheck(); } else { setTimeout('window.reCheck();',400); } } window.reCheck();",400);
		} catch(xxx) {}
	} else {
		dialogWin.win.setTimeout("function reCheck() { var ccType=false; try { ccType = (closeCheck instanceof Function); } catch(xxx){} if( ccType == true) { if(opener && !opener.closed){ if(opener.nd) { try{opener.nd();} catch(xxx){} } } closeCheck(); } else { setTimeout('reCheck();',400); } } reCheck();",400);
	}
	return dialogWin.win;
}

function funcExists(name) {
	var funcCheck = false;
	try { 
		funcCheck = (eval(name + " instanceof Function"));
	} catch(e){} 
	return funcCheck;
}

function confirmPopupAction() {
	for (var i in responseFunctions) {
		if (funcExists(responseFunctions[i])) {
			eval(responseFunctions[i]+'();');	
		}
	}
}

// The following functions will return window width, window height, horizontal scroll bar position and vertical scroll bar position.
// This should provide a browser-independent method of doing do.
// Source: http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
