﻿/// <reference name="MicrosoftAjax.js" />
/// <reference name="Telerik.Web.UI.Common.Core.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Common.jQuery.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Common.jQueryInclude.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Calendar.RadCalendarCommonScript.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Calendar.RadCalendarScript.js" assembly="Telerik.Web.UI" />
/// <reference name="Telerik.Web.UI.Calendar.RadDatePicker.js" assembly="Telerik.Web.UI" />
/// <reference name="IfYouSki.Engine.Resources.ControlTemplates.Frontend.tools.scrollable-1.1.2.min.js" assembly="IfYouSki.Engine" />
/// <reference name="IfYouSki.Engine.Resources.ControlTemplates.Frontend.jquery.tmpl.js" assembly="IfYouSki.Engine" />

/***************************************************************************
SearchForm Control
****************************************************************************/

Type.registerNamespace("IfYouSki.Engine.WebControls");

(function() {

    var $ = $telerik.$;
    var $I = IfYouSki.Engine.WebControls;


    $I.Months = function() { };
    $I.Months.prototype =
             {
                 jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6,
                 jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12
             }
    $I.Months.registerEnum("IfYouSki.Engine.WebControls.Months");


    $I.SearchForm = function(element) {
        //module level variables
        this._whenDayCombo;
        this._whenMonthCombo;
        this._popupButtonId;
        this._calendarPosition;
        this._calendarPopup;
        this._resortComboId;
        this._countryComboId;
        this._countryId;
        this._resortValuesId;
        this._budgetSliderId;
        this._tooltipId;
        this._toggleAdvancedSearchId;
        this._advancedSearchModeId;
        this._isSliding;
        this._budgetIsLoaded = false;
        this._formIsLoaded = false;

        //Calling the base class constructor  
        $I.SearchForm.initializeBase(this, [element]);
    }

    $I.SearchForm.prototype = {
        //Getter for formIsLoaded Property
        get_formIsLoaded: function() {
            return this._formIsLoaded;
        },
        //setter for formIsLoaded Property
        set_formIsLoaded: function(value) {
            this._formIsLoaded = value;
        },
        //Getter for budgetIsLoaded Property
        get_budgetIsLoaded: function() {
            return this._budgetIsLoaded;
        },
        //setter for budgetIsLoaded Property
        set_budgetIsLoaded: function(value) {
            this._budgetIsLoaded = value;
        },
        //Getter for isSliding Property
        get_isSliding: function() {
            return this._isSliding;
        },
        //setter for isSliding Property
        set_isSliding: function(value) {
            this._isSliding = value;
        },
        //Getter for budgetSliderId Property
        get_budgetSliderId: function() {
            return this._budgetSliderId;
        },
        //setter for budgetSliderId Property
        set_budgetSliderId: function(value) {
            this._budgetSliderId = value;
        },
        //Getter for tooltipId Property
        get_tooltipId: function() {
            return this._tooltipId;
        },
        //setter for tooltipId Property
        set_tooltipId: function(value) {
            this._tooltipId = value;
        },
        //Getter for toggleAdvancedSearchId Property
        get_toggleAdvancedSearchId: function() {
            return this._toggleAdvancedSearchId;
        },
        //setter for toggleAdvancedSearchId Property
        set_toggleAdvancedSearchId: function(value) {
            this._toggleAdvancedSearchId = value;
        },
        //Getter for advancedSearchModeId Property
        get_advancedSearchModeId: function() {
            return this._advancedSearchModeId;
        },
        //setter for advancedSearchModeId Property
        set_advancedSearchModeId: function(value) {
            this._advancedSearchModeId = value;
        },
        //Getter for whenDayCombo Property 
        get_whenDayCombo: function() {
            return this._whenDayCombo;
        },
        //setter for whenDayCombo Property
        set_whenDayCombo: function(value) {
            this._whenDayCombo = value;
        },

        //Getter for whenMonthCombo Property
        get_whenMonthCombo: function() {
            return this._whenMonthCombo;
        },
        //setter for whenMonthCombo Property
        set_whenMonthCombo: function(value) {
            this._whenMonthCombo = value;
        },

        //Getter for popupButtonId Property
        get_popupButtonId: function() {
            return this._popupButtonId;
        },
        //setter for popupButtonId Property
        set_popupButtonId: function(value) {
            this._popupButtonId = value;
        },

        //Getter for calendarPosition Property
        get_calendarPosition: function() {
            return this._calendarPosition;
        },
        //setter for calendarPosition Property
        set_calendarPosition: function(value) {
            this._calendarPosition = value;
        },

        //Getter for calendarPopup Property
        get_calendarPopup: function() {
            return this._calendarPopup;
        },
        //setter for calendarPopup Property
        set_calendarPopup: function(value) {
            this._calendarPopup = value;
        },
        //Getter for countryComboId Property
        get_countryComboId: function() {
            return this._countryComboId;
        },
        //setter for countryComboId Property
        set_countryComboId: function(value) {
            this._countryComboId = value;
        },
        //Getter for resortComboId Property
        get_resortComboId: function() {
            return this._resortComboId;
        },
        //setter for resortComboId Property
        set_resortComboId: function(value) {
            this._resortComboId = value;
        },
        //Getter for country Id Property
        get_countryId: function() {
            return this._countryId;
        },
        //setter for country Id Property
        set_countryId: function(value) {
            this._countryId = value;
        },
        //Getter for resort hidden values ID Property
        get_resortValuesId: function() {
            return this._resortValuesId;
        },
        //setter for resort hidden values ID Property
        set_resortValuesId: function(value) {
            this._resortValuesId = value;
        },

        popUpCalendar: function(evt, args) {
            var searchForm = args.sender;

            var popup = $("#" + searchForm.get_calendarPopup());
            var buttonPosition = $(this).position();

            //we need to show before calculatng
            popup.fadeIn('fast');

            var navigation = popup.find(".navigation");

            //find the calendars and count them
            var calendars = popup.find(".items div");
            var firstCalendar = $(":first", calendars);
            var count = (calendars.size() > 3 ? 3 : calendars.size());

            //hide the navigation if there are no calendars
            if (count <= 2)
                navigation.hide();
            else
                navigation.show();

            //get the calculated height of a single calendar
            var width = firstCalendar.outerWidth() * count;
            var height = firstCalendar.outerHeight(true) + (count <= 2 ? 0 : navigation.outerHeight(true));

            //change the position of the picker
            var x = buttonPosition.left;
            if (searchForm.get_calendarPosition() == "BottomLeft")
                x = x - width;

            //position the container
            popup.css({
                position: "absolute",
                marginLeft: 0,
                marginTop: 0,
                top: buttonPosition.top,
                left: x,
                width: width,
                height: height,
                overflow: "hidden"
            });

            var scrollable = popup.find(".scrollable");
            scrollable.css({
                width: width,
                height: firstCalendar.outerHeight(true)
            })
        .scrollable({
            size: 3
        });


            //stop clicks on the popup from bubbling up
            $(popup).click(function(clickEvt) {
                stopPropagation(clickEvt);
            });

            //click to cancel the popup
            $telerik.cancelRawEvent(evt);
            $('html').bind('click.' + searchForm.get_calendarPopup(), function() {
                searchForm.hidePopUp();
                return false;
            });
        },

        hidePopUp: function() {
            var popup = $("#" + this.get_calendarPopup());
            popup.css("");
            popup.fadeOut('fast');

            //remove the click block
            $('html').unbind('click.' + this.get_calendarPopup())
        },

        _calendar_dateSelecting: function(sender, eventArgs) {
            //get the popup
            var popup = $("#" + this.get_calendarPopup());

            //close the popup    
            this.hidePopUp();

            //cancel the click
            eventArgs.set_cancel(true);

            //get the date and format it
            var date = eventArgs.get_renderDay().get_date();
            var dfi = sender.DateTimeFormatInfo;
            var monthYear = dfi.FormatDate(date, "MMM yy");
            var day = date[2];

            //set the when day combo
            var comboItem = $find(this.get_whenDayCombo()).findItemByValue(day);
            if (comboItem != null)
                comboItem.select();

            //set the when day combo
            comboItem = $find(this.get_whenMonthCombo()).findItemByText(monthYear);
            if (comboItem != null)
                comboItem.select();
        },
        _countryCombo_OnClientSelectedIndexChanged: function(combo, eventArgs) {
            if (!this.get_formIsLoaded()) {
                var resortCombo = $find(this.get_resortComboId());
                if (resortCombo != null) {
                    this._resortCombo_OnClientDropDownOpening(resortCombo);
                    this._generateComboText(resortCombo);
                }
            }
        },
        _resortCombo_OnClientDropDownOpening: function(combo, eventArgs) {
            var countryCombo = $find(this.get_countryComboId());

            //hook up Any click
            var thisControl = this;
            $(".rcbHeader input:checkbox", combo.get_dropDownElement()).click(function() {
                search_toggleChecks(this);
                thisControl.getSelectedValues(combo);
            });

            //try the select if the combo is on the page
            if (countryCombo) {
                var countryId = countryCombo.get_value();

                var items = combo.get_items();
                for (var i = 0, ii = items.get_count(); i < ii; i++) {
                    var thisItem = items.getItem(i);
                    //only show if the country id matches or if the country is set to any and don't hide the "Any" item                    
                    if (thisItem.get_attributes().getAttribute("CountryId") == countryId || countryId == "Any" || thisItem.get_value() == "Any") {
                        thisItem.show();
                    }
                    else {
                        thisItem.hide();
                        $("input:checked", thisItem.get_element()).removeAttr("checked");
                    }
                }
            }
            this.getSelectedValues(combo);
        },
        _monthCombo_OnClientSelectedIndexChanging: function(combo, eventArgs) {
            var dayCombo = $find(this.get_whenDayCombo());
            if (dayCombo) {
                if (dayCombo.get_items().get_count() > 0) {

                    //convert the string into useful numbers
                    var monthYear = eventArgs.get_item().get_text();
                    var monthName = monthYear.substring(0, 3);
                    var shortYear = parseInt("20" + monthYear.substring(4));
                    var month = eval("IfYouSki.Engine.WebControls.Months." + monthName.toLowerCase());

                    //get the last day of the month                                        
                    var dd = new Date(shortYear, month, 0);
                    var daysInMonth = dd.getDate();

                    var items = dayCombo.get_items();
                    for (i = 0; i < items.get_count(); i++) {

                        //only show if that day if it exists in that month
                        if (items.getItem(i).get_value() <= daysInMonth || items.getItem(i).get_value() == "Any")
                            items.getItem(i).show();
                        else
                            items.getItem(i).hide();
                    }

                    //if the day selected is out of range then select the last valid day
                    if (dayCombo.get_value() > daysInMonth) {
                        dayCombo.findItemByValue(daysInMonth).select();
                    }

                }
            }
        },
        _resortCombo_OnItemRequesting: function(combo, eventArgs) {
            var context = eventArgs.get_context();
            context["CountryId"] = this.get_countryId();
        },
        _resortCombo_OnClientDropDownClosing: function(combo, eventArgs) {
            this._generateComboText(combo);
        },
        _resortCombo_OnItemRequested: function(combo, eventArgs) {
            var hiddenValues = $("#" + this.get_resortValuesId());

            if (hiddenValues.val().length > 0) {
                var values = hiddenValues.val().split(',');
                for (i = 0; i < values.length; i++) {
                    var item = combo.findItemByValue(values[i]);
                    if (item != null)
                        $(":checkbox", item.get_element()).attr("checked", "checked");
                }
            }

            this._generateComboText(combo, hiddenValues);

            checkboxCombos_SetMouseout(combo, eventArgs);

        },
        _resortCombo_OnItemDataBound: function(combo, eventArgs) {
            var thisControl = this;
            var item = eventArgs.get_item();
            var dataItem = eventArgs.get_dataItem();

            //bind template, and block clicks from closing dropdown
            $(item.get_element())
                .html("")
                .append("#check-template", dataItem)
                .click(function(clickEvt) {
                    stopPropagation(clickEvt);
                })
                .find("input").click(function() {
                    //get the hidden values input
                    var hiddenValues = $("#" + thisControl.get_resortValuesId());
                    var checkbox = $(this);
                    if (checkbox.is(":checked"))
                        hiddenValues.val(hiddenValues.val() + checkbox.val() + ",");
                    else
                        hiddenValues.val(thisControl.removeListValue(hiddenValues.val(), checkbox.val()));
                });
        },
        removeListValue: function(list, value, separator) {
            separator = separator || ",";
            var values = list.split(",");
            for (var i = 0; i < values.length; i++) {
                if (values[i] == value) {
                    values.splice(i, 1);
                    return values.join(",");
                }
            }
            return list;
        },
        getSelectedValues: function(combo) {
            var items = combo.get_items();
            var resortList = "";
            for (i = 0; i < items.get_count(); i++) {
                var thisItem = items.getItem(i);
                if (thisItem.get_visible() && $("input:checked", thisItem.get_element()).length == 1) {
                    resortList += thisItem.get_value() + ",";
                }
            }
            $("#" + this.get_resortValuesId()).val(resortList);
        },
        _budget_OnClientValueChanging: function(sender, args) {
            if (!this.get_isSliding()) return;

            var tooltip = $find(this.get_tooltipId());
            resetBudgetToolTip(tooltip);

            var toolTip = args.get_newValue();
            if (toolTip == sender.get_maximumValue())
                toolTip = "greater than &pound;" + toolTip;
            else if (toolTip == sender.get_minimumValue())
                toolTip = "less than &pound;" + toolTip;
            else
                toolTip = "&pound;" + toolTip;

            tooltip.set_text(toolTip);
        },
        _budget_OnClientSlideStart: function(sender, args) {
            this.set_isSliding(true);

            var tooltip = $find(this.get_tooltipId());
            showBudgetToolTip(tooltip, sender);
        },

        _budget_OnClientSlideEnd: function(sender, args) {
            this.set_isSliding(false); ;

            var tooltip = $find(this.get_tooltipId());
            tooltip.hide();
        },

        toggleAdvancedSearch: function() {
            var advancedSearch = $('#' + this.get_id() + ' .advanced-search');

            var moreLink = $("#" + this.get_toggleAdvancedSearchId());
            var advancedSearchExpanded = $("#" + this.get_advancedSearchModeId());
            var expanded = (advancedSearchExpanded.val() == "true");

            if (!expanded) {
                advancedSearch.removeClass("hidden");
                moreLink.addClass("less");
                this.budgetLoad();

                moreLink.html("Less search options");
                advancedSearchExpanded.val(true);
            } else {
                moreLink.removeClass("less");
                advancedSearch.addClass("hidden");
                moreLink.html("More search options");
                advancedSearchExpanded.val(false);
            }

        },
        budgetLoad: function() {
            if (this.get_budgetIsLoaded()) return;

            var slider = $find(this.get_budgetSliderId());
            var items = slider.get_items();

            for (var i = 0, ii = items.length; i < ii; i++) {
                var prepend = "&pound;";
                if (i == 0)
                    prepend = "&lt;" + prepend
                if (i == items.length - 1)
                    prepend = "&gt;" + prepend

                var item = $("span", items[i].get_element());
                if (item.length > 0)
                    item.html(prepend + item.html());
            }
            this.set_budgetIsLoaded(true);
        },
        _generateComboText: function(combo, hiddenValues) {
            if (hiddenValues == null)
                hiddenValues = $("#" + this.get_resortValuesId());
            if (hiddenValues.val().length == 0)
                combo.set_text("Any");
            else {
                var checkAll = $(".rcbHeader input:checkbox", combo.get_dropDownElement());
                var allSelected = (hiddenValues.val().split(',').length - 1 == combo.get_items().get_count());
                if (allSelected)
                    checkAll.attr("checked", "checked");
                checkAll.siblings("label[for=" + checkAll.attr("id") + "]").html(allSelected ? "Deselect All" : "Select All");
                combo.set_text("Resorts selected");
            }
        }
        ,

        initialize: function() {
            $I.SearchForm.callBaseMethod(this, 'initialize');

            this.set_isSliding(false);

            //add the popup click event
            var thisControl = this;
            var _popupClick = Function.createCallback(this.popUpCalendar, { sender: this });
            $addHandler($get(this._popupButtonId), 'click', _popupClick);

            //find all the calendars and set them to the calendar click event
            $("#" + thisControl.get_calendarPopup() + " table.RadCalendar").each(function() {
                var element = $find(this.id);
                if (element && Telerik.Web.UI.RadCalendar && element instanceof Telerik.Web.UI.RadCalendar) {
                    // it is a calendar so add an anonymous function to encapsulate with this object
                    element.add_dateSelecting(function(sender, eventArgs) {
                        thisControl._calendar_dateSelecting(sender, eventArgs);
                    });
                }
            });

            //set up the selected index
            var countryCombo = $find(this.get_countryComboId());
            if (countryCombo) {
                // build combo on server
                if (countryCombo.get_webServiceSettings().get_path())
                    countryCombo.requestItems("Any", false);

                countryCombo.add_selectedIndexChanged(function(combo, eventArgs) {
                    thisControl._countryCombo_OnClientSelectedIndexChanged(combo, eventArgs);
                });
            }

            //set up the drop down handler
            var resortCombo = $find(this.get_resortComboId());
            if (resortCombo) {
                resortCombo.add_dropDownOpening(function(combo, eventArgs) {
                    thisControl._resortCombo_OnClientDropDownOpening(combo, eventArgs);
                });
                resortCombo.add_itemsRequesting(function(combo, eventArgs) {
                    thisControl._resortCombo_OnItemRequesting(combo, eventArgs);
                });

                resortCombo.add_itemsRequested(function(combo, eventArgs) {
                    thisControl._resortCombo_OnItemRequested(combo, eventArgs);
                });

                resortCombo.add_itemDataBound(function(combo, eventArgs) {
                    thisControl._resortCombo_OnItemDataBound(combo, eventArgs);
                });

                resortCombo.add_itemDataBound(function(combo, eventArgs) {
                    thisControl._resortCombo_OnItemDataBound(combo, eventArgs);
                });

                resortCombo.add_dropDownClosing(function(combo, eventArgs) {
                    thisControl._resortCombo_OnClientDropDownClosing(combo, eventArgs);
                });

                // build combo on server
                if (resortCombo.get_webServiceSettings().get_path())
                    resortCombo.requestItems("Any", false);
            }

            //set up the month combo change
            var monthCombo = $find(this.get_whenMonthCombo());
            monthCombo.add_selectedIndexChanging(function(sender, eventArgs) {
                thisControl._monthCombo_OnClientSelectedIndexChanging(sender, eventArgs);
            });

            //set up the budget slider
            var budgetSlider = $find(this.get_budgetSliderId());
            if (budgetSlider) {
                budgetSlider.add_slideEnd(function(slider, eventArgs) {
                    thisControl._budget_OnClientSlideEnd(slider, eventArgs);
                });
                budgetSlider.add_slideStart(function(slider, eventArgs) {
                    thisControl._budget_OnClientSlideStart(slider, eventArgs);
                });
                budgetSlider.add_valueChanging(function(slider, eventArgs) {
                    thisControl._budget_OnClientValueChanging(slider, eventArgs);
                });
            }

            //hook up the advanced search
            var advancedSearchExpanded = $("#" + this.get_advancedSearchModeId());
            if (advancedSearchExpanded.size() != 0 && budgetSlider) {

                var moreLink = $("#" + this.get_toggleAdvancedSearchId());
                moreLink.click(function() {
                    thisControl.toggleAdvancedSearch();
                });

                var expanded = (advancedSearchExpanded.val() == "true");
                if (expanded) {
                    advancedSearchExpanded.val(false);
                    thisControl.toggleAdvancedSearch();
                }
            }

            //control to indicate all has loaded
            thisControl.set_formIsLoaded(true);
        },
        dispose: function() {

            //clear event handlers
            $clearHandlers($get(this._popupButtonId));

            //Add custom dispose actions here
            $I.SearchForm.callBaseMethod(this, 'dispose');
        }
    }

    $I.SearchForm.registerClass('IfYouSki.Engine.WebControls.SearchForm', Sys.UI.Control);

})();

