function checkdates(checkin, checkout){
    
    if(checkin == 'check-in' && checkout == 'check-out'){
        return true;
    }
    else if (checkin == 'check-in' && checkout != 'check-out'){
        alert("Please select check-in date.");
        return false;
    }
    else if (checkin != 'check-in' && checkout == 'check-out'){
        alert("Please select check-out date.");
        return false;
    }
    else{
        if (Date.parse(checkin) >= Date.parse(checkout)) {
            alert("Checkin Date must be before Checkout Date");
            return false;
        }
        var toDay = new Date();
        var month = toDay.getMonth() + 1;
        var day = toDay.getDate();
        var year = toDay.getFullYear();
        var toDay = month + "/" + day + "/" + year;
        if ((Date.parse(checkin) < Date.parse(toDay)) || (Date.parse(checkout) < Date.parse(toDay))){
            alert("Checkin or Checkout date is in the past.  Please choose another date.");
            return false;
        }
    }
    
    return true;
} 

function inputTipper(id, input_empty){
    var input = $(id);
    if(!input[0]) return;
    if(typeof(input_empty)!='string') input_empty = '';
    input.val(input_empty).addClass('inputTipper');
    if (input_empty == 'check-in' || input_empty == 'check-out'){
    input[0].defaulttext = input_empty;
    }
    else input.removeClass('inputTipper');
        
    input.change(function(){
        if(input.val() !== input_empty)input.removeClass('inputTipper');
        });
    input.keyup( function(e){
        if(input.val().length > 0)input.removeClass('inputTipper');
        else input.addClass('inputTipper');
        });
    input.focus(function(e){
        if(input.val() === input_empty){
            if (input_empty == 'check-in' || input_empty == 'check-out'){
            input.val("").removeClass('inputTipper');
            }
            else input.val(input_empty).removeClass('inputTipper');
        }
        });
        input.blur( function(e){
            if(input.val() === "")input.val(input_empty).addClass('inputTipper');
            else if(input.val() === input_empty)input.addClass('inputTipper');
            });
    
    }

jQuery.fn.hasValue = function(){
    if(!this.length) return false;
    if(this[0].defaulttext && ($(this[0]).val()==this[0].defaulttext)) return false;    
    return (jQuery.trim($(this[0]).val())!=='');
    }

// --- datepicker --- //



var curDateField;
var callocked = false;

function onDatePicker(){
    curDateField.datepicker('option', 'minDate', new Date());
    if(curDateField && curDateField[0].checkin){ // this is checkout input      
        var inval = curDateField[0].checkin.val(); 
        if(inval!==curDateField[0].checkin[0].defaultvalue){
            var date = curDateField[0].checkin.datepicker('getDate');
            if (date != null){
                date.setDate(date.getDate() + 1);               
                curDateField.datepicker('option', 'minDate', date);
            }           
        } else {
            var date = new Date();
            date.setDate(date.getDate() + 1);
            curDateField.datepicker('option', 'minDate', date);
        }
        
    } 
}

function handleDateClick(callFormSubmit, isUpdateCookie, isClearDates) {
	
   inputTipper(curDateField, curDateField.val());
    
    var chkIn = (curDateField[0].checkin ? curDateField[0].checkin : curDateField);
    var chkOut = (curDateField[0].checkout ? curDateField[0].checkout : curDateField);
    
    if (isUpdateCookie && chkIn.val() != 'check-in'){
    	$.cookie("filterCheckin", chkIn.val(), { expires: 0,path:'/' }); 
    }
    
    if(curDateField[0].checkout) { // this is checkin select
        var checkInDate = chkIn.datepicker('getDate');
        var checkOutDate = new Date(Date.parse(chkOut.val()));
        if (checkInDate && checkOutDate && (checkInDate >= checkOutDate)){
        	// add day using milliseconds instead of getDate()+1; it adds only day not month & year
            checkOutDate.setTime(checkInDate.getTime() + 86400000);
            chkOut.datepicker('setDate',checkOutDate);                      
        }
    }
        
    if (isUpdateCookie && chkOut.val() != 'check-out'){
    	 $.cookie("filterCheckout", chkOut.val(), { expires: 0,path:'/' });
    }
    
    if(callFormSubmit && (isClearDates  || (chkIn.val() && chkOut.val() && chkIn.val() != 'check-in' && chkOut.val() != 'check-out'))) {
    	if(typeof(sendXHR) != "undefined") sendXHR();
    }
    return false;
}

