if (outrig === undefined) {
    var outrig = {};
}

outrig.book = function() {
    /*	**************************************		CONFIG OPTIONS	***/
    var defDaysDiff = 3; //	Default days between check in and check out values
    
    /*	**************************************		INITIALIZATION	***/
    var _jsonObject = null;
    var _prepopulateData = null;
    var _destListElm = null;
    var _propsListElm = null;
    var _propsListDefaultOptText = undefined;

    //	jQuery DOM element handlers
    var required = {
        "checkIn": ".book-checkin-fld",
        "checkOut": ".book-checkout-fld",
        "destination": ".book-dest-fld",
        "property": ".book-prop-fld",
        "propertiesList": ".book-prop-list-fld"
    };
    var all = "";
    var $ctrls = {};
    jQuery.each(required, function(index, value) {
        $ctrls[index] = jQuery(value);
        all += value + ", ";
    });

    var $ctrlsReq = jQuery(all); //	Cache all required fields into one JQ object
    $ctrls.submit = jQuery(".book-submit-btn");
    $ctrls.dpTrigger = jQuery(".con-book .datepicker-ico img, .con-book-full .datepicker-ico img");
    $ctrls.numAdults = jQuery(".book-adults-fld");
    $ctrls.numChildren = jQuery(".book-children-fld");
    $ctrls.numRooms = jQuery(".book-rooms-fld");
    $ctrls.totalGuests = jQuery(".book-total-guests-val");

    //	Initialize UI and attach event listeners
    if (jQuery('.booking_widget_mode').val() != "mini") {
    //    $ctrls.submit.attr("disabled", true); //	By default disabled until user selects destination//DISABLEBTN
    }
    else {
        //If destination was pre-selected on server side, assume mini-booking widget
        //which means we already know the destination and property so user can't pick.
        $ctrls.destination.hide();
        $ctrls.property.hide();
    }

    //  DATEPICKER
    $ctrls.checkIn.datepicker({
        numberOfMonths: 2,
        changeMonth: true,
        closeText: 'Close',
        showOtherMonths: true,
        minDate: 0,
        maxDate: "+1y"
    })
    $ctrls.checkOut.datepicker({
        numberOfMonths: 2,
        changeMonth: true,
        closeText: 'Close',
        showOtherMonths: true,
        minDate: 1,
        maxDate: "+1y +1d"
    })
    $ctrls.checkIn.datepicker().change(function() { validateBookDates(this); }).datepicker("setDate", new Date());
    
    $ctrls.checkIn.click(function(){ _bCurrentCheckControl = $ctrls.checkIn; });
    $ctrls.checkOut.click(function(){ _bCurrentCheckControl = $ctrls.checkOut; });
    
    $ctrls.checkOut.datepicker().change(function() { validateBookDates(this); }).datepicker("setDate", '+' + defDaysDiff);
    $ctrls.destination.change(function() { updateSelOpt($ctrls.destination, $ctrls.property); });
    $ctrlsReq.change(function() { onRequiredChange(); });
    //  Trigger check in datepicker if icon is clicked
    
    var _bCurrentCheckControl = $ctrls.checkIn;
    
    $ctrls.dpTrigger.click(function() {
        //$ctrls.checkIn.datepicker('show');
        _bCurrentCheckControl.datepicker('show');
    });

    //  Add hidden input to handle "All condos" option
    // (obsolete) jQuery(".book-form").append('<input type="hidden" id="propertiesList" name="propertiesList" />');
    var propertyDefaultText = jQuery(":selected", $ctrls.property).text();

    // Retreive JSON destination and property data
    if (typeof (jsonDestination) != "undefined") {
        _jsonObject = jsonDestination;
        /*
        if(updateSelOpt($ctrls.destination, $ctrls.property) > 0) {
            $ctrls.submit.attr("disabled", false);
        }
        */
        //DISABLEBTN
        
    }
    
    if (typeof (jsonMinimumData) != "undefined") {
        _prepopulateData = jsonMinimumData;
        updateSelOpt($ctrls.destination, $ctrls.property);
        //$ctrls.submit.attr("disabled", false);//DISABLEBTN
    }

    //Prepopulate form if data is available
    if (typeof (jsonReservation) != "undefined") {
        _prepopulateData = jsonReservation;
        updateSelOpt($ctrls.destination, $ctrls.property);
        $ctrls.checkIn.datepicker("setDate", new Date(parseInt(_prepopulateData.CheckInDate.substr(6))));
        $ctrls.checkOut.datepicker("setDate", new Date(parseInt(_prepopulateData.CheckOutDate.substr(6))));
        //$ctrls.submit.attr("disabled", false);//DISABLEBTN
    }

    /*	*************************************** 			METHODS		***/

    /*
    * onRequiredChange
    * evt handler
    * Conditions to enable submit btn:
    * - Destination value is not empty
    */
    var onRequiredChange = function() {
        /*
        $ctrls.submit.attr("disabled", true);
        if ($ctrls.destination.val() != "") {
            $ctrls.submit.attr("disabled", false);
        }
        */
        //DISABLEBTN
    }
    /*
    * updateTotalGuests
    */
    var updateTotalGuests = function(el) {
		$ctrls.totalGuests.html( "&nbsp;"+(parseInt($ctrls.numAdults.val()) + parseInt($ctrls.numChildren.val())) * parseInt($ctrls.numRooms.val()) );
	}
    /*
    * validateBookDates
    * @param {object} el - element that recieved the change
    * 
    * Executes upon change on date inputs
    * If checkout date is previous or equal to checkin sets the one that didn't change
    * to one day after or before the new one to make dates consistent
    */
    var validateBookDates = function(el) {
        if ($ctrls.checkIn.val() != "" && $ctrls.checkOut.val() != "") {
            var checkIn_date = new Date($ctrls.checkIn.val());
            var checkOut_date = new Date($ctrls.checkOut.val());
            //	Determine who changed
            if (jQuery(el).attr("name") == $ctrls.checkIn.attr("name")) {
                //	checkIn changed
                //	Compare dates
                if (checkOut_date <= checkIn_date) {
                    var newDate = $ctrls.checkIn.datepicker("getDate");
                    $ctrls.checkOut.datepicker("setDate", new Date(newDate.setDate(newDate.getDate() + defDaysDiff)));
                }
                //	Checkin changed, trigger checkout show.
                //	Delay so checkin finishes closing (doesn't work otherwise)
                 
                 jQuery(required.checkIn).stop(true,true);
                 var t;
                 
                 if(jQuery.browser.msie && jQuery.browser.version.indexOf("6")== 0){
                    t = setTimeout("jQuery('" + required.checkOut + "').datepicker('show')", 1200);
                 }else{
                    t = setTimeout("jQuery('" + required.checkOut + "').datepicker('show')", 500);
                 }
                 
                 _bCurrentCheckControl= jQuery(required.checkOut);
                
            }
            else {
                if (checkOut_date <= checkIn_date) {
                    //	checkOut changed
                    var newDate = $ctrls["checkOut"].datepicker("getDate");
                    $ctrls["checkIn"].datepicker("setDate", new Date(newDate.setDate(newDate.getDate() - defDaysDiff)));
                }
            }

        }
    }

    /*
    * function updateSelOpt
    * @param field1 {object} select box that changed
    * @param field1 {object} select box to be populated
    * 		Read options from configuration object, populate level 2
    * 		select box
    *  2010-06-01 Updated to support All condos with value=0 and d a hidden input with properties IDs
    */
    function updateSelOpt($field1, $field2) {
        $field2.html("");
        var selectedIndex = -1;
        var numProperties = 0;
        var destination = _jsonObject[getDestinationIndex($field1.val())];
        //Populate properties list
        if (destination !== undefined) {
            var propObj = destination.Properties;
            var externalPropObj = destination.ExternalProperties;
            if (propObj || externalPropObj) {
                var listItems = '<option value="-1">' + jQuery('.label-all-props').val() + '</option>';
                var allProps = "";
                for (var i = 0; i < propObj.length; i++) {
                    listItems += createOptionElement(propObj[i].Code, propObj[i].Name);
                    if (_prepopulateData && _prepopulateData.PropertyCode == propObj[i].Code) selectedIndex = i;
                    allProps += propObj[i].Code + "|";
                }
                for (var i = 0; i < externalPropObj.length; i++) {
                    listItems += createOptionElement(externalPropObj[i].Code, externalPropObj[i].Name);
                    if (_prepopulateData && _prepopulateData.PropertyCode == propObj[i].Code) selectedIndex = i;
                    allProps += propObj[i].Code + "|";
                }
                numProperties = propObj.length + 1;
                //(obsolete) jQuery("#propertiesList").val(allProps);
                $ctrls.propertiesList.val(allProps);

            } else {
                listItems += createOptionElement(undefined, _propsListDefaultOptText);
            }
        }
        else {
            listItems = '<option value="0">' + propertyDefaultText + '</option>';
        }
        $field2.html(listItems);

        //If we had prepopulate data, set selected index of properites list
        if (selectedIndex > -1) {
            $field2.get(0).selectedIndex = selectedIndex + 1;
        }
        return numProperties;
    }
    function getDestinationIndex(sCode) {
        for (var i = 0; i < _jsonObject.length; i++) {
            if (_jsonObject[i].Code == sCode)
                return i;
        }
    }
    /*
    * function createOptionElement
    * @param value {string} value to be applied to option
    * @param label {string} text to be applied to option
    * 		Creates an option item to be added to a select list
    */
    function createOptionElement(value, label) {
        return "<option value='" + value + "'>" + label + "</option>";
    }

    //	Full has total number of guests to auto update
    if (jQuery('.con-book-full').length) {
        $ctrls.numAdults.change(function() { updateTotalGuests(); });
        $ctrls.numChildren.change(function() { updateTotalGuests(); });
        $ctrls.numRooms.change(function() { updateTotalGuests(); });
    }
    updateTotalGuests();    //  init total num of guests
    
}                                                                       //outrig.book END
var $j = jQuery.noConflict();
$j(document).ready(function() {
if (jQuery('.con-book').length || jQuery('.con-book-full').length) {
        var book = new outrig.book();
    }
});