/***************************************************************************
Other functions
****************************************************************************/

function stopPropagation(e) {
    e = e || event; /* get IE event ( not passed ) */
    e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
}

(function($) {
    $(document).ready(function() {
        //move the calendar
        var popup = $("div.popup-calendar");
        $(document.body).append(popup);
    });
})($telerik.$);


/***************************************************************************
Combo box event handlers
***************************************************************************/
function searchCombos_ItemsRequested(combo, eventArgs) {
    if (combo.get_items().get_count() > 0) {
        var selectedValue = combo.get_value();
        var selectedText = combo.get_text();

        //pre-select the first item or the item whos value was already set
        var item = combo.findItemByValue(selectedValue);
        if (item != null) {
            item.select();
            combo.set_text(item.get_text());
        } else {
            item = combo.findItemByText(selectedText);
            combo.set_text(selectedText);
            item.select();
        }
    }
}

function searchCombos_ItemsRequestFailed(combo, eventArgs) {
    if (console == typeof (undefined)) {
        console.info(eventArgs.get_errorMessage());
    }
    alert("There was a problem loading the search form options, please try again later");
    eventArgs.set_cancel(true);
}

function searchCombos_OnItemDataBound(sender, eventArgs) {
    var item = eventArgs.get_item();
    var dataItem = eventArgs.get_dataItem();
    var countryId = dataItem.CountryId;
    item.get_attributes().setAttribute("CountryId", countryId);
}