function setSendOmnitureDate(){
	if($.cookie("filterCheckin") != checkincookie || $.cookie("filterCheckout") != checkoutcookie){
		  $.cookie("dateUpdated", "Yes", { expires: 0,path:'/' });
	 }
	
}

function attachDatepickerFooterEvent() {
    if(callocked) return;
    callocked = true;
    $('#ui-datepicker-footer a').click(function(){
    	
    	var ci = $.cookie("filterCheckin"), co = $.cookie("filterCheckout");
    	var custOptns = curDateField[0].customOptions;
    	
	    $.cookie("filterCheckin", "", { path: '/' });
	    $.cookie("filterCheckout", "", { path: '/' });    	
        curDateField.datepicker('option', 'minDate', '');
                
        if(curDateField[0].checkin) dateFields(curDateField[0].checkin, curDateField, custOptns);
        if(curDateField[0].checkout)    dateFields(curDateField, curDateField[0].checkout, custOptns);
        
        // This call should be after above datefields call as datefield function is setting value from cookie
        // And cases where isUpdateCookie is false, we are again setting values in cookies.
        if(!custOptns.isUpdateCookie) {
	        $.cookie("filterCheckin", ci, { path: '/' });
	        $.cookie("filterCheckout", co, { path: '/' });
    	}
        
        handleDateClick(custOptns.callFormSubmit, custOptns.isUpdateCookie, true);
        return false;
        });
    callocked = false;
    updateCalendar();
}
function updateCalendar(){ 
    var Cal = $('#ui-datepicker-div');
    var mos = {January: 1, February: 2, March: 3, April: 4, May: 5, June: 6, July: 7, August: 8, September: 9, October: 10, November: 11, December: 12};
    var month = mos[$('.ui-datepicker-month').html()];
    var year = parseInt($('.ui-datepicker-year').html());
    var tds = Cal.find('td').removeClass('ui-datepicker-pastdate');
    if(!month)return; // error
    var curdate = new Date();
    var curyear = curdate.getYear();
    if(!$.browser.msie) curyear += 1900;
    var curmonth = curdate.getMonth() + 1;
    if((year>curyear) || (year==curyear) && (month>curmonth))return; // future month
    else if((year<curyear) || (year==curyear) && (month<curmonth))tds.addClass('ui-datepicker-pastdate');// past month
    else{// current month
        for(var i=0; i<tds.length; i++){
            var obj = $(tds[i]);
            if(obj.hasClass('ui-datepicker-today')) break;
            else obj.addClass('ui-datepicker-pastdate');
            }
        }
    
    // link alerts
    $('#ui-datepicker-div .ui-datepicker-pastdate a').click(function(){
        alert('This date is in the past.  Please choose another date.');
        return false;
        });
    }


function appendDatePicker(){
    return '<div id="ui-datepicker-footer"><a href="#">clear dates</a></div><script type="text/javascript">attachDatepickerFooterEvent();</script>';
    }

