﻿var isOptionOpen = false;
var extraOptionsSelected = false;
var resultPageType = 1;
var refineUpdate = null; //function name if a postback is required on the parent page. embeddedsearch currently uses this.
function slideSearchDivDown() {
    $('#divSliders').slideToggle("fast");

    toggleOptionButton();
    $('#dvPassengerAttributes').slideToggle("fast");
    //reset searchCriteria
}

function toggleOptionButton() {
    //set the option to its opposite
    isOptionOpen = !isOptionOpen;

    if (isOptionOpen) {
        $('#imgOptions').attr('src', '/img/Icons/openArrow.gif');
        $('#aOptions').text('Hide Options');
        $('#dvExtraFunc').fadeIn('slow');
    }
    else {
        $('#imgOptions').attr('src', '/img/Icons/downarrow.gif');
        $('#aOptions').text('More Options');
        $('#dvExtraFunc').fadeOut('fast');
    }
}

var skiSearch =
{
    details: null,
    searchCriteria:
    {
        Countries: [],
        Resorts: [],
        Airports: [],
        DateRanges: [],
        PropertyTypes: [],
        BoardBasis: [],
        Features: [],
        Regions: [],
        SkiAreas: [],
        PropertyRatings: [],
        PriceRange: [],
        Flexibility: 2,
        Duration: 0,
        WholeChalet: false,
        AccommodationOnly: false,
        Passengers: 0,
        PropertyRating: 0,
        Adults: 0,
        Children: 0,
        ChildCare: false,
        Slopes: false,
        addCountry: function (countryCode) {
            this.Countries = new Array();
            this.Countries[this.Countries.length] = { 'code': countryCode };
        },
        addSkiArea: function (skiAreaId) {
            this.SkiAreas = new Array();
            this.SkiAreas[this.SkiAreas.length] = { 'id': skiAreaId };
        },
        addRegion: function (regionId) {
            this.clearRegions();
            this.Regions[this.Regions.length] = { 'id': regionId };
        },
        clearCountry: function () {
            this.Countries.length = 0;
            this.SkiAreas.length = 0;
        },

        removeCountry: function (countryCode) {
            this.Countries = removeElementFromArray(this.Countries, countryCode);
        },

        addDateRange: function (startDate, endDate) {
            this.DateRanges[this.DateRanges.length] = { 'startDate': startDate, 'endDate': endDate };
        },

        clearDateRange: function () {
            this.DateRanges.length = 0;
        },

        clearPropertyType: function () {
            this.PropertyTypes.length = 0;
        },
        clearBoardBasis: function () {
            this.BoardBasis.length = 0;
        },
        clearFeatures: function () {
            this.Features.length = 0;
        },
        clearRegions: function () {
            this.Regions.length = 0;
        },
        clearPropertyRatings: function () {
            this.PropertyRatings.length = 0;
        },
        clearPriceRange: function () {
            this.PriceRange.length = 0;
        },
        removeDateRange: function (startDate, endDate) {

        },

        addResort: function (resortId) {
            this.Resorts[this.Resorts.length] = { 'id': resortId };
        },

        clearResort: function () {
            this.Resorts.length = 0;
        },

        removeResort: function (resortId) {
            this.Resorts = removeElementFromArray(this.Resorts, resortId);
        },

        addDeparturePort: function (departurePortId) {
            this.Airports[this.Airports.length] = { 'id': departurePortId };
        },

        clearDeparturePort: function () {
            this.Airports.length = 0;
        },

        removeDeparturePort: function (departurePortId) {
            this.Airports = removeElementFromArray(this.Airports, departurePortId);
        },

        setFlexibility: function (flexibility) {
            skiSearch.resetSearchCriteria("f");
            this.Flexibility = flexibility;
        },

        setDuration: function (duration) {
            skiSearch.resetSearchCriteria('d');
            this.Duration = duration;
        },

        toggleFeature: function (checked, featureId) {

            if (checked) {
                if (skiSearch.itemExistsInArray(this.Features, featureId))
                    this.Features = skiSearch.removeElementFromArray(this.Features, featureId);

                this.Features[this.Features.length] = featureId;
            }
            else {
                if (skiSearch.itemExistsInArray(this.Features, featureId))
                    this.Features = skiSearch.removeElementFromArray(this.Features, featureId);
            }
        },

        toggleBoardBasis: function (boardBasisCode) {

            this.clearBoardBasis();
            if (skiSearch.itemExistsInArray(this.BoardBasis, boardBasisCode))
                this.BoardBasis = skiSearch.removeElementFromArray(this.BoardBasis, boardBasisCode);
            else
                this.BoardBasis[this.BoardBasis.length] = boardBasisCode;
        },

        togglePropertyType: function (propertyTypeCode) {
            if (skiSearch.itemExistsInArray(this.PropertyTypes, propertyTypeCode))
                this.PropertyTypes = skiSearch.removeElementFromArray(this.PropertyTypes, propertyTypeCode);
            else
                this.PropertyTypes[this.PropertyTypes.length] = propertyTypeCode;
        },

        setWholeChalet: function (wholeChalet) {
            this.WholeChalet = wholeChalet;
        },

        setSlopes: function (nearSlopes) {
            this.Slopes = nearSlopes;
        },
        setChildCare: function (childCare) {
            this.ChildCare = childCare;
        },
        setPassengers: function (adults, children) {
            this.Passengers = adults + children;
            this.Adults = adults;
            this.Children = children;
        },

        setRating: function (rating) {
            this.clearPropertyRatings();
            for (var i = 0; i < rating.length; i++)
                this.PropertyRatings[this.PropertyRatings.length] = parseInt(rating[i]);
        },
        setPriceRange: function (priceRange) {
            this.clearPriceRange();
            for (var i = 0; i < priceRange.length; i++)
                this.PriceRange[this.PriceRange.length] = parseInt(priceRange[i]);
        },

        setAccommodationOnly: function (accommodationOnly) {
            this.AccommodationOnly = accommodationOnly;
        }
    },

    enableGroupChalet: function () {
        // get total party size
        var totalParty = parseInt($('#ddlAdults').val()) + parseInt($('#ddlChildren').val());
        // first get the accommodation type and make sure it is a chalet
        var accomType = $('#ddlAccom option:selected').text();
        // only enable if chalet and total party size is greater than 5
        if (accomType == 'Chalet' && totalParty >= 6) {
            $('#chkGroupChalet').removeAttr('disabled');
        }
        else {
            $('#chkGroupChalet').attr('checked', false)
                                .attr('disabled', true);

            skiSearch.changeWholeChalet(false);
        }
    },

    BindCriteria: function () {
        var myObject = null;
        if (resultPageType == 1) {
            myObject =
        {
            'id': 1,
            'method': 'GetHomepageSearchCriteria',
            'params':
            {
                'topResortOnly': 0
            }
        };
        }
        else {
            myObject =
        {
            'id': 1,
            'method': 'GetOfferResultsSearchCriteria'
        };
        }
        //Fetch the search crtiera
        $.ajax({
            url: "/Services/JSON/HolidaySearch.ashx",
            data: JSON.stringify(myObject),
            contentType: 'application/json',
            type: "POST",
            dataType: 'json',
            cache: false,
            success: function (a) {
                skiSearch.bindToSearch(a);
            },
            dataType: 'json'
        });
    },
    removeElementFromArray: function (array, identifier) {
        var returnArray = [];
        for (var i = 0; i < array.length; i++)
            if ((array[i].id != null && array[i].id.toString() != identifier.toString()) || (array[i].code != null && array[i].code.toString() != identifier.toString()) || array[i] != identifier)
                returnArray[returnArray.length] = array[i];

        return returnArray;
    },

    itemExistsInArray: function (array, identifier) {
        for (var i = 0; i < array.length; i++)
            if ((array[i].id != null && array[i].id.toString() == identifier.toString()) || (array[i].code != null && array[i].code.toString() == identifier.toString()) || array[i] == identifier)
                return true;

        return false;
    },
    bindDuration: function (destination, input, selectedOption, type) {
        destination.empty();
        if (input.length > 1)
            destination.append("<option  value=\"Any\">Any Duration</option>");
        for (var i = 0; i < input.length; i++) {
            if (input[i] == selectedOption) {
                destination.append("<option selected=\"selected\" value=\"" + input[i] + "\">" + skiSearch.getDurationDisplay(input[i]) + "</option>");
                skiSearch.populateFromSearch(type, selectedOption);
            }
            else
                destination.append("<option  value=\"" + input[i] + "\">" + skiSearch.getDurationDisplay(input[i]) + "</option>");
        }
    },
    getDurationDisplay: function (nights) {
        switch (nights) {
            case -2:
                return "< 7 Nights";
            default:
                return nights + " " + "Nights";
        }
    },
    getDurationDisplayByInt: function (nights) {
        switch (nights) {
            case -2:
                return "< 7 Nights";
            default:
                return nights + " " + "Nights";
        }
    },
    bindArrayToSelect: function (destination, input, firstLine) {
        destination.empty();

        if (firstLine)
            destination.append("<option value=\"" + firstLine.code + "\">" + firstLine.name + "</option>");

        for (var i = 0; i < input.length; i++)
            destination.append("<option value=\"" + (input[i].code || input[i].id) + "\">" + input[i].name + "</option>");
    },

    bindArrayToSelect: function (destination, input, firstLine, selectedOption, type) {
        destination.empty();
        if (firstLine)
            destination.append("<option value=\"" + firstLine.code + "\">" + firstLine.name + "</option>");

        for (var i = 0; i < input.length; i++) {
            //check for the previouslyselected options and set the search criteria
            if (selectedOption == (input[i].code || input[i].id)) {

                //populate the criteria
                skiSearch.populateFromSearch(type, (input[i].code || input[i].id));

                destination.append("<option selected=\"selected\" value=\"" + (input[i].code || input[i].id) + "\">" + input[i].name + "</option>");
            }
            else
                destination.append("<option value=\"" + (input[i].code || input[i].id) + "\">" + input[i].name + "</option>");
        }
    },

    bindSelectByGroup: function (destination, input, firstLine, selectedOption, groupName, type) {
        var options = "";
        if (type == "c") {
            options += "<option value=\"" + firstLine.code + "\">" + firstLine.name + "</option>";
            options += "<optgroup label=\"" + groupName + "\">";
        }
        else {
            options = "<optgroup label=\"" + groupName + "\">";
            if (firstLine != null)
                options += "<option value=\"" + firstLine.code + "\">" + firstLine.name + "</option>";

        }
        for (var i = 0; i < input.length; i++) {

            if (selectedOption == (input[i].code || input[i].id)) {

                //populate the criteria
                options += "<option selected = \"selected\" value=\"" + (input[i].code || input[i].id) + "\">" + input[i].name + "</option>";
                skiSearch.populateFromSearch(type, (input[i].code || input[i].id));

                //do the control                
            }
            else
                options += "<option value=\"" + (input[i].code || input[i].id) + "\">" + input[i].name + "</option>";
        }

        destination.append(options + "</optgroup>");

    },

    bindSelect: function (listName, selectedOption, type) {

        if (selectedOption.toLowerCase() == "any")
            return;
        $(listName + ' option').each(function (i) {
            if ($(this).val().toLowerCase() == selectedOption.toLowerCase()) {
                $(this).attr('selected', 'selected');
                skiSearch.populateFromSearch(type, selectedOption);
            }
        });

    },

    bindBoardBasis: function (listName, selectedOption, type) {
        if (skiSearch.details.boardBasis.length > 1)
            $(listName).append("<option value=\"Any\">Any Board</option>");
        for (var i = 0; i < skiSearch.details.boardBasis.length; i++) {

            if (selectedOption == skiSearch.details.boardBasis[i].split('/')[0]) {

                $(listName).append("<option selected = \"selected\"  value=\"" + skiSearch.details.boardBasis[i].split('/')[0] + "\">" + skiSearch.details.boardBasis[i].split('/')[1] + "</option>");
                skiSearch.populateFromSearch(type, selectedOption);

            }
            else
                $(listName).append("<option value=\"" + skiSearch.details.boardBasis[i].split('/')[0] + "\">" + skiSearch.details.boardBasis[i].split('/')[1] + "</option>");
        }
        if (selectedOption.toLowerCase() == "any")
            this.searchCriteria.clearBoardBasis();
    },
    bindAccommSelect: function (listName, selectedOption, type) {

        if (skiSearch.details.propertyTypes.length > 1)
            $(listName).append("<option value=\"Any\">Any Type</option>");
        var selString = '';
        for (var i = 0; i < skiSearch.details.propertyTypes.length; i++) {

            if (selectedOption == skiSearch.details.propertyTypes[i].split('/')[0]) {
                $(listName).append("<option selected = \"selected\" value=\"" + skiSearch.details.propertyTypes[i].split('/')[0] + "\">" + skiSearch.details.propertyTypes[i].split('/')[1] + "</option>");
                skiSearch.populateFromSearch(type, selectedOption);
            }
            else
                $(listName).append("<option value=\"" + skiSearch.details.propertyTypes[i].split('/')[0] + "\">" + skiSearch.details.propertyTypes[i].split('/')[1] + "</option>");
        }
        if (selectedOption.toLowerCase() == "any")
            this.searchCriteria.clearPropertyType();
    },
    bindCheckBoxes: function (name, isSelected, controlName, value) {
        switch (name.toLowerCase()) {

            case "childcare":
                $(controlName).attr("checked", isSelected);
                skiSearch.changeChildCare(isSelected);
                break;
            case "slopes":
                $(controlName).attr("checked", isSelected);
                skiSearch.changeSlopes(isSelected);
                break;
            case "groupchalet":
                $(controlName).attr("checked", isSelected);
                skiSearch.changeWholeChalet(isSelected)
                break;
            case "snowboard":
                $(controlName).attr("checked", isSelected);
                skiSearch.changeFeature(isSelected, value);
                break;
        }

        if (isSelected && !extraOptionsSelected)
            extraOptionsSelected = true;
    },
    /*
    Type Values
    a=airport, ad=adults, c=country, ch=children, d=duration, ac=propertytype, ra=rating f=flex r=resort* mon=month da= day*/
    populateFromSearch: function (type, selectedVal) {
        switch (type) {
            case "a": //airport
                skiSearch.searchCriteria.addDeparturePort(selectedVal);
                break;
            case "se": //skiArea
                skiSearch.searchCriteria.addSkiArea(selectedVal);
                break;
            case "re": //region
                skiSearch.searchCriteria.addRegion(selectedVal);
                break;
            case "r": //resort
                skiSearch.searchCriteria.addResort(selectedVal);
                var resort = this.findItemInArray(this.details.resorts, selectedVal);
                skiSearch.toggleCountryOrSkiAreaBind(resort)
                //bind the country back
                break;
            case "c": //ccountry
                skiSearch.searchCriteria.addCountry(selectedVal);
                break;
            case "f": //flexibility
                skiSearch.searchCriteria.setFlexibility(selectedVal);
                break;
            case "ac": //propertytype
                skiSearch.setPropertyTypeFromValue(selectedVal);
                break;
            case "ad": //adults
                skiSearch.searchCriteria.Adults = selectedVal;
                skiSearch.searchCriteria.Passengers += parseInt(selectedVal)
                if (selectedVal != "2")
                    extraOptionsSelected = true;
                break;
            case "ch": //children
                skiSearch.searchCriteria.Children = selectedVal;
                skiSearch.searchCriteria.Passengers += parseInt(selectedVal);
                if (!extraOptionsSelected)
                    extraOptionsSelected = true;
                break;
            case "d": //duration
                skiSearch.searchCriteria.setDuration(selectedVal);
                break;
            case "ra": //rating
                skiSearch.searchCriteria.setRating(selectedVal);
                break;
            case "bb": //boardbasis
                skiSearch.searchCriteria.toggleBoardBasis(selectedVal);
                break;
        }
    },

    populateDateFromSearch: function (monthValue, dayValue) {
        skiSearch.changeSingleDateRange(monthValue, dayValue);
    },
    clearSelect: function (controlName, defautValue, type) {
        $(controlName).val(defautValue);
        skiSearch.resetSearchCriteria(type);
    },
    clearCheckBox: function (controlName, type) {
        $(controlName).attr("checked", false);
        skiSearch.resetSearchCriteria(type);
    },
    clearSliders: function (control, defautValue, type) {
        control.reset(defautValue);
    },
    resetSearchCriteria: function (type) {

        switch (type) {
            case "a": //airport
                skiSearch.searchCriteria.Airports.length = 0;
                skiSearch.searchCriteria.Regions.length = 0;
                break;
            case "r": //resort
                skiSearch.searchCriteria.Resorts.length = 0;
                break;
            case "c": //country            
                skiSearch.searchCriteria.Countries.length = 0;
                skiSearch.searchCriteria.SkiAreas.length = 0;
                break;
            case "f": //flexibility
                skiSearch.searchCriteria.Flexibility = 0;
                break;
            case "ac": //propertytype
                skiSearch.searchCriteria.PropertyTypes.length = 0;
                break;
            case "ad": //adults
                skiSearch.searchCriteria.Adults = 2;
                break;
            case "ch": //children
                skiSearch.searchCriteria.Children = 0;
                break;
            case "d": //duration
                skiSearch.searchCriteria.Duration = 0;
                break;
            case "ra": //rating
                skiSearch.searchCriteria.PropertyRatings.length = 0;
                break;
            case "bb": //boardbasis
                skiSearch.searchCriteria.BoardBasis.length = 0;
                break;
            case "pr": //priceRange
                skiSearch.searchCriteria.PriceRange.length = 0;
                break;
            case "wholechalet":
                skiSearch.searchCriteria.WholeChalet = false;
                break;
            case "snowboard":
                skiSearch.searchCriteria.Features.length = 0;
                break;
            case "slopes":
                skiSearch.searchCriteria.Slopes = false;
                break;
            case "childcare":
                skiSearch.searchCriteria.ChildCare = false;
                break;
            case "monthyear":
            case "day":
                skiSearch.searchCriteria.DateRanges.length = 0;
                break;
        }

    },
    findItemInArray: function (array, identifier) {
        for (var i = 0; i < array.length; i++)
            if ((array[i].id != null && array[i].id.toString() == identifier.toString()) || (array[i].code != null && array[i].code.toString() == identifier.toString()))
                return array[i];

        return null;
    },

    bindToSearch: function (data) {
        skiSearch.details = data.result;
        //Bind countries and Ski Areas
        skiSearch.bindSelectByGroup($('#ddlCountry'), skiSearch.details.countries, { code: 'Any', name: 'Any Country or Ski Area' }, skiSearch.details.selections.countryCode, "Countries", "c");
        if (skiSearch.details.skiAreas != null && skiSearch.details.skiAreas.length > 0)
            skiSearch.bindSelectByGroup($('#ddlCountry'), skiSearch.details.skiAreas, null, skiSearch.details.selections.skiAreas, "Ski Areas", "se");

        //if A country is selected, then bind the resort
        if (skiSearch.details.selections.countryCode != "Any" && skiSearch.findItemInArray(this.details.countries, skiSearch.details.selections.countryCode) != null)
            skiSearch.bindCountryChildResorts(skiSearch.details.selections.countryCode, skiSearch.details.selections.resortId);
        //if A SkiArea is selected, then bind the resort
        else if (skiSearch.details.selections.skiAreas != "Any" && skiSearch.findItemInArray(skiSearch.details.skiAreas, skiSearch.details.selections.skiAreas) != null)
            skiSearch.bindSkiAreaChildResorts(skiSearch.details.selections.skiAreas, skiSearch.details.selections.resortId);
        else {
            //bind resorts
            skiSearch.bindArrayToSelect($('#ddlResort'), skiSearch.details.resorts, { code: 'Any', name: 'Any Resort' }, skiSearch.details.selections.resortId, "r");
        }
        //now select the resort
        skiSearch.changeSelectedResort(false);

        //toggleResort
        skiSearch.toggleBackGroundColor($('#ddlResort')[0]);
        //toggleCountry
        skiSearch.toggleBackGroundColor($('#ddlCountry')[0]);


        //bind accommodation
        if (skiSearch.details.selections.accomOnly) {
            $("#ddlDepartFrom option[value='AccomOnly']").attr('selected', 'selected');
            skiSearch.searchCriteria.setAccommodationOnly(true);
            //bind regions
            skiSearch.bindSelectByGroup($('#ddlDepartFrom'), skiSearch.details.regions, null, "", "Regions", "re");
            //bind ports
            skiSearch.bindSelectByGroup($('#ddlDepartFrom'), skiSearch.details.airports, null, "", "Airports", "a");
        }
        else {
            //bind regions
            skiSearch.bindSelectByGroup($('#ddlDepartFrom'), skiSearch.details.regions, null, skiSearch.details.selections.regions, "Regions", "re");
            //bind ports
            skiSearch.bindSelectByGroup($('#ddlDepartFrom'), skiSearch.details.airports, null, skiSearch.details.selections.portId, "Airports", "a");
        }
        skiSearch.toggleBackGroundColor($('#ddlDepartFrom')[0]);


        //flex
        skiSearch.bindSelect('#ddlDateFlexibility', skiSearch.details.selections.flex, "f");
        skiSearch.toggleBackGroundColor($('#ddlDateFlexibility')[0]);

        //accomType       
        skiSearch.bindAccommSelect('#ddlAccom', skiSearch.details.selections.accomType, "ac");
        skiSearch.toggleBackGroundColor($('#ddlAccom')[0]);

        //adults
        skiSearch.bindSelect('#ddlAdults', skiSearch.details.selections.adults, "ad");
        skiSearch.toggleAdultBackGroundColor($('#ddlAdults')[0]);

        //children
        skiSearch.bindSelect('#ddlChildren', skiSearch.details.selections.children, "ch");
        skiSearch.toggleBackGroundColor($('#ddlChildren')[0]);

        //priceRange        
        skiSearch.bindPriceRange(skiSearch.details.selections.priceRanges);

        //rating
        if (skiSearch.details.selections.minRating > 0)
            skiSearch.bindRatingRange([skiSearch.details.selections.minRating, 5]);
        else
            skiSearch.bindRatingRange(skiSearch.details.selections.ratings);

        //bindate

        if (resultPageType == 1) {
            var dateRange = skiSearch.details.dateRanges[0];
            var startDate = new Date(dateRange.startDateString[0], parseInt(dateRange.startDateString[1]) - 1, dateRange.startDateString[2]);
            var endDate = new Date(dateRange.endDateString[0], parseInt(dateRange.endDateString[1]) - 1, dateRange.endDateString[2]);
            skiSearch.bindDates(startDate, endDate, $('#ddlDay'), $('#ddlMonthYear'), skiSearch.details.selections.monthYear, skiSearch.details.selections.day);
            skiSearch.toggleBackGroundColor($('#ddlMonthYear')[0]);
            skiSearch.toggleBackGroundColor($('#ddlDay')[0]);

            //duration
            skiSearch.bindSelect('#ddlDuration', skiSearch.details.selections.duration, "d");

            skiSearch.toggleBackGroundColor($('#ddlDuration')[0]);
        }
        else {
            if (skiSearch.details.dateRanges.length > 1)
                $('#cbxOfferDate').append("<option value=\"Any\">Any</option>");
            var selString = '';
            for (var i = 0; i < skiSearch.details.dateRanges.length; i++) {
                var dateRange = skiSearch.details.dateRanges[i];
                var startDate = new Date(dateRange.startDateString[0], parseInt(dateRange.startDateString[1]) - 1, dateRange.startDateString[2]);

                if (skiSearch.details.selections.monthYear == startDate.getMonth() + "/" + startDate.getFullYear()
                && skiSearch.details.selections.day == startDate.getDate()) {
                    selString = "selected = \"selected\"";
                    $('#cbxOfferDate').append("<option selected = \"selected\"  value=\"" + startDate.getDate().toString() + "/" + startDate.getMonth().toString() + "/" + startDate.getFullYear() + "\"> "
                 + (startDate.getDate()) + ' (' + igluDays[startDate.getDay()] + ') ' + igluMonths[startDate.getMonth()] + " " +
                 startDate.getFullYear() + " </option>");

                    this.searchCriteria.DateRanges = new Array();
                    this.searchCriteria.DateRanges[this.searchCriteria.DateRanges.length] = { 'startDate': startDate, 'endDate': startDate };
                }
                else {
                    $('#cbxOfferDate').append("<option  value=\"" + startDate.getDate().toString() + "/" + startDate.getMonth().toString() + "/" + startDate.getFullYear() + "\"> "
                 + (startDate.getDate()) + ' (' + igluDays[startDate.getDay()] + ') ' + igluMonths[startDate.getMonth()] + " " +
                 startDate.getFullYear() + " </option>");
                }
                skiSearch.toggleBackGroundColor($('#cbxOfferDate')[0]);
            }

            if (selString == '')
                this.searchCriteria.DateRanges = new Array();
            skiSearch.bindDuration($('#ddlDuration'), skiSearch.details.durationOptions, skiSearch.details.selections.duration, "d");
            skiSearch.toggleBackGroundColor($('#ddlDuration')[0]);
        }

        //childcare
        skiSearch.bindCheckBoxes("childcare", skiSearch.details.selections.childCare, '#chkChildCare');
        //slopes
        skiSearch.bindCheckBoxes("slopes", skiSearch.details.selections.slopes, '#chkSlopes');
        //group chalet
        skiSearch.bindCheckBoxes("groupchalet", skiSearch.details.selections.wholeChalet, '#chkGroupChalet');
        if (skiSearch.details.selections.wholeChalet == false) {
            var totalParty = tryParseInt(skiSearch.details.selections.adults, 0) + tryParseInt(skiSearch.details.selections.children, 0);
            if (skiSearch.details.selections.accomType != 'CHA,CHH,CLU' || totalParty < 6) {
                $('#chkGroupChalet').attr('checked', false)
                                    .attr('disabled', true);
            }
        }
        //snowboard
        skiSearch.bindCheckBoxes("snowboard", skiSearch.details.selections.snowBoarding, '#chkSnowBoarding', 107);

        //boardbasis
        var selString = '';
        skiSearch.bindBoardBasis('#ddlBoardBasis', skiSearch.details.selections.boardBasis, "bb");
        skiSearch.toggleBackGroundColor($('#ddlBoardBasis')[0]);
        if (extraOptionsSelected)
            slideSearchDivDown();


    },

    bindCountryBasedOnResort: function (countryCode) {

        try {
            $('#ddlCountry').val(countryCode);
        }
        catch (ex) {
            setTimeout("$('#ddlCountry').val('" + countryCode + "')", 1);
        }
    },

    bindRatingRange: function (selectedRange) {
        if (selectedRange != null && selectedRange.length > 0) {
            refineRatingSlider.setUp([selectedRange[0] == "0" ? 1 : selectedRange[0], selectedRange[1] == "0" ? 5 : selectedRange[1]]);
            this.searchCriteria.setRating([selectedRange[0] == "0" ? 1 : selectedRange[0], selectedRange[1] == "0" ? 5 : selectedRange[1]]);

            if (selectedRange[0] != "1" || selectedRange[1] != "5")
                extraOptionsSelected = true;
        }
        else {
            refineRatingSlider.setUp([1, 5]);
            this.searchCriteria.setRating([1, 5]);
        }
    },
    bindPriceRange: function (selectedRange) {
        if (selectedRange != null && selectedRange.length > 0) {
            //set up the price range from a previous selection
            refinePriceSlider.setUp([selectedRange[0] == "0" ? 0 : selectedRange[0], selectedRange[1] == "0" ? 2000 : selectedRange[1]]);
            this.searchCriteria.setPriceRange([selectedRange[0] == "0" ? 0 : selectedRange[0], selectedRange[1] == "0" ? 2000 : selectedRange[1]]);

            if (selectedRange[0] != "0" || selectedRange[1] != "2000")
                extraOptionsSelected = true;
        }
        else //use default
        {
            refinePriceSlider.setUp([0, 2000]);
            this.searchCriteria.setPriceRange([0, 2000]);
        }
    },
    bindDates: function (startDate, endDate, controlDay, controlMonthYear, selectedMonth, seletedDay) {

        //We only care about Month/Year, set day to first so that feb is included when day is > 28
        startDate = new Date(startDate.getFullYear(), startDate.getMonth(), 1);
        endDate = new Date(endDate.getFullYear(), endDate.getMonth(), 1);

        /*
        Get the start and enddate 
        start a while loop on the date and
        */
        controlMonthYear.empty();
        controlMonthYear.append("<option value=\"Any\">Any Month</option>");
        if (seletedDay == "Any")
            skiSearch.bindDay(controlDay, seletedDay, 31, -1, -1);

        while (startDate <= endDate) {
            if (startDate.getMonth() <= 3 || startDate.getMonth() == 11) {
                if (selectedMonth == startDate.getMonth() + "/" + startDate.getFullYear()) {
                    controlMonthYear.append("<option selected = \"selected\" value=\"" + (startDate.getMonth()) + "/" + startDate.getFullYear() + "\">" + igluMonths[startDate.getMonth()] + " " + startDate.getFullYear() + "</option>");
                    skiSearch.populateDateFromSearch(selectedMonth, seletedDay);
                    skiSearch.bindDay(controlDay, seletedDay, startDate.getMonthDays(startDate.getMonth()), startDate.getMonth(), startDate.getFullYear());
                }
                else
                    controlMonthYear.append("<option value=\"" + (startDate.getMonth()) + "/" + startDate.getFullYear() + "\">" + igluMonths[startDate.getMonth()] + " " + startDate.getFullYear() + "</option>");
            }

            if (startDate.getMonth() == 11)
                startDate = new Date((startDate.getFullYear() + 1), 0, startDate.getDate());
            else
                startDate = new Date(startDate.getFullYear(), (startDate.getMonth() + 1), startDate.getDate());
        }

    },

    bindDay: function (controlDay, selectedDayOfMonth, daysInMonth, currentMonth, currentYear) {

        //get day for the month
        controlDay.empty();
        controlDay.append("<option value=\"Any\">Any Day</option>");
        for (var i = 0; i < daysInMonth; i++) {

            if (selectedDayOfMonth == (i + 1)) {
                var today = new Date(currentYear, currentMonth, selectedDayOfMonth);
                controlDay.append("<option selected = \"selected\" value=\"" + (i + 1) + "\">" + (i + 1) + ' (' + igluDays[today.getDay()] + ')' + " </option>");
            }
            else {
                if (currentMonth == -1 && currentYear == -1)
                    controlDay.append("<option value=\"" + (i + 1) + "\"> " + (i + 1) + " </option>");
                else {
                    var today = new Date(currentYear, currentMonth, (i + 1));
                    controlDay.append("<option value=\"" + (i + 1) + "\"> " + (i + 1) + ' (' + igluDays[today.getDay()] + ')' + " </option>");
                }
            }
        }
    },
    reset: function () {
        var myObject =
        {
            'id': 1,
            'method': resultPageType == 1 ? 'SearchResetAndReturnDefaultResorts' : 'SearchDerivedReset',
            'params':
            {
                'TopResorts': true
            }
        };

        //reset the search in session, and get the default resorts back
        $.ajax({
            url: "/Services/JSON/HolidaySearch.ashx",
            data: JSON.stringify(myObject),
            contentType: 'application/json',
            type: 'POST',
            dataType: 'json',
            success: function (a) {
                skiSearch.searchCriteria.clearResort();
                if (resultPageType == 1) {
                    skiSearch.searchCriteria.Resorts = a.result;
                    skiSearch.bindArrayToSelect($('#ddlResort'), skiSearch.searchCriteria.Resorts, { code: 'Any', name: 'Any Resort' }, "Any", "r");
                }

                skiSearch.clearSelect('#ddlAccom', 'Any', 'ac');
                skiSearch.clearSelect('#ddlCountry', 'Any', 'c');
                skiSearch.clearSelect('#ddlDepartFrom', 'Any', 'a');
                skiSearch.clearSelect('#ddlDuration', 'Any', 'd');
                skiSearch.clearSelect('#ddlRating', 'Any', 'ra');
                if (resultPageType == 1) {
                    skiSearch.clearSelect('#ddlMonthYear', 'Any', 'monthyear');
                    skiSearch.clearSelect('#ddlDay', 'Any', 'day');
                }
                else
                    skiSearch.clearSelect('#cbxOfferDate', 'Any', 'day');
                skiSearch.clearSelect('#ddlDateFlexibility', '2', 'f');
                skiSearch.clearSelect('#ddlAdults', '2', 'ad');
                skiSearch.clearSelect('#ddlChildren', '0', 'ch');
                skiSearch.clearSelect('#ddlBoardBasis', 'Any', 'bb');
                skiSearch.clearCheckBox('#chkSlopes', 'slopes');
                skiSearch.clearCheckBox('#chkSnowBoarding', 'snowboard');
                skiSearch.clearCheckBox('#chkGroupChalet', 'wholechalet');
                skiSearch.clearCheckBox('#chkChildCare', 'childcare');
                skiSearch.clearSliders(refinePriceSlider, [0, 2000], 'pr');
                skiSearch.clearSliders(refineRatingSlider, [1, 5], 'ra');

                skiSearch.toggleBackGroundColor($('#ddlBoardBasis')[0]);
                skiSearch.toggleBackGroundColor($('#ddlResort')[0]);
                skiSearch.toggleBackGroundColor($('#ddlCountry')[0]);
                skiSearch.toggleBackGroundColor($('#ddlDepartFrom')[0]);
                skiSearch.toggleBackGroundColor($('#ddlDateFlexibility')[0]);
                skiSearch.toggleBackGroundColor($('#ddlChildren')[0]);
                skiSearch.toggleBackGroundColor($('#ddlDuration')[0]);
                skiSearch.toggleBackGroundColor($('#ddlAccom')[0]);
                skiSearch.toggleAdultBackGroundColor($('#ddlAdults')[0]);

                //toggleControl Colors        
                if (resultPageType == 1) {
                    skiSearch.toggleBackGroundColor($('#ddlMonthYear')[0]);
                    skiSearch.toggleBackGroundColor($('#ddlDay')[0]);
                    //reset the search in session
                    $.get('/Services/JSON/HolidaySearch.ashx/SearchReset');
                }
                else {
                    skiSearch.toggleBackGroundColor($('#cbxOfferDate')[0]);
                    $.get('/Services/JSON/HolidaySearch.ashx/SearchDerivedReset');
                }
            }
        });
    },

    changeSelectedCountry: function () {
        var selectedCountry = $('#ddlCountry option:selected');
        this.searchCriteria.clearCountry();

        if (selectedCountry.val() != 'Any') {
            if (selectedCountry.parent().attr('label') != "Ski Areas")
                skiSearch.bindCountryChildResorts(selectedCountry.val(), "Any");
            else
                skiSearch.bindSkiAreaChildResorts(selectedCountry.val(), "Any");

            //Bind all Resorts that match that country            
        }
        else {
            $('#ddlResort').empty();
            skiSearch.bindArrayToSelect($('#ddlResort'), this.details.resorts, { code: 'Any', name: 'Any Resort' }, skiSearch.details.selections.resortId, "r");
        }
        //fetchHolidayCount();
    },
    bindSkiAreaChildResorts: function (value, resortId) {
        var skiArea = this.findItemInArray(this.details.skiAreas, value);
        var ddlResortText;

        if (value == "Any")
            ddlResortText = 'Any Resort';
        else
            ddlResortText = 'Any Resort in ' + skiArea.name;

        var skiAreaResorts = [];
        for (var i = 0; i < this.details.resorts.length; i++)
            if (this.details.resorts[i].skiAreaId == skiArea.id)
                skiAreaResorts[skiAreaResorts.length] = this.details.resorts[i];

        $('#ddlResort').empty();
        skiSearch.bindArrayToSelect($('#ddlResort'), skiAreaResorts, { code: 'Any', name: ddlResortText }, resortId, "r");
        this.searchCriteria.addSkiArea(skiArea.id);
        skiSearch.bindCountryBasedOnResort(skiArea.id);
    },
    bindCountryChildResorts: function (value, resortId) {
        var country = this.findItemInArray(this.details.countries, value);
        var ddlResortText;
        if (value == "Any")
            ddlResortText = 'Any Resort';
        else
            ddlResortText = 'Any Resort in ' + country.name;

        var countryResorts = [];
        for (var i = 0; i < this.details.resorts.length; i++)
            if (this.details.resorts[i].countryCode == country.code)
                countryResorts[countryResorts.length] = this.details.resorts[i];

        $('#ddlResort').empty();
        skiSearch.bindArrayToSelect($('#ddlResort'), countryResorts, { code: 'Any', name: ddlResortText }, resortId, "r");
        this.searchCriteria.addCountry(country.code);
        skiSearch.bindCountryBasedOnResort(country.code);

    },

    changeSelectedResort: function (bindCountryOrSkiArea) {

        var selectedResort = $('#ddlResort option:selected');
        this.searchCriteria.clearResort();
        if (selectedResort.val() != 'Any') {
            var resort = this.findItemInArray(this.details.resorts, selectedResort.val());
            this.searchCriteria.addResort(resort.id);
            if (bindCountryOrSkiArea)
                skiSearch.toggleCountryOrSkiAreaBind(resort)
            skiSearch.toggleBackGroundColor($('#ddlCountry')[0]);
        }
        //this.fetchHolidayCount();
    },

    toggleCountryOrSkiAreaBind: function (resort) {
        if ($('#ddlCountry option:selected').val() == "Any") {
            var country = skiSearch.findItemInArray(skiSearch.details.countries, resort.countryCode);
            skiSearch.bindCountryBasedOnResort(resort.countryCode);
        }
    },
    changeAccommodationOnly: function () {
        var input = $('#chkAccommodationOnly');

        searchCriteria.setAccommodationOnly(input.attr('checked'));

        if (input.attr('checked'))
            $('#departFromContainer').fadeOut(500);
        else
            $('#departFromContainer').fadeIn(500);

        //fetchHolidayCount();
    },

    changeSelectedAirport: function () {
        var selectedAirport = $('#ddlDepartFrom option:selected');
        var selectedAirportsBox = $('#selectedAirports');

        selectedAirportsBox.empty();
        this.searchCriteria.clearDeparturePort();
        this.searchCriteria.clearRegions();
        this.searchCriteria.setAccommodationOnly(false);
        if (selectedAirport.val() != 'Any') {

            if (selectedAirport.val() == 'AccomOnly')
                this.searchCriteria.setAccommodationOnly(true);
            else {
                if (selectedAirport.parent().attr('label') != "Regions")
                    this.searchCriteria.addDeparturePort(selectedAirport.val());
                else
                    skiSearch.searchCriteria.addRegion(parseInt(selectedAirport.val()));
            }
        }

        //fetchHolidayCount();
    },
    changeOfferDate: function () {
        if ($('#cbxOfferDate').val() != '' && $('#cbxOfferDate').val() != 'Any') {
            var startDateTime;
            var endDateTime;
            endDateTime = startDateTime = new Date(parseInt($('#cbxOfferDate').val().split('/')[2]),
             parseInt($('#cbxOfferDate').val().split('/')[1]),
              parseInt($('#cbxOfferDate').val().split('/')[0]));

            this.searchCriteria.DateRanges = new Array();
            this.searchCriteria.DateRanges[this.searchCriteria.DateRanges.length] = { 'startDate': startDateTime, 'endDate': endDateTime };
        }
        else
            this.searchCriteria.DateRanges = new Array();
    },

    changeDateRange: function () {
        //we need to wait for slow-ass ie6 and below to load for a sec
        if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
            setTimeout("skiSearch.changeSingleDateRange($('#ddlMonthYear').val(), $('#ddlDay').val())", 1);
        }
        else
            skiSearch.changeSingleDateRange($('#ddlMonthYear').val(), $('#ddlDay').val());
    },
    changeSingleDateRange: function (monthValue, dayValue) {
        if (monthValue != "Any") {
            var startDateTime;
            var endDateTime;
            if (dayValue != "Any") {
                //start and enddate the same signalling  specific day search
                endDateTime = startDateTime = new Date(parseInt(monthValue.split('/')[1]), parseInt(monthValue.split('/')[0]), dayValue);
            }
            else {
                startDateTime = new Date(parseInt(monthValue.split('/')[1]), parseInt(monthValue.split('/')[0]), 1);
                endDateTime = new Date(parseInt(monthValue.split('/')[1]), parseInt(monthValue.split('/')[0]), startDateTime.getMonthDays(startDateTime.getMonth()));
            }
            this.searchCriteria.DateRanges = new Array();
            this.searchCriteria.DateRanges[this.searchCriteria.DateRanges.length] = { 'startDate': startDateTime, 'endDate': endDateTime };
            skiSearch.bindDay($('#ddlDay'), dayValue, startDateTime.getMonthDays(parseInt(monthValue.split('/')[0])), parseInt(monthValue.split('/')[0]), parseInt(monthValue.split('/')[1]));
        }
        else {
            this.searchCriteria.DateRanges = new Array();
        }
    },
    changeFlexibility: function () {
        this.searchCriteria.setFlexibility($('#ddlDateFlexibility').val());

        //fetchHolidayCount();
    },

    changeSelectedDuration: function () {
        if ($('#ddlDuration').val().toLowerCase() != "any")
            this.searchCriteria.setDuration($('#ddlDuration').val());
        else
            skiSearch.resetSearchCriteria('d');
        //fetchHolidayCount();
    },

    changeFeature: function (selected, value) {
        this.searchCriteria.toggleFeature(selected, value);
    },

    changeBoardBasis: function () {
        this.searchCriteria.clearBoardBasis();
        if ($('#ddlBoardBasis option:selected').val() != "Any")
            this.searchCriteria.toggleBoardBasis($('#ddlBoardBasis option:selected').val());
    },

    changePropertyType: function (propertyTypeCode) {
        this.searchCriteria.clearPropertyType();
        this.searchCriteria.togglePropertyType(propertyTypeCode);

        //fetchHolidayCount();
    },

    changePropertyType: function () {
        this.searchCriteria.clearPropertyType();
        if ($('#ddlAccom').val() != 'Any') {
            this.setPropertyTypeFromValue($('#ddlAccom').val());
        }
    },

    setPropertyTypeFromValue: function (accomVal) {
        for (var i = 0; i < accomVal.split(",").length; i++) {
            this.searchCriteria.togglePropertyType(accomVal.split(",")[i]);
        }
    },
    changeWholeChalet: function (wholeChalet) {
        this.searchCriteria.setWholeChalet(wholeChalet);

        //fetchHolidayCount();
    },
    changeChildCare: function (childCare) {
        this.searchCriteria.setChildCare(childCare);

        //fetchHolidayCount();
    },
    changeSlopes: function (nearSlopes) {
        this.searchCriteria.setSlopes(nearSlopes);

        //fetchHolidayCount();
    },
    changedSelectedPassengers: function () {
        this.searchCriteria.setPassengers(parseInt($('#ddlAdults').val()), parseInt($('#ddlChildren').val()));

        //fetchHolidayCount();
    },

    changeRating: function () {
        if ($('#ddlRating').val() != 'Any') {
            this.searchCriteria.setRating($('#ddlRating').val());
        }
    },
    showDateRange: function () {
        //We just want to show the other half of this date range
        $('#addDateRange').fadeOut(500, function () {
            var dateRangeControl = $('div.dateRangeControl:eq(0)');

            $('span.fromLabel, div.fromLabelClearer, div.dateRangeTo, div.arrow', dateRangeControl).fadeIn(500);
            $('#addAnotherDateRange').fadeIn(500);
            $('#dateFlexibilityContainer').fadeOut(500);

            //We need to change the fields that are set to be a single date, to be a range now
            $('select.anyYearFrom, select.anyDayFrom').attr('onchange', '').change(function () {
                this.changeDate('range', 0);
            });
        });
    },

    addAnotherDateRange: function () {
        var clonedDateRange = $('div.dateRangeControl:eq(0)').clone().css({ display: 'none', marginTop: '10px' });
        $('span.toLabel, div.toLabelCleaer, span.fromLabel, div.fromLabelClearer', clonedDateRange).remove();
        $('div.arrow', clonedDateRange).css({ marginTop: '0px', display: 'block' });
        $('a.removeDateRange', clonedDateRange).css({ display: 'block' });
        //We need to change the fields that are set to be a single date, to be a range now
        $('select.anyYearTo, select.anyDayTo, select.anyYearFrom, select.anyDayFrom', clonedDateRange).attr('onchange', '').change(function () {
            changeDate('range', $('div.dateRangeControl').length - 1);
        });
        clonedDateRange.insertBefore($('#dateRangeClearer')).fadeIn(500);
    },

    removeDateRange: function (input) {
        if ($('div.dateRangeControl').length > 1)
            $(input).parents('div.dateRangeControl').fadeOut(500, function () { $(this).remove(); });
        else {
            //We just want to do the reverse of showDateRange
            var dateRangeControl = $('div.dateRangeControl:eq(0)');
            $('#addAnotherDateRange').fadeOut(500);
            $('span.fromLabel, div.fromLabelClearer, div.dateRangeTo, div.arrow', dateRangeControl).fadeOut(500, function () {
                $('#addDateRange').fadeIn(500);
                $('#dateFlexibilityContainer').fadeIn(500);
            });
        }
    },

    fetchHolidayCount: function () {
        var myObject =
    {
        'id': 1,
        'method': 'SearchResultsCount',
        'params':
        {
            'criteria': skiSearch.searchCriteria
        }
    };

        $('#updatingHolidayCount').show();

        $.ajax({
            url: "/Services/JSON/HolidaySearch.ashx",
            data: JSON.stringify(myObject),
            contentType: 'application/json',
            type: 'POST',
            beforeSend: function (a) {
                $('#holidayCount').fadeOut(200, function () { $('#waitingForResponse').fadeIn(200); });
            },
            success: function (a) {
                var f = 0;

                $('#waitingForResponse, #holidayCount').stop();
                $('#waitingForResponse').fadeOut(200, function () {
                    $('#holidayCount').html('<span style="font-size: 2.0em; line-height: 1.3em;">' + addCommas(a.result.toString()) + '</span><br />Holidays Found').fadeIn(200);
                });
            },
            dataType: 'json'
        });
    },

    addCommas: function (nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    },

    toggleBackGroundColor: function (control) {
        if (control.options[control.selectedIndex].value != "Any" && control.options[control.selectedIndex].value != "0")
            control.style.backgroundColor = '#FFFFCC';
        else
            control.style.backgroundColor = '';
    },
    toggleAdultBackGroundColor: function (control) {
        if (control.options[control.selectedIndex].value != "Any" && control.options[control.selectedIndex].value != "2")
            control.style.backgroundColor = '#FFFFCC';
        else
            control.style.backgroundColor = '';
    },
    DoSearch: function () {
        var myObject =
    {
        'id': 1,
        'method': resultPageType == 1 ? 'PopulateSearchObjectFromRefineSearch' : 'PopulateSearchObjectFromDerivedSearch',
        'params':
        {
            'criteria': skiSearch.searchCriteria
        }
    };

        $.ajax({
            url: "/Services/JSON/HolidaySearch.ashx",
            data: JSON.stringify(myObject),
            contentType: 'application/json',
            type: 'POST',
            cache: false,
            success: function (a) {
                //postback if this is an embedded search                
                if (postBackFunction != null)
                    postBackFunction();
            },
            dataType: 'json'
        });
    }
};

// helper methods
function tryParseInt(string, defaultValue) {
    if (string == null || string == '' || isNaN(string)) {
        return defaultValue;
    }

    return parseInt(string);
}