/***********************************************************
* VALIDATOR CONTROL FUNCTIONS                         *
***********************************************************/
/*
* function onClickSubmit
* @param e {object} event object
* 		Validates check in and check out dates when submit
* 		button is clicked
*/
function onClickSubmit(oSrc, args) {

    if (jQuery(".book-dest-fld").val() == "") {
        args.IsValid = false;
        return;
    }
    var checkin;
    var checkout;

    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].className.indexOf("book-checkin-fld") != -1) {
            checkin = inputs[i];
        }
        else if (inputs[i].className.indexOf("book-checkout-fld") != -1) {
            checkout = inputs[i];
        }
    }

    var validCheckIn = validateDate(checkin.value);
    if (!validCheckIn) {
        alert("Please enter a valid check in date.");
        checkin.value = "";
        checkin.focus();
        args.IsValid = false;
        return;
    }

    var validCheckOut = validateDate(checkout.value);
    if (!validCheckOut) {
        alert("Please enter a valid check out date.");
        checkout.value = "";
        checkout.focus();
        args.IsValid = false;
        return;
    }

    args.IsValid = true;

    showLoadingDialog();
    return false;
}

    /* progressbar animation */
    function progressBar() {
        var jqt = setTimeout(function () { jQuery('.dialog-results-loading .dialog-progressbar').css({ 'background-image': 'url(../images/loader-spinner.gif)' }); }, 250);
    }

    /* build dialog object */
    var dialogLoading = jQuery(".dialog-results-loading").dialog({
        bgiframe: true,
        autoOpen: false,
        modal: true,
        dialogClass: 'results-loading',
        width: 669,
        height: 240,
        zIndex: 3999,
        position: 'center',
        resizable: false,
        open: function (ev, ui) {
            if (jQuery.browser.msie && jQuery.browser.version.indexOf("6") == 0) {
                jQuery('select').css('visibility', 'hidden');
            }
            jQuery('.results-loading').css('border', '4px solid #999');
            progressBar();
        },
        close: function (ev, ui) {
            jQuery('select').css('visibility', 'visible');
        }
    });

    /* show processing dialog */
    function showLoadingDialog() {
        dialogLoading.dialog('open');
    }

/*
* function validateDate
* @param inDate {object} date string
* 		Validates that the date string is in MM/DD/YYYY format and that the
* 		date is not in the past.
*/
function validateDate(inDate) {
    return true;
    
    var invalid = false;
    var params = inDate.split("/");

    //Validate format
    if (params.length != 3 || params[0].length != 2 || params[1].length != 2 || params[2].length != 4) {
        return invalid;
    }

    //Validate data type
    var now = new Date();
    var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    var date = new Date(params[2], parseInt(params[0], 10) - 1, parseInt(params[1], 10));
    if (date < today) {
        return invalid;
    }

    return !invalid;
}

