﻿Type.registerNamespace('widgets.searchengine');

widgets.searchengine.simpleSearchUrl = "/Search/Simple";

widgets.searchengine.advancedSearchUrl = "/Search/Advanced";

widgets.searchengine.originalHtml = null;

widgets.searchengine.showEffect = {
    effect: "slide",
    options: { direction: "down" },
    speed: 250
};

widgets.searchengine.hideEffect = {
    effect: "slide",
    options: { direction: "up" },
    speed: 250
};

widgets.searchengine.getSearchCount = function(type, zoneSelector) {
    if (widgets.searchengine.originalHtml == null)
        widgets.searchengine.originalHtml = $("#hasbeenfound").html();
    var realEstateTypeSelector = document.getElementById(type + "RealEstateTypes");
    var locationIdSelector = document.getElementById(type + "Locations");
    isForSale = (type == "Sale");
    realEstateType = realEstateTypeSelector.options[realEstateTypeSelector.selectedIndex].value;
    locationId = locationIdSelector.options[locationIdSelector.selectedIndex].value;
    if (realEstateType == "") {
        realEstateType = -1;
    }
    if (locationId == "") {
        locationId = -1;
    }
    var refillZones = false;
    if (zoneSelector && zoneSelector.selectedIndex > 0)
        zone = zoneSelector.options[zoneSelector.selectedIndex].value || zoneSelector.options[zoneSelector.selectedIndex].text;
    else {
        refillZones = true;
        zoneSelector = document.getElementById(type + "LocationZone");
        zone = "";
    }
    if (realEstateType > 0 || locationId > 0 || zone != "") {
        if ($('#hasbeenfound').is(':visible'))
            $("#hasbeenfound").hide(
            widgets.searchengine.hideEffect.effect,
            widgets.searchengine.hideEffect.options,
            widgets.searchengine.showEffect.speed);
        common.toggleLoader("show");
        var proxy = new ajax.poldo.it.AjaxRealEstateService();
        proxy.GetSearchCount(locationId, realEstateType, zone, isForSale, !isForSale,
        function(successResult) {
            var proxy = new ajax.poldo.it.AjaxResourceService();
            proxy.GetResourceString("Widgets.SearchEngine, HasBeenFound", "~/", [successResult.Count], function(result) {
                $("#hasbeenfound").html(result);
                $("#hasbeenfound").show(
                widgets.searchengine.showEffect.effect,
                widgets.searchengine.showEffect.options,
                widgets.searchengine.showEffect.speed);
            }, common.showError);
            if (refillZones) widgets.searchengine.fillZones(zoneSelector, successResult.Zones);
            common.toggleLoader("hide");
        }, common.showError);
    } else {
        widgets.searchengine.resetPayoff();
    }
};


widgets.searchengine.searchTerm = function(type) {
    var typeStr = type;
    if (!(typeStr.lastIndexOf(".") >= 0))
        typeStr = typeStr + ".";
    typeStr = typeStr.replace(/\./g, "\\.");
    $("#" + typeStr + "LocationName").search();
}

widgets.searchengine.autocompleteResult = function(data, pos, total, term) { return data.Name; }

widgets.searchengine.setAutoCompleteLocation = function(type, activate, callback) {
    var typeStr = type;
    if (!(typeStr.lastIndexOf(".") >= 0))
        typeStr = typeStr + ".";
    typeStr = typeStr.replace(/\./g, "\\.");
    if (activate) {
        //var locationName = $("#LocationID").val();        
        var path = "/Services/AjaxRealEstateService.svc/GetAutocompleteLocations";

        $("#" + typeStr + "LocationName").autocomplete(path, {
            parse: function(data) {
                var obj = eval(data.d);
                var parsed = [];
                for (var i = 0; i < obj.length; i++) {
                    var row = obj[i];
                    if (row) {
                        parsed[parsed.length] = {
                            data: row,
                            value: row.Name,
                            result: widgets.searchengine.autocompleteResult(row, row.Name)
                        };
                    }
                }
                return parsed;
            },
            dataType: "json",
            matchSubset: true,
            cacheLength: 10,
            autoFill: true,
            minChars: 3,
            mustMatch: true,
            width: 250,
            max: 10,
            formatItem: function(data, pos, total, term) { return data.Name + " (" + data.ProvinceName + ")"; },
            formatResult: widgets.searchengine.autocompleteResult
        });
        $("#" + typeStr + "LocationName").result(function(event, data, formatted) {
            if (data != null) {
                if (data.IsProvince) {
                    $("#" + typeStr + "IncludeSubLocations").attr("disabled", "");
                } else {
                    $("#" + typeStr + "IncludeSubLocations").attr("checked", "");
                    $("#" + typeStr + "IncludeSubLocations").attr("disabled", "true");
                }
                $("#" + typeStr + "LocationID").val(data.LocationID);
                widgets.searchengine.refreshZones2(type);
                widgets.searchengine.checkZones(type);
            } else {
                //alert("No Match");
            }
        });
        
        $("#" + typeStr + "LocationName").attr("disabled", false);
        /*
         var proxy = new ajax.poldo.it.AjaxRealEstateService();
       
        proxy.GetLocations("", 10,
        function(successResult) {
            var res = eval(successResult);
            $("#" + typeStr + "LocationName").autocomplete(
        res, {
            matchSubset: true,
            cacheLength: 10,
            autoFill: true,
            minChars: 0,
            mustMatch: true,
            width: 250,
            formatItem: function(data, pos, total, term) { return data.Name + " (" + data.ProvinceName + ")"; },
            formatResult: function(data, pos, total, term) { return data.Name }
        }
        );
            $("#" + typeStr + "LocationName").result(function(event, data, formatted) {
                if (data != null) {
                    if (data.IsProvince) {
                        $("#" + typeStr + "IncludeSubLocations").attr("disabled", "");
                    } else {
                        $("#" + typeStr + "IncludeSubLocations").attr("checked", "");
                        $("#" + typeStr + "IncludeSubLocations").attr("disabled", "true");
                    }
                    $("#" + typeStr + "LocationID").val(data.LocationID);
                    widgets.searchengine.refreshZones2(type);
                    widgets.searchengine.checkZones(type);
                } else {
                    //alert("No Match");
                }
            });
            if (callback != null && $.isFunction(callback)) {
                callback();
            }
            if ($("#" + typeStr + "LocationName").attr("disabled"))
                $("#" + typeStr + "LocationName").attr("disabled", false);
        }, common.showError);*/
        
    } else {
        $("#" + typeStr + "LocationID").unautocomplete();
    }
}

