//------------------------------------------------------
          // U T I L I T Y    F U N C T I O N S
//-------------------------------------------------------

var arrayIndex;

// strip leading zero, if any.
function stripZero(s)
{
	if(s.charAt(0) == '0'){
		s = s.substr(1,s.length);
	}
	return s;
}
//-----------------------------------------------
// padd a zero if string is one char
function paddZero(s)
{
	if(s >= 0 && s <= 9){
	  s = '0' + s;
	}
	return s;
}
//------------------------------------------------------
// function to assign action and submit form
function assignActionSubmit(f,action)
{
	f.action = action;
	f.submit();
}
//------------------------------------------------------
// function set errorArray
function setErrCode(code)
{
	errorArray[errorArray.length] = code;
}
//------------------------------------------------------
// function set resetArray
function resetErr()
{
   errorArray = new Array();
}
// diff in days between two dates
function getDiffDays(indate,outdate)
{
	if(indate == null || outdate == null)
		return '';
	
	var diff = '';
	// this will give us a float i.e something like 7.9583333.. for 8 days
	var df =  ( outdate.getTime()-indate.getTime() ) / (1000 * 60 * 60 * 24);
	
	// convert to a whole number
	df = Math.round(df);
	
	// convert to string
	diff = df.toString(10);
	
	return diff;
}

//---------------------------------------------------------
function isIn(elt, list, cityFlag){
	var tempArray;
	if(elt == null || list == null)
		return false;
		
	if (cityFlag){
		for(var i=0; i < list.length; i++){
			tempArray = list[i].split(":")
			if( tempArray[0] == elt ){
				arrayIndex = i;
				return true;
			}
		}
	} else {
		for(var i=0; i < list.length; i++)
			if( list[i] == elt ){return true;}
	}
	return false;
}
//------------------------------------
// end methods for changing state/country

function collectList(f,elemName,sourceName)
{
	var checkList = '';
	var tempSource = eval('f.' + elemName);
	var tempElem = sourceName;
	tempElem = eval('f.' + tempElem);
	for (var i=0;i<tempSource.length;i++) {
		if (eval(tempSource[i]).checked == true){
			if (checkList == '') {
				checkList = eval(tempSource[i]).value;
			} else {
				checkList = checkList + ',' + eval(tempSource[i]).value;
			}
		}
	}
	tempElem.value = checkList;
	checkList = '';
}

function correctDate(incFormat) //incorrect format expected: yyyy-mm-dd
{
	if (incFormat != ''){
		var tempArray = incFormat.split("-");
		
		var tempYear = tempArray[0];
		var tempMonth = tempArray[1];
		var tempDay = tempArray[2];
		
		var corFormat = tempMonth + "/" + tempDay + "/" + tempYear;	
		return corFormat;
	} else {
		return false;
	}
}