function checkboxCombos_SetMouseout(sender, eventArgs) {
    (function($) {
        $(sender.get_dropDownElement()).bind("mouseleave", function() {
            sender.hideDropDown();
        });
    })($telerik.$);
}

function checkboxCombos_OnLoad(sender, eventArgs) {
    (function($) {
        var items = sender.get_items();
        for (var i = 0, ii = items.get_count(); i < ii; i++) {
            var item = items.getItem(i);
            $(item.get_element()).click(function(clkevt) {
                stopPropagation(clkevt);
            });
        }

        var selectedCount = $(".rcbList input:checked", sender.get_dropDownElement()).length;
        if (selectedCount == 0 || allSelected)
            sender.set_text("Any");

        else {
            var checkAll = $(".rcbHeader input:checkbox", sender.get_dropDownElement());
            var allSelected = (selectedCount == sender.get_items().get_count());
            if (allSelected)
                checkAll.attr("checked", "checked");
            checkAll.siblings("label[for=" + checkAll.attr("id") + "]").html(allSelected ? "Deselect All" : "Select All");
            sender.set_text("Multiple selected");
        }

        checkboxCombos_SetMouseout(sender, eventArgs);

    })($telerik.$);
}

function checkboxCombos_Closing(sender, eventArgs) {
    (function($) {
        var selectedCount = $(".rcbList input:checked", sender.get_dropDownElement()).length;
        if (selectedCount == 0 || allSelected)
            sender.set_text("Any");
        else {
            var allSelected = (selectedCount == sender.get_items().get_count());
            if (allSelected)
                $(".rcbHeader input:checkbox", sender.get_dropDownElement()).attr("checked", "checked");
            sender.set_text("Multiple selected");
        }
    })($telerik.$);
}

function search_toggleChecks(check) {
    (function($) {
        var checkAll = $(check);
        var isChecked = checkAll.is(":checked");
        var checboxes = checkAll.closest("div.RadComboBoxDropDown").find(".rcbList input:checkbox").each(function() {
            if (isChecked)
                $(this).attr("checked", "checked");
            else
                $(this).removeAttr("checked");
        });
        checkAll.siblings("label[for=" + checkAll.attr("id") + "]").html(isChecked ? "Deselect All" : "Select All");

    })($telerik.$);
}

function showBudgetToolTip(tooltip, slider) {
    var activeHandle = slider.get_activeHandle();
    if (!activeHandle) return;

    tooltip.set_targetControl(activeHandle);
    resetBudgetToolTip(tooltip);
}

function resetBudgetToolTip(tooltip) {
    if (!tooltip.isVisible())
        tooltip.show();
    else
        tooltip.updateLocation();
}


if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();