function dateFields(checkInDate, checkOutDate, customOptions){
	
	customOptions = $.extend({}, defaultCustomOptions, customOptions);
	
    if(($.cookie("filterCheckin") != null && $.cookie("filterCheckin") != '') && ($.cookie("filterCheckout") != null && $.cookie("filterCheckout") != '')){
        $(checkInDate).val($.cookie("filterCheckin"));
        $(checkOutDate).val($.cookie("filterCheckout"));
    }else{
        inputTipper(checkInDate, 'check-in');
        inputTipper(checkOutDate, 'check-out');         
    }

    var options = {isAppendDatePicker: true, nextText: '', prevText: '', beforeShow: function(input){curDateField = $(input);onDatePicker();}, onClose: function(text, Obj){          
        if(!curDateField.hasValue()) return; // "clear dates" clicked, do nothing
        if(!curDateField[0].otherfield.hasValue())setTimeout(function(){curDateField[0].otherfield.trigger('focus');}, 200); // the delay fixes a prev/next month arrow clich
        else if(customOptions.autosubmit)setTimeout(function(){curDateField.parents('form:first').submit();}, 300); // delay so the calendar can fade out
        }, onSelect: function() {handleDateClick(customOptions.callFormSubmit, customOptions.isUpdateCookie);}};
    checkInDate = $(checkInDate).datepicker(options);
    checkOutDate = $(checkOutDate).datepicker(options);
    checkInDate[0].otherfield = checkInDate[0].checkout = checkOutDate;
    checkOutDate[0].otherfield = checkOutDate[0].checkin = checkInDate;
    checkInDate[0].defaultvalue = 'check-in';
    checkOutDate[0].defaultvalue = 'check-out';
    checkInDate[0].customOptions = customOptions;
    checkOutDate[0].customOptions = customOptions;
    
}

function addDatesToUrl(checkInDate, checkOutDate, url){
	checkInDate = checkInDate.split("/")[0] +"-"+ checkInDate.split("/")[1] +"-"+ checkInDate.split("/")[2];
	checkOutDate = checkOutDate.split("/")[0] +"-"+ checkOutDate.split("/")[1] +"-"+ checkOutDate.split("/")[2];
	url = url + "?checkIn=" + checkInDate + "&checkOut=" + checkOutDate;
	return url;
	
}

var defaultCustomOptions = {
		autosubmit : false,
		callFormSubmit : false,
		isUpdateCookie : true
	};

var checkincookie;
var checkoutcookie;

$(document).ready(function(){
    $('#search-btn').bind('click',function(){var flag = checkdates($('#checkin').val(), $('#checkout').val());return flag;});
    //To apply the date validation onto map click.
    $('area').bind('click',function(){
    	var flag = checkdates($('#checkin').val(), $('#checkout').val());
    	if (flag){
    		if( $.cookie("filterCheckin") && $.cookie("filterCheckout") ){
    			var checkInDate = $.cookie("filterCheckin");
    			checkInDate = checkInDate.split("/")[0] +"-"+ checkInDate.split("/")[1] +"-"+ checkInDate.split("/")[2];
    			var checkOutDate = $.cookie("filterCheckout");
    			checkOutDate = checkOutDate.split("/")[0] +"-"+ checkOutDate.split("/")[1] +"-"+ checkOutDate.split("/")[2];
    			var url = $(this).attr('href') + "&checkIn=" + checkInDate + "&checkOut=" + checkOutDate;
    			this.href = this.href.replace($(this).attr('href'), url);	
    			return true;
    		}
    	}else return flag;	

	});
    $.cookie("dateUpdated", "", { path: '/' });
    checkincookie = $.cookie("filterCheckin");
    checkoutcookie = $.cookie("filterCheckout");
    //apply the date validation onto region link click on FAR page.
    $('div.wide').find('a').bind('click',function(){var flag = checkdates($('#checkin').val(), $('#checkout').val());return flag;});
    //added availability date range for search from about page
    $('ul.arrowlist').find('a').bind('click', function(){
    	if( $.cookie("filterCheckin") && $.cookie("filterCheckout") ){
    		var url = addDatesToUrl($.cookie("filterCheckin"), $.cookie("filterCheckout"), $(this).attr('href'));  
    		this.href = this.href.replace($(this).attr('href'), url);	
    		return true;
    	}
    });
    	
});

