﻿/// <reference path="jquery-1.4.1.js" />
/// <reference path="jquery.jqURL.js" />
/// <reference path="jquery.selectboxes.js" />
/// <reference path="eaFormOpts.js" />
/// <reference path="ui.dropdownchecklist-min.js" />

/************************************************************************************************************************


************************************************************************************************************************/
if (agDet) {
    var propIframe = "http://powering2.expertagent.co.uk/customsearch.aspx?ShowSearchFirst=false&aid={" + agDet.agencyGuid + "}&";
    var dep = parseInt($.jqURL.get("dep"));
    if (isNaN(dep)) {
        dep = agDet.salesDepts[0];
    }

    $(document).ready(function () {
        LoadSearchPod();
        InitSearchPod();
        LoadIFrame();
    });


    function LoadSearchPod() {
        $(agDet.podDiv).load("ea/searchPodTemplate.htm", InitSearchPod);
    }

    function InitSearchPod() {
        $(agDet.podDiv + " select").each(function (index) {
            var opts = "opts_" + this.id;
            if (this.id.indexOf("price") != -1) {
                PopulatePriceDropDown(this);
                //SetupPriceDefaults(this);
            }
            else if (typeof (window[opts]) != "undefined") {
                $(this).addOption(window[opts], false);
                $(this).sortOptions();
            }
            if ($.jqURL.qs()) {
                $(this).selectOptions($.jqURL.get(GetVarFromId(this.id), true));
            } else {
                if (this.id === 'dd_dep') {
                    $(this).selectOptions(dep.toString(), true);
                } else {
                    if ($(this).containsOption("")) {
                        $(this).selectOptions("", true);
                    } else {
                        $(this)[0].selectedIndex = 0;
                    }
                }
            }
        });

        if ($.jqURL.qs() && $.jqURL.get("types") != null) {
            $(agDet.podDiv + " #dd_types option").each(function (i, opt) {
                if (i > 0 && $.jqURL.get("types").indexOf($(opt).val()) != -1) {
                    $(opt).attr("selected", "selected");
                }
            });

            var $allTypesOptions = $(agDet.podDiv + " #dd_types option");
            var allTypesSelected = true;
            $allTypesOptions.each(function (index) {
                if (index > 0) {
                    var selected = $(this).attr("selected");
                    if (!selected) allTypesSelected = false;
                }
            });
            var $firstTypesCheckbox = $allTypesOptions.filter(":first");
            $firstTypesCheckbox.removeAttr("selected");
            if (allTypesSelected) {
                $firstTypesCheckbox.attr("selected", "selected");
            }
        }


        var $selected_types = $(agDet.podDiv + " #dd_types :selected");
        var $types_dropdown = $(agDet.podDiv + " #dd_types");
        if ($selected_types.val() == '' || $selected_types.size() == 0) {
            $types_dropdown.selectOptions(/./, true);
            $types_dropdown.selectOptions("", false);
        }

        $types_dropdown.dropdownchecklist("destroy");
        $types_dropdown.dropdownchecklist(
                {
                    firstItemChecksAll: true,
                    textFormatFunction: function (selectOptions) {
                        var selectedOptions = selectOptions.filter(":selected");
                        var numSelected = selectedOptions.size();
                        var size = selectOptions.size();
                        switch (numSelected) {
                            case 0: return "Please Select..";
                            case 1: return selectedOptions.text();
                            case size: return "All Types";
                            default: return numSelected + " / " + (size - 1) + " Types";
                        }
                    }
                });

        if ($.jqURL.qs() && $.jqURL.get("districts") != null) {
            $(agDet.podDiv + " #dd_districts option").each(function (i, opt) {
                if (i > 0 && $.jqURL.get("districts").indexOf($(opt).val()) != -1) {
                    $(opt).attr("selected", "selected");
                }
            });

            var $allDistrictsOptions = $(agDet.podDiv + " #dd_districts option");
            var allDistrictsSelected = true;
            $allDistrictsOptions.each(function (index) {
                if (index > 0) {
                    var selected = $(this).attr("selected");
                    if (!selected) allDistrictsSelected = false;
                }
            });
            var $firstDistrictsCheckbox = $allDistrictsOptions.filter(":first");
            $firstDistrictsCheckbox.removeAttr("selected");
            if (allDistrictsSelected) {
                $firstDistrictsCheckbox.attr("selected", "selected");
            }
        }

        var $selected_districts = $(agDet.podDiv + " #dd_districts :selected");
        var $districts_dropdown = $(agDet.podDiv + " #dd_districts");
        if ($selected_districts.val() == '' || $selected_districts.size() == 0) {
            $districts_dropdown.selectOptions(/./, true);
            $districts_dropdown.selectOptions("", false);
        }

        $districts_dropdown.dropdownchecklist("destroy");
        $districts_dropdown.dropdownchecklist(
                {
                    firstItemChecksAll: true,
                    textFormatFunction: function (selectOptions) {
                        var selectedOptions = selectOptions.filter(":selected");
                        var numSelected = selectedOptions.size();
                        var size = selectOptions.size();
                        switch (numSelected) {
                            case 0: return "Please Select..";
                            case 1: return selectedOptions.text();
                            case size: return "All Areas";
                            default: return numSelected + " / " + (size - 1) + " Areas";
                        }
                    }
                });


        $(agDet.podDiv + " #dd_dep").change(function () {
            dep = $(this).val();
            PopulatePriceDropDowns();
        });

        if ($.jqURL.qs()) {
            $(agDet.podDiv + " :checkbox").each(function () {
                if ($.jqURL.get(GetVarFromId(this.id)) == "true") {
                    $(this).attr('checked', true);
                }
            });
        }
    }

    function SetupPriceSlider(isChangedDept) {
        var $sl_price = $(agDet.podDiv + " #sl_price");
        var sl_price_opts = window["opts_sl_price" + GetOptsSuffix()];
        var sl_minprice = sl_price_opts.min - sl_price_opts.step;
        var sl_maxprice = sl_price_opts.max + sl_price_opts.step;

        $(agDet.podDiv + " #lbl_pricerange").html(sl_price_opts.priceText);

        $sl_price.slider({
            range: true,
            slide: function (event, ui) {
                $(agDet.podDiv + " #lbl_minprice").html(((ui.values[0] != (sl_price_opts.min - sl_price_opts.step)) ? agDet.currencySymbol + ui.values[0] : 'No Min'));
                $(agDet.podDiv + " #lbl_maxprice").html(((ui.values[1] != (sl_price_opts.max + sl_price_opts.step)) ? agDet.currencySymbol + ui.values[1] : 'No Max'));
            }
        });

        if ($.jqURL.qs() && !isChangedDept) {
            var minpriceQs = parseInt($.jqURL.get("minprice"));
            if (!isNaN(minpriceQs)) {
                sl_minprice = minpriceQs;
            }
            var maxpriceQs = parseInt($.jqURL.get("maxprice"));
            if (!isNaN(maxpriceQs)) {
                sl_maxprice = maxpriceQs;
            }
        } else {
            sl_minprice = sl_price_opts.default_min;
            sl_maxprice = sl_price_opts.default_max;
        }


        $sl_price.slider("option", "step", sl_price_opts.step);
        $sl_price.slider("option", "min", sl_price_opts.min - sl_price_opts.step);
        $sl_price.slider("option", "max", sl_price_opts.max + sl_price_opts.step);
        $sl_price.slider("values", 0, sl_minprice);
        $sl_price.slider("values", 1, sl_maxprice);
        $(agDet.podDiv + " #lbl_minprice").html(((sl_minprice != (sl_price_opts.min - sl_price_opts.step)) ? agDet.currencySymbol + sl_minprice : 'No Min'));
        $(agDet.podDiv + " #lbl_maxprice").html(((sl_maxprice != (sl_price_opts.max + sl_price_opts.step)) ? agDet.currencySymbol + sl_maxprice : 'No Max'));
    }

    function PopulatePriceDropDowns() {
        $(agDet.podDiv + " select[id *= 'price']").each(function () {
            PopulatePriceDropDown(this, dep);
        });
    }

    function PopulatePriceDropDown(dropDown) {
        $(dropDown).removeOption(/./);
        var prices = window["opts_" + dropDown.id + GetOptsSuffix()];
        if (dropDown.id.indexOf("min") != -1) {
            $(agDet.podDiv + " #" + dropDown.id).addOption('', 'No Minimum', false);
        }
        for (var i in prices) {
            $(agDet.podDiv + " #" + dropDown.id).addOption(prices[i], FormatPrice(prices[i], agDet.currencySymbol), false);
        }
        if (dropDown.id.indexOf("max") != -1) {
            $(agDet.podDiv + " #" + dropDown.id).addOption('', 'No Maximum', false);
        }
        SetupPriceDefaults(dropDown);
    }

    function SetupPriceDefaults(dropDown) {
        var defaultVal = window["agDet"]["default_" + dropDown.id + GetOptsSuffix()].toString();
        $(dropDown).selectOptions(defaultVal, true);
    }

    function FormatPrice(price, currencySymbol) {
        price += '';
        var x = price.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        var formattedPrice = currencySymbol + x1 + x2 + ((IsLettingsDept()) ? agDet.lettingsSuffix : '');
        return $("<div />").html(formattedPrice).text();
    }

    function LoadIFrame() {
        var iframeSrc = propIframe + (($.jqURL.qs()) ? $.jqURL.qs() : "dep=" + dep);
        $(agDet.propIframeId).attr("src", iframeSrc);
    }

    function Search() {
        var qsParams = {};
        $(agDet.podDiv + " #dd_types option:first").removeAttr("selected");
        $(agDet.podDiv + " select").each(function () {
            qsParams[GetVarFromId(this.id)] = $(this).selectedValues();
        });

        $(agDet.podDiv + " input:checked").each(function () {
            qsParams[GetVarFromId(this.id)] = "true";
        });

        $(agDet.podDiv + " input[type=text]").each(function () {
            if ($(this).val().length > 0) {
                qsParams[GetVarFromId(this.id)] = $(this).val();
            }
        });


        var url = $.jqURL.set(qsParams, true);
        var qs = url.substr(url.indexOf("?"));
        if (url.indexOf(agDet.propPage) != -1) {
            $(agDet.propIframeId).attr("src", propIframe + qs.substr(1));
        } else {
            $.jqURL.loc(agDet.propPage + qs);
        }
    }

    function GetVarFromId(i) {
        return (i.substr(3));
    }

    function IsLettingsDept() {
        return ($.inArray(parseInt(dep), agDet.lettingsDepts) != -1);
    }

    function GetOptsSuffix() {
        return ((IsLettingsDept()) ? '_lettings' : '_sales');
    }
} else {
    alert("EA Option file not found. This is required for the search pod to function - please contact support.");
}

