//varaible used to defferentiate between en and es locale for dd/MMM/yyyy format
var local = "en";
var customCheckInFieldName = 'checkInDate';
var customCheckOutFieldName = 'checkOutDate';
/**
 * Populates the check in date.
 * @fulldate - the date.
 * @pattern - the date pattern.
 */
function populateCheckIn(fulldate, pattern, fieldName, dispName, hidName)
{
	document.getElementById(fieldName).value = fulldate;
	fieldAgreement(pattern, true, fieldName);
	calendarExit(dispName, hidName);
}

/**
 * Populates the check out date.
 * @fulldate - the date.
 * @pattern - the date pattern.
 */
function populateCheckOut(fulldate, pattern, fieldName, dispName, hidName)
{
	document.getElementById(fieldName).value = fulldate;
	fieldAgreement(pattern, false, fieldName);
	calendarExit(dispName, hidName);
}

/**
 * This method ensures the check in/out dates
 * and nights dropdown are all in agreement.
 *
 * @param pattern - the date format pattern.
 * @param isUpdateCheckInDate - a flag to determine
 * if the update check should be updated.
 */
function fieldAgreement(pattern, isUpdateCheckInDate) {
	var millisSecondsInOneHour = 1000 * 60 * 60;
	var millisSecondsInOneDay = millisSecondsInOneHour * 24;
	var datePattern = pattern.toLowerCase();
	var nightsValue = 1;
	var isUseNightsDropdown = false;
	if (document.getElementById('numberOfNight')!=null) {
		isUseNightsDropdown = true;
	}
	var date1 = new Date();
	var date2 = new Date();
	diff  = new Date();
	checkInValue = document.getElementById(customCheckInFieldName).value;
	checkOutValue = document.getElementById(customCheckOutFieldName).value;
		
	if (checkInValue == datePattern) { 
		checkInValue = ""; 
	}
	if (checkOutValue == datePattern) { 
		checkOutValue = ""; 
	}
	
	// set the nights field if both checkIn & checkOut dates have been selected	
	if (checkInValue != '' && checkOutValue != '') { 		
		checkInTempDate = createDate(checkInValue, datePattern);
		checkOutTempDate = createDate(checkOutValue, datePattern);
		if (checkInTempDate!=null && checkInTempDate!='-1' && checkOutTempDate!=null && checkOutTempDate!='-1') {
			date1.setTime(checkInTempDate.getTime());
			date2.setTime(checkOutTempDate.getTime());
			// check in date is less than the check out date
			if (date1.getTime() < date2.getTime()) {
				var one_day=1000*60*60*24;
				var difference_ms = Math.abs(date1.getTime() - date2.getTime());
				var numNights = Math.round(difference_ms/one_day)-1;
				if (isUseNightsDropdown) {
					document.getElementById('numberOfNight').selectedIndex = numNights;
				} 
			} 
			// check out date is less than or equal to the check in date - set the check
			// in date to 1 day ahead of the check in date.
			else if (date2.getTime() <= date1.getTime()) {
				var tempDate = null;
				if (isUpdateCheckInDate) {
					tempDate = createDate(checkInValue, datePattern);
				} else {
					tempDate = createDate(checkOutValue, datePattern);
				}
				if (tempDate!=null && tempDate!='-1') {					
					date1.setTime(tempDate.getTime());
					if (isUpdateCheckInDate) {
						diff.setTime(Math.floor(date1.getTime() + (millisSecondsInOneDay + (millisSecondsInOneHour * 2))));
					} else {
						var time = Math.floor(date1.getTime());
						var today = new Date();
						// do not roll back further than today
						if (date1.getTime()>today.getTime()) {
							time = Math.floor(date1.getTime() - millisSecondsInOneDay);
						}
						diff.setTime(time);
					}
					var yr = diff.getFullYear();
					var dt = diff.getDate();
					var mo = diff.getMonth() + 1;
					if (mo <= 9) { mo = '0' + mo; }
					if (dt <= 9) { dt = '0' + dt; }
					if (isUpdateCheckInDate) {
						setDate(dt, mo, yr, document.getElementById(customCheckOutFieldName), datePattern);
					} else {
						setDate(dt, mo, yr, document.getElementById(customCheckInFieldName), datePattern);
					}
					if (isUseNightsDropdown) {
						document.getElementById('numberOfNight').selectedIndex = 0;
					}
				} else {
					if (isUseNightsDropdown) {
						document.getElementById('numberOfNight').selectedIndex = -1;
					}
				}
			}
			else if (isUseNightsDropdown) {
				document.getElementById('numberOfNight').selectedIndex = -1;
			}
		}
		return false; 
	}
	// if only the checkIn date has been chosen, add the # of nights & populate the checkOut date
	else if (checkInValue != '' && checkOutValue == '') { 
	document.getElementById('numberOfNight').selectedIndex = 0;
	var checkInTempDate = createDate(checkInValue, datePattern);
	if (checkInTempDate!=null && checkInTempDate!='-1') {
		date1.setTime(checkInTempDate.getTime());
		diff.setTime(Math.floor(date1.getTime() + (millisSecondsInOneDay + (millisSecondsInOneHour * 2)) * nightsValue));
			var yr = diff.getFullYear();
			var dt = diff.getDate();
			var mo = diff.getMonth() + 1;
			if (mo <= 9) { mo = '0' + mo; }
			if (dt <= 9) { dt = '0' + dt; }
			setDate(dt, mo, yr, document.getElementById(customCheckOutFieldName), datePattern);
		}
	}
	// if only the checkOut date has been chosen, subtract the # of nights & populate the checkIn date
	else if (checkInValue == '' && checkOutValue != '') { 
	document.getElementById('numberOfNight').selectedIndex = 0;
	var checkOutTempDate = createDate(checkOutValue, datePattern);
	if (checkOutTempDate!=null && checkOutTempDate!='-1') {
		date2.setTime(checkOutTempDate.getTime());
		diff.setTime(Math.floor(date2.getTime() - millisSecondsInOneDay * nightsValue));
			var yr = diff.getFullYear();
			var dt = diff.getDate();
			var mo = diff.getMonth() + 1;
			if (mo <= 9) { mo = '0' + mo; }
			if (dt <= 9) { dt = '0' + dt; }
			setDate(dt, mo, yr, document.getElementById(customCheckInFieldName), datePattern);
		}
	}
}