widgets.searchengine.fillZones = function(selector, elements) {
    var nullOption = selector.options[0];
    selector.options.length = 0;
    selector.options.add(nullOption);
    $(elements).each(function(index, elem) {
        selector.options.add(new Option(elem));
    });
};

$.fn.outerHTML = function() {
    var doc = this[0] ? this[0].ownerDocument : document;
    return $('<div>', doc).append(this.eq(0).clone()).html();
};


widgets.searchengine.checkZones = function(type) {
    var typeStr = type;
    if (!(typeStr.lastIndexOf(".") >= 0))
        typeStr = typeStr + ".";
    typeStr = typeStr.replace(/\./g, "\\.");
    if ($("#" + typeStr + "IncludeSubLocations").attr("checked") != "") {
        $("#" + typeStr + "LocationZone").attr("disabled", "true");
    }
    else
        $("#" + typeStr + "LocationZone").attr("disabled", "");
}

widgets.searchengine.refreshZones2 = function(type) {
    var typeStr = type;
    if (!(typeStr.lastIndexOf(".") >= 0))
        typeStr = typeStr + ".";
    typeStr = typeStr.replace(/\./g, "\\.");
    var locationID = $("#" + typeStr + "LocationID").val();

    var proxy = new ajax.poldo.it.AjaxRealEstateService();
    proxy.GetLocationZones(locationID,
			function(successResult) {
			    var lastSelected = $("#" + typeStr + "LocationZone").val();
			    //$("#" + type + "LocationZone option").remove();
			    var options = "";
			    // "j" is the json object that was output by your PHP script
			    // it is the array of key-value pairs to turn
			    // into option value/labels...
			    var res = eval(successResult);
			    for (var i = 0; i < res.length; i++) {
			        options += "<option value=\"" + res[i].Name + "\">" + res[i].Name + "</option>";
			    }
			    options = $("#" + typeStr + "LocationZone option:first").outerHTML() + options;
			    // stick these new options in the existing select menu
			    $("#" + typeStr + "LocationZone").html(options);
			    $("#" + typeStr + "LocationZone option").each(function(i) {
			        var value = $(this).attr("value");
			        if (lastSelected.toLowerCase() == value.toLowerCase()) {
			            $(this).attr("selected", true);
			            return false;
			        } else return true;
			    });
			}, common.showError);
    //activateAutoComplete();
}


widgets.searchengine.toggleAdvanced = function(type) {
    $("#advancedSearch" + type).toggle("blind", {}, 500, function() {
        if ($("#advancedSearch" + type + ":visible").length > 0) {
            $("#" + type + "Form").attr("action", widgets.searchengine.advancedSearchUrl);
        }
        else {
            $("#" + type + "Form").attr("action", widgets.searchengine.simpleSearchUrl);
        }
    });
    $("#SimpleCommand" + type).toggle();
    $("#AdvancedCommand" + type).toggle();
    return false;
}