//-------------------------------------------------
// Removes all characters which appear in string bag from string s.
function stripCharsInBag (s, bag)
{   
	var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

//-------------------------------------------------
// Boolean value to determine if a String has any integers in it.
function isInteger(s)
{
	var re = /^\d+$/
	return (s.search(re) == -1) ? false : true ;
}
//-------------------------------------------------
// Begin onKeyDown capture
if (document.layers)
	document.captureEvents(Event.KEYDOWN);

document.onkeydown = function (evt) {
	var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
	if (keyCode == 13) {
		return false;
	} else {
		return true;
	}
}
//-------------------------------------------------
// Write to a Div layer
function writetoDiv(containerName,elemLoc,msg,pageType)
{
//alert(elemLoc);
	if (document.layers) {
		elemLoc = containerName.document[elemLoc];
		elemLoc.document.open();
		elemLoc.document.write("<br>"+msg);
		elemLoc.document.close();
	} else {
		if(msg == null){
			document.getElementById(elemLoc).style.display = 'none';
		} else {
			document.getElementById(elemLoc).innerHTML = msg;
			document.getElementById(elemLoc).style.display = 'block';
		}
	}
}
//-------------------------------------------------
// TabSwitching functions
function tabSwitch(newSection,pageType) {
	if (pageType == '' || pageType == null){
		hideSection(activeSection);
		showSection(newSection);
		activeSection = newSection;
	}
}

function hideSection (sectionName) {
	var tempSection = getSectionRef(sectionName);
	hideDiv(tempSection.elemName);
}

function showSection (sectionName) {
	var tempSection = getSectionRef(sectionName);
	showDiv(tempSection.elemName);
}

function hideDiv (divRef) {
	var tempDiv = document.getElementById(divRef);
	tempDiv.style.visibility = "hidden";
}
function showDiv (divRef) {
	var tempDiv = document.getElementById(divRef);
	tempDiv.style.visibility = "visible";
}
//-------------------------------------------------

//-------------------------------------------------
// Determine if there are any errors.
function checkForErrors(f1,action,pageType,f2)
{
	if (errorArray.length > 0){
		for (i=0; i < errorArray.length; i++){
			showErrArray = showErrArray + errorArray[i] + ", ";
		}
		//alert(showErrArray);
		resetPage(pageType);
		evalErrors(errorArray,f1,pageType);
		
		resetErr();
		showErrArray = '';
	} else {
		// begin alert form elements before submitting
			if (f2){var formElements = f2.elements;}
			else if (f1){var formElements = f1.elements;}
			else{var formElements = f.elements;}
			
			var str = "";
	
			for (i=0; i<formElements.length; i++) {
				var name  = formElements[i].name;
				var value = formElements[i].value;
				var type  = formElements[i].type;
				str += type + " " + name + " = " + value + "\n";
			}
			//alert(str);
		// end alert form elements before submitting

		if (f2){
			f2.action = action;
			f2.submit();
		} else {
			f1.action = action;
			f1.submit();
		}
	}
}
//-------------------------------------------------

//-------------------------------------------------
// Clear whatever field you pass in 
function clearField(fieldName, valueToCheck)
{
	if (eval(fieldName).value == valueToCheck){
		eval(fieldName).value = '';
	};
};
//-------------------------------------------------

//-------------------------------------------------
// Add data to field with whatever is passed in
function addToField(fieldName, valueToAdd)
{
	if (eval(fieldName).value == ''){
		eval(fieldName).value = valueToAdd;
	};
};
//-------------------------------------------------

//-------------------------------------------------
// Hide/Show Div
function hideShowDiv(elemLoc, displayType)
{
//alert("elemLoc: " + elemLoc + " -- " + document.getElementById(elemLoc).style.display);
	if(displayType == 'hide'){
		document.getElementById(elemLoc).style.display = 'none';
	} else {
		document.getElementById(elemLoc).style.display = 'block';
	}
}
//-------------------------------------------------

//-------------------------------------------------
// Takes a checkbox.checked boolean and applies it to a hidden form element
function readyCheckBox(checkbox, hiddenElem){
	if (checkbox.checked == true){
		hiddenElem.value = "1";
	} else {
		hiddenElem.value = "0";
	}
}
//-------------------------------------------------

//-------------------------------------------------
// Takes (n) number of checkboxes with the same name, 
// creates a comma separated string and sets it to the value of a hidden element
function commaStringFromCheckBox(f, elemSrc, elemDest) {
	var varElemSrc = eval('f.' + elemSrc);
	var varElemDest = eval('f.' + elemDest);
	var checkList = '';
	
	for (var i=0;i<varElemSrc.length;i++) {
		if (varElemSrc[i].checked == true){
			if (checkList == "") {
				checkList = varElemSrc[i].value;
			} else {
				checkList = checkList + "," + varElemSrc[i].value;
			}
		}
	}
	
	varElemDest.value = checkList;
	checkList = '';
}
//-------------------------------------------------

//-------------------------------------------------
// Takes in a radio button array and returns which value is selected
function getRadioValue(radioObj) {
	var value = null;
	for(var i=0; i<radioObj.length; i++) {
		if(radioObj[i].checked) {
			value = radioObj[i].value;
			break;
		}
	}
	return value;
}
//-------------------------------------------------

//-------------------------------------------------
// utility function to validate dates
function validDate(field) {
	this.field = field;
	_s  = field.value;
	_d = getDateFromField(field, dateFormatString);
	this.valid = true;
	if ( isNaN(_d.getDate() ) ) {  // Basically, this allows the functions to gracefully return to the format string instead of putting a date in the field.
			this.valid = false;
	}
	
	/*  This is the old way of dealing with odd strings in the date field. The new way is done in the getDateFromField function.
	_d = new Date()
	_d.setTime(Date.parse(_s))
	alert(_d);
	this.valid = true;
	if ( isNaN(_d.getDate()) ) {
		var year = new Date().getYear() + "";
		_d.setTime(Date.parse(  _s + "/200" + year.charAt(year.length-1))); 
		if ( isNaN(_d.getDate() ) ) {
			this.valid = false;
		} else {
			var nowDelta = _d.getTime() - new Date().getTime();
			if (nowDelta < (-1 * (1000*60*60*24*5) )) { 
				_d.setYear(_d.getYear() + 1);
			} 
		}
	}
	*/
	
	this.d = _d;
	this.setD = function(_d) {this.d = _d}
	this.setNonD = function(_s) {this.s = _s}
	this.getM = function() {
		var month = this.d.getMonth();
		return month;
	}
	this.getD = function() {
		var day = this.d.getDay();
		return day;
	}
	this.getY = function() {
		var y = (this.d.getYear() + 10000) % 100;
		y += (y < 38) ? 2000 : 1900; 
		return y
	}
	this.setField = function() {
		writeDateToField(this.field, this.d, dateFormatString);
	}
	this.setAltField = function() {
		s = this.getY() +"-"+ lZero(this.d.getMonth() + 1 ) + "-" + lZero(this.d.getDate());
		field.value = s
		return s;
	}
	this.nextDay = function() {
		return this.d.setDate(this.d.getDate()+1);
	}
	this.diffDate = function(dd) {
		return (makeDate(this.d).getTime() - makeDate(dd).getTime()) / (1000*60*60*24);
	}
	function makeDate(md) {
		return new Date(md.getMonth() + 1 + "/" + md.getDate() + "/" + md.getYear()); 
	}

	function lZero(nr) {if (nr < 10) nr = "0" + nr;return nr;}
	return this;
}
//--------------------------------------------------------

//--------------------------------------------------------
// calculate the lengthOfStay
function getLengthOfStay(checkin,checkout){
var checkinDate = getDateFromField(checkin, dateFormatString);
var checkoutDate = getDateFromField(checkout, dateFormatString);
	if (!(isNaN(checkinDate)) && !(isNaN(checkoutDate))){
		if(f.lengthOfStay != null) {
			var diff = getDiffDays(checkinDate,checkoutDate);
			if(diff > 30 || diff < 0)
			diff = 0;
			
			f.lengthOfStay.value = diff;
		}
	}
}
//--------------------------------------------------------

//--------------------------------------------------------
// reset a form
function okReset(f) {
	var formElements = f.elements;
	var str = "";
	var name, type, value

	for (i=0; i<formElements.length; i++) {
		name  = formElements[i].name;
		type = formElements[i].type;
		value = formElements[i].value;
		
		if (type == 'text'){
			if (name == 'ciDate'){formElements[i].value = dateFormatString;}
			else if (name == 'coDate'){formElements[i].value = dateFormatString;}
			else {formElements[i].value = '';}
		}		
		if (type == 'checkbox'){formElements[i].checked = false;}
		if (type == 'select-one'){formElements[i][formElements[i].selectedIndex].selected = 0;}
	}
}
//--------------------------------------------------------

//--------------------------------------------------------
//check all brands off if the all brand check box is checked
//--------------------------------------------------------
function checkAllIn(theForm) {
    for (i=1,n=theForm.elements.length;i<n;i++)
        if ((theForm.elements[i].name.indexOf('brandchk') !=-1)&&(theForm.elements[i].name!='brandchk0'))
            theForm.elements[i].checked = false;
}

//--------------------------------------------------------
//check allbrands field off if one of the brand is checked
//--------------------------------------------------------
function checkAllOut(theForm) {
    theForm.brandchk0.checked = false;
}
//--------------------------------------------------------
//Wrtie the brand info into the hidden field brandFilter
//--------------------------------------------------------

function brandFilter(theForm) {
	if (theForm.brandchk0.checked == false) {
	text ="";
    for (i=1,n=theForm.elements.length;i<n;i++)
        if (theForm.elements[i].name.indexOf('brandchk') !=-1){
			if(theForm.elements[i].checked==true)
			if (text == ""){
			text = theForm.elements[i].value;
			}else{
			text = text + "," +theForm.elements[i].value;
			}    	
		}
		theForm.brandFilter.value = text;
	}else{
	theForm.brandFilter.value = theForm.brandchk0.value;
	}
}
//--------------------------------------------------------



//--------------------------------------------------------
//Get the Date from a form field - Based on Internationalization Variables
//--------------------------------------------------------
function getDateFromField(formField, dateFormat) {
	// formField is a reference to a text field
	// dateFormat is a string describing the local date format
	//	Current options for dateFormat:
	//		mm/dd/yyyy - English
	//		dd/mm/yyyy - Non-English, Non-Japanese
	//		yyyy/mm/dd - Japanese
	
	var date = new Date(); // Default the date to today ready to be overwritten.
	var currDate = new Date(); // Today's date and time for comparison's sake.

	dateFormat = dateFormat.toLowerCase();
	var fieldString;
	if (typeof formField == "object") { fieldString= formField.value; } // Get the current value of the field
		else { fieldString = formField; } // We were passed a direct value
	if (fieldString.search("/") > 0) { // check if we have / to delimit
		var dateValues = fieldString.split("/");
	} else if (fieldString.search("-") > 0) { // They used - instead of /
		var dateValues = fieldString.split("-");
	} else if (fieldString != "") {  // Assume there are no delimiters, assume one number
		var dateValues = new Array(fieldString);
	} else if (fieldString == "") {  // If there's not data there, assume it was deleted, and throw back a validDate object compatible invalid date.
		date.setTime(Date.parse(dateFormatString));
		return date;
	}

	if (fieldString.toLowerCase() == dateFormatString) { 
		date.setTime(Date.parse(fieldString));
		return date;
	}
	
	var year;
	var month;
	var day;
	
	switch(dateFormat) {
		case 'mm/dd/yyyy':
			if (dateValues[0]) month = dateValues[0];
			if (dateValues[1]) day = dateValues[1];
			if (dateValues[2]) year = dateValues[2];
			break;
		case 'dd/mm/yyyy':
			if (dateValues[0]) day = dateValues[0];
			if (dateValues[1]) month = dateValues[1];
			if (dateValues[2]) year = dateValues[2];
			break;
		case 'yyyy/mm/dd':
			if (dateValues[0]) year = dateValues[0];
			if (dateValues[1]) month = dateValues[1];
			if (dateValues[2]) day = dateValues[2];
			break;
		case 'yyyy/dd/mm':
			if (dateValues[0]) year = dateValues[0];
			if (dateValues[1]) day = dateValues[1];
			if (dateValues[2]) month = dateValues[2];
			break;
		default:  // Default to mm/dd/yyyy
			if (dateValues[0]) month = dateValues[0];
			if (dateValues[1]) day = dateValues[1];
			if (dateValues[2]) year = dateValues[2];
			break;
	}
			
	if (year) { 
		if (year.length == 2) { year = "20" + year; } // Try to make the year 4 digits
		if (year.length == 4) { // If it's not 4 digits, just fall back to using the current year
			date.setFullYear(year);
		}
	}
	date.setDate(1);
	if (month) date.setMonth(month - 1); // setMonth uses a zero-based number
	if (day) date.setDate(day);
	if (date.getTime() < currDate.getTime()) date.setYear(currDate.getFullYear() + 1); // For dates in the past, set to next year.
	writeDateToField(formField, date, dateFormat);
	return date;
}

//--------------------------------------------------------
//Write the date to a form field - Based on Internationalization Variables
//--------------------------------------------------------

function writeDateToField(formField, date, dateFormat) {

	if ( isNaN(date.getDate() ) ) {
		formField.value = dateString;
		return;
	}
	
	dateFormat = dateFormat.toLowerCase();
	var month = date.getMonth() + 1;
	month = paddZero(month);
	var day = date.getDate();
	day = paddZero(day);
	var year = date.getFullYear();
	var dateString;
	var sep = "/";
	switch(dateFormat) {
		case 'mm/dd/yyyy':
			dateString = month + sep + day + sep + year;
			break;
		case 'dd/mm/yyyy':
			dateString = day + sep + month + sep + year;
			break;
		case 'yyyy/mm/dd':
			dateString = year + sep + month + sep + day;
			break;
		case 'yyyy/dd/mm':
			dateString = year + sep + day + sep + month;
			break;
		default:  // Default to mm/dd/yyyy
			dateString = month + sep + day + sep + year;
			break;
	}
	
	formField.value = dateString;
}

// Safely adds to the document's onLoad event.
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}