/**
 * Updates the check out date by calculating
 * the number of nights.  Function is called 
 * when the nights dropdown is changed.
 */
function setCheckoutDateByNights(nights, pattern) {
	var datePattern = pattern.toLowerCase();
	var date1 = new Date();
	var date2 = new Date();
	diff  = new Date();
	var millisSecondsInOneHour = 1000 * 60 * 60;
	var millisSecondsInOneDay = millisSecondsInOneHour * 24;

	checkInValue = document.getElementById(customCheckInFieldName).value;
	checkOutValue = document.getElementById(customCheckOutFieldName).value;
	if (checkInValue == datePattern) { checkInValue = ""; }
	if (checkOutValue == datePattern) { checkOutValue = ""; }
	
	if (checkInValue != '') { 	
		date1temp = createDate(checkInValue, datePattern);
		date1.setTime(date1temp.getTime());
		nights = nights * (millisSecondsInOneDay) + (millisSecondsInOneHour);
		diff.setTime(Math.abs(date1.getTime() + nights ));
		var yr = diff.getFullYear();
		var dt = diff.getDate();
		var mo = diff.getMonth() + 1;
		if (mo <= 9) { mo = '0' + mo; }
		if (dt <= 9) { dt = '0' + dt; }
		setDate(dt, mo, yr, document.getElementById(customCheckOutFieldName), datePattern);
		return false; 
	} 
}

/**
 * Closes the calendar.
 */
function calendarExit(dispName, hidName) {
	if(dispName && hidName){
		document.getElementById(dispName).style.visibility = "hidden";
		document.getElementById(dispName).style.display = "none";
		document.getElementById(hidName).style.visibility = "hidden";
		document.getElementById(hidName).style.display = "none";
	}
	else {
		document.getElementById('checkOutCalendar').style.visibility = "hidden";
		document.getElementById('checkOutCalendar').style.display = "none";
		document.getElementById('checkInCalendar').style.visibility = "hidden";
		document.getElementById('checkInCalendar').style.display = "none";	
	}
}

/**
 * Opens the calendar.
 * @param theForm - the quick res form.
 * @param pattern - the date format pattern.
 * @param dateInputFieldName - the date input field that requires the calendar.
 * @param divLayerDisplayName - the div layer to display the calendar.
 * @param divLayerHideName - the div layer to hide.
 * @param jsMethodName - the javascript method to call when a date is clicked on the calendar.
 */
function openCalendar(uriPrefix, theForm, pattern, dateInputFieldName, divLayerDisplayName, divLayerHideName, jsMethodName)
{
	var dateInput = document.getElementById(dateInputFieldName);
	var datePattern = pattern.toLowerCase();
	var cDate = parseDate(dateInput.value, datePattern);
	var cMonth = parseMonth(dateInput.value, datePattern);
	var cYear = parseYear(dateInput.value, datePattern);
	document.getElementById(divLayerHideName).style.visibility = "hidden";
	document.getElementById(divLayerHideName).style.display = "none";
	document.getElementById(divLayerDisplayName).style.visibility = "visible";
	document.getElementById(divLayerDisplayName).style.display = "block";
	var url = uriPrefix + "/calendar?month=" + cMonth + "&year=" + cYear + "&date=" + cDate + "&jsMethodName="+jsMethodName+"&inputFieldName="+dateInputFieldName+"&displayName="+divLayerDisplayName+"&hideName="+divLayerHideName+"&openerForm=" + theForm;
	document.getElementById(divLayerDisplayName).innerHTML = "<iframe SRC=" + url + " WIDTH=\"273\" HEIGHT=\"149\" scrolling=\"no\" FRAMEBORDER=0>Your browser does not support the iframe tag.  Please consider upgrading your browser.</iframe>";
	return false;
}