widgets.searchengine.setFromTo = function(type, control) {
    type = type.replace(/\./g, "\\.");
    if (control == null) {
        var from = parseInt($("select#" + type + "From").val());
        var to = parseInt($("select#" + type + "To").val());

        if (from > 0 && (to > 0 && to <= from)) {
            $("select#" + type + "To option").each(function(i, elem) {
                if (elem.value > from) {
                    $(elem).attr("selected", "selected");
                    return false;
                }
            });
        }
    } else {
        //$("select#" + type + "From option").remove();
        //$("select#" + type + "To option").remove();
        var contractType = $(control).val();
        if (contractType == "SALE") {
            fromSteps = widgets.searchengine.saleFromSteps;
            toSteps = widgets.searchengine.saleToSteps;
            $("#" + type + "SaleThousand").show();
        } else if (contractType == "RENT") {
            fromSteps = widgets.searchengine.rentFromSteps;
            toSteps = widgets.searchengine.rentToSteps;
            $("#" + type + "SaleThousand").hide();
        }
        var optionsFrom = "";
        var optionsTo = "";
        $.each(fromSteps, function() {
            optionsFrom += "<option value=" + $(this)[1] + ">" + $(this)[0] + "</option>";
        });
        $.each(toSteps, function() {
            optionsTo += "<option value=" + $(this)[1] + ">" + $(this)[0] + "</option>";
        });
        $("select#" + type + "From").html(optionsFrom);
        $("select#" + type + "To").html(optionsTo);
        $("select#" + type + "From option:first").attr("selected", "selected");
        $("select#" + type + "To option:last").attr("selected", "selected");
    }
}

widgets.searchengine.resetPayoff = function() {
    if (widgets.searchengine.originalHtml == null)
        widgets.searchengine.originalHtml = $("#hasbeenfound").html();
    $("#hasbeenfound").hide(
            widgets.searchengine.hideEffect.effect,
            widgets.searchengine.hideEffect.options,
            widgets.searchengine.showEffect.speed, function() {
                $("#hasbeenfound").html(widgets.searchengine.originalHtml);
                $("#hasbeenfound").show(
                            widgets.searchengine.showEffect.effect,
                            widgets.searchengine.showEffect.options,
                            widgets.searchengine.showEffect.speed);
            });
}


widgets.searchengine.showSale = function() {
    widgets.searchengine.resetPayoff();
    var imgtabvendita = $("#imgtabvendita")
    var imgtabaffitto = $("#imgtabaffitto");
    var tmpDivAffi = $("#divricercaaffitto");
    var tmpDivVend = $("#divricercavendita");

    imgtabvendita.attr("src", "/Content/Images/tabvendita_on.gif");
    imgtabaffitto.attr("src", "/Content/Images/tabaffitto_off.gif");
    tmpDivAffi.fadeOut("fast", function() {
        tmpDivVend.fadeIn("fast", function() {
            if ($.browser.msie)
                this.style.removeAttribute('filter');
        });
    });
};

widgets.searchengine.showRent = function() {
    widgets.searchengine.resetPayoff();
    var imgtabvendita = $("#imgtabvendita")
    var imgtabaffitto = $("#imgtabaffitto");
    var tmpDivAffi = $("#divricercaaffitto");
    var tmpDivVend = $("#divricercavendita");

    imgtabvendita.attr("src", "/Content/Images/tabvendita_off.gif");
    imgtabaffitto.attr("src", "/Content/Images/tabaffitto_on.gif");
    tmpDivVend.fadeOut("fast", function() {
        tmpDivAffi.fadeIn("fast", function() {
            if ($.browser.msie)
                this.style.removeAttribute('filter');
        });
    });
};


widgets.searchengine.isAdvancedSearchOpen = false;

widgets.searchengine.toggleAdvancedSearch = function(actionType, speed) {
    if (actionType == "show")
        widgets.searchengine.isAdvancedSearchOpen = false;
    else if (actionType == "hide")
        widgets.searchengine.isAdvancedSearchOpen = true;
    if (speed == null) speed = 500;
    if (!widgets.searchengine.isAdvancedSearchOpen) {
        $(".advancedsearch").animate({
            left: "376px"
        }, speed, "swing", function() { widgets.searchengine.isAdvancedSearchOpen = true; $('#isAdvancedSearch').val(true); });
    } else {
        $(".advancedsearch").animate({
            left: "67px"
        }, speed, "swing", function() { widgets.searchengine.isAdvancedSearchOpen = false; $('#isAdvancedSearch').val(false); });
    }

}

widgets.searchengine.searchTypeOpened = "residential";

widgets.searchengine.showSearchType = function(type) {
    widgets.searchengine.toggleAdvancedSearch("hide", 50);
    if (type == "residential" && widgets.searchengine.searchTypeOpened != type) {
        $("#residentialTab").removeClass("tab_sx").addClass("tab_sx_on");
        $("#commercialTab").removeClass("tab_on").addClass("tab");
        $(".commercialSearch").hide("slide", { direction: "down" }, 500, function() {
            $(".residentialSearch").show("slide", { direction: "down" }, 500, function() {
            });
        });
        widgets.searchengine.searchTypeOpened = type;
        $('#searchType').val(type);
    }
    if (type == "commercial" && widgets.searchengine.searchTypeOpened != type) {
        $("#commercialTab").removeClass("tab").addClass("tab_on");
        $("#residentialTab").removeClass("tab_sx_on").addClass("tab_sx");
        $(".residentialSearch").hide("slide", { direction: "down" }, 500, function() {
            $(".commercialSearch").show("slide", { direction: "down" }, 500, function() {
            });
        });
        widgets.searchengine.searchTypeOpened = type;
        $('#searchType').val(type);
    }
}

