﻿/// <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 () {
        InitNf();
        InitSearchPod();
        LoadIFrame();
    });

    $(window).load(function () {
        if ($.jqURL.qs() && $.jqURL.get("areas") != null) {
            $(agDet.podDiv + " area[coords]").each(function (i) {
                var areaId = this.id.substr(8);
                if ($.jqURL.get("areas").indexOf(areaId) != -1) {
                    $(this).click();
                }
            });
        }
    });

    function InitNf() {
        //set the starting bigestHeight variable
        var biggestHeight = 0;
        //check each of them
        $('.equal_height').each(function () {
            //if the height of the current element is
            //bigger then the current biggestHeight value
            if ($(this).height() > biggestHeight) {
                //update the biggestHeight with the
                //height of the current elements
                biggestHeight = $(this).height();
            }
        });
        //when checking for biggestHeight is done set that
        //height to all the elements
        $('.equal_height').height(biggestHeight);

        $.fn.maphilight.defaults = {
            fill: true,
            fillColor: '51544c',
            fillOpacity: 0.6,
            stroke: false,
            strokeColor: 'FFA500',
            strokeOpacity: 1,
            strokeWidth: 1,
            fade: false,
            alwaysOn: false,
            neverOn: false,
            groupBy: false
        };
        $('#nfMap').maphilight();

        $('area').click(mapAreaClick);

        $(".trigger").click(function () {
            $(".panel").toggle("fast");
            $(this).toggleClass("active");
            return false;
        });
    }

    function mapAreaClick(e) {
        e.preventDefault();
        var areaId = this.id.toString().substr(8);
        var data = $(this).data('maphilight') || {};
        data.alwaysOn = !data.alwaysOn;
        selectedMapAreas[areaId] = data.alwaysOn;
        $(this).data('maphilight', data).trigger('alwaysOn.maphilight');
    }


    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 {
                $(this).selectOptions("", true);
            }
        });

        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 $firstCheckbox = $allTypesOptions.filter(":first");
            $firstCheckbox.removeAttr("selected");
            if (allTypesSelected) {
                $firstCheckbox.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(
                {
                    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";
                        }
                    }
                });

        //SetupPriceSlider(false);

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

        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');
        }
        return currencySymbol + x1 + x2 + ((IsLettingsDept()) ? agDet.lettingsSuffix : '');
    }

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

    function Search() {
        var qsParams = {};


//        var opts_sl = window["opts_sl_price" + GetOptsSuffix()];
//        $(agDet.podDiv + " #sl_price").each(function () {
//            var sl_min_price = $(this).slider("values", 0);
//            var sl_max_price = $(this).slider("values", 1);
//            if (sl_min_price >= opts_sl.min) {
//                qsParams.minprice = sl_min_price;
//            }
//            if (sl_max_price <= opts_sl.max) {
//                qsParams.maxprice = sl_max_price;
//            }
//        });
        var selectedAreas = '';
        for (var i in selectedMapAreas) {
            if (selectedMapAreas[i]) {
                selectedAreas += (i + ',');
            }
        }
        qsParams.areas = selectedAreas.substr(0, selectedAreas.length - 1);

        $(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.");
}

