// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=0;
var maxYear=2500;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}
	var daysInMonth = DaysArray(12);

function datePiecesArray(dtStr)
{
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	if (pos1==-1 || pos2==-1){
		return null
	}

   	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return null
	}

   	var pieces = new Array(3);
   	pieces[0]=dtStr.substring(0,pos1)
	pieces[1]=dtStr.substring(pos1+1,pos2)
	pieces[2]=dtStr.substring(pos2+1)
	
	return pieces;
}

function isDate(dtStr){
   	var datePieces = datePiecesArray(dtStr)

	if (datePieces == null)
	{
		var badDate = "Please enter a valid date of the form: " + ((dtCh == '-') ? "yyyy-mm-dd" : "mm/dd/yyyy");
		alert(badDate);
		return false
	}

	var strYear = datePieces[ (dtCh == '-') ? 0 : 2 ]
	var strMonth= datePieces[ (dtCh == '-') ? 1 : 0 ]
	var strDay  = datePieces[ (dtCh == '-') ? 2 : 1 ]

	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
 
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)

	if (strMonth.length<1 || month<1 || month>12){
		alert(month + "is not a valid month.")
		return false
	}

	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert(month + dtCh + day + " is not a valid day.")
		return false
	}
//	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
//		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
	if (year<minYear || year>maxYear){
		alert("Please enter a valid year between "+minYear+" and "+maxYear)
		return false
	}

	return true
}

CRS_Utils.prototype.checkDateFormat = function(elem)
{
    if (elem.value.length > 0)
    {
    	if (isDate(elem.value))
        {
        	if (this.onDateChanged != null)
        	{
        		this.onDateChanged(elem);
        	}
    	}
    	else
    	{
    		elem.focus();
    	}
    }
    else if (this.onDateChanged != null)
    {
    	this.onDateChanged(elem);
    }
}
 
 function refreshTimeField(timeField,hourDropDown,minuteDropDown)
 {
 	timeField.value = hourDropDown.options[hourDropDown.selectedIndex].value + ":" +
 		"22" ; 
		// minuteDropDown.options[minuteDropDown.selectedIndex].value;
 }
 
 function focusElement(elementId)
 {
 	var element = crs.getRequiredElement(elementId);
 	
 	element.focus();
 	element.select();
 }
 
 function isValidPhone(phoneField, isInternational)
 {
 	var isValid = false;
 	var phoneNumber = phoneField.value;
 	
 	try
 	{
		if (phoneNumber.length != 14)
		{
			throw new Error("(XXX) XXX-XXXX");
		}
		
		isValid = true;
 	}
 	catch (e)
 	{
			alert("Please enter a valid phone number. [" + e.message + "]");
			setTimeout("focusElement('" + phoneField.id + "')",0);
 	}
 	
 	return isValid;
 }

function validateDateRange(startDateField, endDateField, maxDays, allowOpenEnd)
{
	if (allowOpenEnd == null) allowOpenEnd = false; // caller must request explicitly
	
	var error = new Error("");
	error.problemField = endDateField; // default to this
	
	try
	{
		if (startDateField.value.length == 0)
		{
	    	error.message = "From Date missing";
			error.problemField = startDateField;
	    	throw error;
		}

		var haveEndDate = (endDateField.value.length != 0);
		
		if (!haveEndDate && !allowOpenEnd)
		{
	    	error.message = "To Date missing";
	    	throw error;
		}
		
		var startDate = new Date(startDateField.value);
	
	    var year = startDate.getYear();
	
	    if (year < 100) {
	        startDate.setFullYear(2000 + year);
	    	startDateField.value = (1 + startDate.getMonth()) + "/" + startDate.getDate() + "/" + startDate.getFullYear();
	    }
	
		if (haveEndDate)
		{
			var endDate = new Date(endDateField.value);
		    year = endDate.getYear();
		
		    if (year < 100) {
		        endDate.setFullYear(2000 + year);
		    	endDateField.value = (1 + endDate.getMonth()) + "/" + endDate.getDate() + "/" + endDate.getFullYear();
		    }
		}
		
	    var today = new Date();
	
	    today.setHours(0);
	    today.setMinutes(0);
	    today.setSeconds(0);
	    today.setMilliseconds(0);
	    
	    if (startDate < today)
	    {
	    	error.message = "From Date should be equal or after today's date";
			error.problemField = startDateField;
	    	throw error;
	    }
	    
	    if (haveEndDate)
	    {
		    if (endDate < today)
		    {
		    	error.message = "To Date should be equal or after today's date";
		    	throw error;
		    }
		    
		    if (endDate < startDate)
		    {
		    	error.message = "To Date should be equal or after From Date";
		    	throw error;
		    }
		    
		    var maxDate = today;
		
		//  maxDate.setDate(today.getDate() + maxDays);
			addDays(maxDays,maxDate); // workaround Safari bug
			
		  	if (endDate > maxDate)
		  	{
		    	error.message = "To Date should not be more than " + maxDays + " days from today";
		    	throw error;
		    }
	    }
    }
    catch (e)
    {
    	e.message = "Invalid Date Range: " + e.message;
    	throw e;
    }
}

// Use this function to add/subtract days to a Date, instead of straight setDate calls,
// whenever the number of days may be outside the range of -128 to +127.
// In Safari, there's a bug where the parameter for Date.setDate() is converted to a 
// signed byte integer. This means that it can only be called with numbers from -128 to 127;
// all other values "roll over" into that range.
// (courtesy of: http://brianary.blogspot.com/2006/03/safari-date-bug.html
function addDays(d,D)
{
  var x= new Date(2000,1,1), y= new Date(2000,1,1); 
  if(x.setDate(128) > y.valueOf())
  { D.setDate(D.getDate()+d); return D; }
  // Safari setDate(uint8) workaround
  if(d < 0)
    for(var i= -97; d < i; d-= i) 
      D.setDate(D.getDate()+i);
  else
    for(var i= 96; d > i; d-= i) 
      D.setDate(D.getDate()+i);
  D.setDate(D.getDate()+d);
  return D;
}

function stayDateValidation(checkinDateField, checkoutDateField, maxStayDays, systemTimeZoneOffset)
{
	checkinDateValue = crs.getRequiredElement(checkinDateField).value;
	checkoutDateValue = crs.getRequiredElement(checkoutDateField).value;

	checkinDate = new Date(checkinDateValue);
	checkoutDate = new Date(checkoutDateValue);

	//Calculate difference between the two dates, and convert to days.
	var totalStayDays = Math.ceil((checkoutDate.getTime() - checkinDate.getTime())/(1000*60*60*24)); 

    systemDate = new Date();
    systemDate.setDate(systemDate.getDate() - 1); 
    utcTimeInMillis = systemDate.getTime() + (systemDate.getTimezoneOffset() * 60000);
    systemDate = new Date(utcTimeInMillis + (systemTimeZoneOffset*3600000));
   
	if(checkinDate < systemDate)
	{
		alert("Reservations cannot be made prior to today's date.  Please check your dates and try again.");
		return false;
	}
	if(checkoutDate <= checkinDate)
	{
		alert("Departure date must be after the arrival date.");
		return false;
	}
	if((maxStayDays > 0) && (totalStayDays > maxStayDays))
	{
		alert("The Departure Date of your stay must be within " + maxStayDays + " days of your Arrival Date.");
		return false;
	}
	
	return true;
}