/**
 * Parses and returns the month from the full date.
 * @param fullDate - the date to parse.
 * @param datePattern - the formatted pattern of the date.
 */
function parseMonth(fullDate, datePattern) {
	datePattern = datePattern.toLowerCase();
	if (!fullDate) fullDate = datePattern;
	var dateArray1 = fullDate.split("/");
	
	// mm/dd/yyyy
	var cMonth;
	if (datePattern == "mm/dd/yyyy") {
		cMonth = dateArray1[0];
	} 
	
	// dd/mm/yyyy
	if (datePattern == "dd/mm/yyyy") {
		cMonth = dateArray1[1];
	}
	
	// dd-mmm-yyyy
	if (datePattern == "dd-mmm-yyyy") {
		if (!fullDate) fullDate = datePattern;
		var dateArray = fullDate.split("-");

	        if (dateArray[1] == "Jan" || dateArray[1] == "ene") {
	            cMonth = '01';
	            if (dateArray[1] == "ene") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Feb" || dateArray[1] == "feb") {
	            cMonth = '02';
	            if (dateArray[1] == "feb") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Mar" || dateArray[1] == "mar") {
	            cMonth = '03';
	            if (dateArray[1] == "mar") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Apr" || dateArray[1] == "abr") {
	            cMonth = '04';
	            if (dateArray[1] == "abr") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "May" || dateArray[1] == "may") {
	            cMonth = '05';
	            if (dateArray[1] == "may") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Jun" || dateArray[1] == "jun") {
	            cMonth = '06';
	            if (dateArray[1] == "jun") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Jul" || dateArray[1] == "jul") {
	            cMonth = '07';
	            if (dateArray[1] == "jul") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Aug" || dateArray[1] == "ago") {
	            cMonth = '08';
	            if (dateArray[1] == "ago") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Sep" || dateArray[1] == "sep") {
	            cMonth = '09';
	            if (dateArray[1] == "sep") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Oct" || dateArray[1] == "oct") {
	            cMonth = '10';
	            if (dateArray[1] == "oct") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Nov" || dateArray[1] == "nov") {
	            cMonth = '11';
	            if (dateArray[1] == "nov") {
	                local = "es";
	            }
	        }
	        if (dateArray[1] == "Dec" || dateArray[1] == "dic") {
	            cMonth = '12';
	            if (dateArray[1] == "dic") {
	                local = "es";
	            }
	        }
	}
	
	// yyyy/mm/dd
	if (datePattern == "yyyy/mm/dd"){
		cMonth = dateArray1[1];
	}
	
	if(cMonth == null || cMonth == "mm" || cMonth == ""){
		cMonth = "-1";
	}
	else {
		cMonth = (cMonth - 1);
	}
	
	return cMonth;
}

/**
 * Parses and returns the year from the full date.
 * @param fullDate - the date to parse.
 * @param datePattern - the formatted pattern of the date.
 */
function parseYear(fullDate, datePattern) {
	datePattern = datePattern.toLowerCase();
	if (!fullDate) fullDate = datePattern;
	var dateArray = fullDate.split("/");
	// mm/dd/yyyy
	var cYear;
	if (datePattern == "mm/dd/yyyy") {
		cYear = dateArray[2];
	} 
	// dd-mm-yyyy
    else if (datePattern == "dd-mmm-yyyy") {
		if (!fullDate) fullDate = datePattern;
    	var dateArray1 = fullDate.split("-");
        cYear = dateArray1[2];
    }
	// dd/mm/yyyy
	else if (datePattern == "dd/mm/yyyy") {
		cYear = dateArray[2];
	}
	// yyyy/mm/dd
	else {
		cYear = dateArray[0];
	}
	if(cYear == null || cYear == "yyyy" || cYear == ""){
	    cYear = "-1";
	}
	return cYear;
}

/**
 * Parses and returns the day from the full date.
 * @param fullDate - the date to parse.
 * @param datePattern - the formatted pattern of the date.
 */
function parseDate(fullDate, datePattern) {
	datePattern = datePattern.toLowerCase();
	if (!fullDate) fullDate = datePattern;
	var dateArray = fullDate.split("/");
	var cDate;
	
	// mm/dd/yyyy
	if (datePattern == "mm/dd/yyyy") {
		cDate = dateArray[1];
	} 
	
	// dd-mm-yyyy
	else if (datePattern == "dd-mmm-yyyy") {
		if (!fullDate) fullDate = datePattern;
    		var dateArray1 = fullDate.split("-");
        	cDate = dateArray1[0];
        }
	
	// dd/mm/yyyy
	else if (datePattern == "dd/mm/yyyy") {
		cDate = dateArray[0];
	}
	
	// yyyy/mm/dd
	else {
		cDate = dateArray[2];
	}
	
	if(cDate == null || cDate == "dd" || cDate == ""){
	    cDate = "-1";
	}
	
	return cDate;
}

/**
 * Sets the date in the specified text field.
 * @param day - the date.
 * @param month - the month. 
 * @param year - the year.
 * @param textFieldToUpdate - the text field to update.
 * @param datePattern - the date pattern.
 */
function setDate(day, month, year, textFieldToUpdate, datePattern) {
	// mm/dd/yyyy
	if (datePattern == "mm/dd/yyyy") {
		textFieldToUpdate.value = (month + "/" + day + "/" + year);
	} 
	// dd/mm/yyyy
	else if (datePattern == "dd/mm/yyyy") {
		textFieldToUpdate.value = (day + "/" + month + "/" + year);
	}
	// dd-mmm-yyyy
	else if (datePattern == "dd-mmm-yyyy") {
	        var cMonth;
	        if (month == "01") {
	            if (local == "en") {
	                cMonth = "Jan";
	            }
	            else {
	                cMonth = "ene";
	            }
	        }
	        if (month == "02") {
	            if (local == "en") {
	                cMonth = "Feb";
	            }
	            else {
	                cMonth = "feb";
	            }
	        }
	        if (month == "03") {
	            if (local == "en") {
	                cMonth = "Mar";
	            }
	            else {
	                cMonth = "mar";
	            }
	        }
	        if (month == "04") {
	            if (local == "en") {
	                cMonth = "Apr";
	            }
	            else {
	                cMonth = "abr";
	            }
	        }
	        if (month == "05") {
	            if (local == "en") {
	                cMonth = "May";
	            }
	            else {
	                cMonth = "may";
	            }
	        }
	        if (month == "06") {
	            if (local == "en") {
	                cMonth = "Jun";
	            }
	            else {
	                cMonth = "jun";
	            }
	        }
	        if (month == "07") {
	            if (local == "en") {
	                cMonth = "Jul";
	            }
	            else {
	                cMonth = "jul";
	            }
	        }
	        if (month == "08") {
	            if (local == "en") {
	                cMonth = "Aug";
	            }
	            else {
	                cMonth = "ago";
	            }
	        }
	        if (month == "09") {
	            if (local == "en") {
	                cMonth = "Sep";
	            }
	            else {
	                cMonth = "sep";
	            }
	        }
	        if (month == "10") {
	            if (local == "en") {
	                cMonth = "Oct";
	            }
	            else {
	                cMonth = "oct";
	            }
	        }
	        if (month == "11") {
	            if (local == "en") {
	                cMonth = "Nov";
	            }
	            else {
	                cMonth = "nov";
	            }
	        }
	        if (month == "12") {
	            if (local == "en") {
	                cMonth = "Dec";
	            }
	            else {
	                cMonth = "dic";
	            }
	        }
	        
	        textFieldToUpdate.value = (day + "-" + cMonth + "-" + year);
        }
        
        // yyyy/mm/dd
        else {
    		textFieldToUpdate.value = (year + "/" + month + "/" + day);
    	}
}

/**
 * Creates and returns a date after parsing the 
 * specified value.  If the date can not be parsed, 
 * then -1 is returned.
 * @param dateValueToParse - the date to parse.
 * @param pattern - the date pattern.
 */
function createDate(dateValueToParse, pattern) {
	if (dateValueToParse != '') {
		var day = parseDate(dateValueToParse, pattern);
		var month = parseMonth(dateValueToParse, pattern);
		var year = parseYear(dateValueToParse, pattern);
		if (day!= "-1" && month!= "-1" && year!= "-1") {					
			var tempDate = new Date(year, month, day);
			return tempDate;
		}
	}
	return "-1";
}

/*
 Reads keypress value for assigned fields.
 Used here to listen for TAB keypress for customCheckOutFieldName field element
*/
function checkForTab(e){
	e = (e) ? e : (window.event) ? event : null;	
	if (e){
		var charCode = (e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : ((e.which) ? e.which : 0));
	}
	if(charCode == 9){
		fieldAgreement('MM/dd/yyyy');
		calendarExit();
	}
}
