function SearchSummary() {
    var _activeTabId;
    var _activeTabContext = {}
    var _hasListingTypeDropDown = false;
    var _namesFormatted = [];

    var _formats = [
        { name: "Criteria/MinPrice|Criteria/MaxPrice", format: "Price: {Criteria/MinPrice} - {Criteria/MaxPrice}" },
        { name: "Criteria/MinBedrooms", format: "Beds: {Criteria/MinBedrooms}" },
        { name: "Criteria/MinBathrooms", format: "Baths: {Criteria/MinBathrooms}" },
        { name: "Criteria/SquareFootage|Criteria/MaxSquareFootage", format: "Sq Footage: {Criteria/SquareFootage} - {Criteria/MaxSquareFootage}" },
        { name: "Criteria/MinAcreage|Criteria/MaxAcreage", format: "Acreage: {Criteria/MinAcreage} - {Criteria/MaxAcreage}" },
        { name: "Criteria/City|Criteria/ZipCodeAdvanced", format: "{Criteria/City} - {Criteria/ZipCodeAdvanced}" },
        { name: "Criteria/OpenHouseStartDtm|Criteria/OpenHouseStopDtm", format: "Open House Dates: {Criteria/OpenHouseStartDtm} - {Criteria/OpenHouseStopDtm}" },
        { name: "Criteria/MinYearBuilt|Criteria/MaxYearBuilt", format: "Built: {Criteria/MinYearBuilt} - {Criteria/MaxYearBuilt}" },
        { name: "Criteria/CumulativeDaysOnMarket", format: "Days on Market: {Criteria/CumulativeDaysOnMarket}" },
        { name: "Criteria/AS_StreetName", format: "Street: {Criteria/AS_StreetName}" },
        { name: "Criteria/AS_City", format: "City: {Criteria/AS_City}" },
        { name: "Criteria/AS_StateOrProvinceCode", format: "State: {Criteria/AS_StateOrProvinceCode}" },
        { name: "Criteria/AS_ZipCodeAdvanced", format: "Zip: {Criteria/AS_ZipCodeAdvanced}" },
        { name: "Criteria/AS_FilterByAddress", format: "{Criteria/AS_FilterByAddress}" },
        { name: "Criteria/ListingNumber", format: "Listing Number: {Criteria/ListingNumber}" },
        { name: "Criteria/SoldDate", format: "Sold within: {Criteria/SoldDate}" },
        { name: "Criteria/PublicRemarks", format: "Remarks: {Criteria/PublicRemarks}" }
    ];
    
    function getActiveTabSelector() {
        var legacyIds = {};
        legacyIds['basicSearch'] = "#basicSearch, #advancedSearch";
        legacyIds['advancedSearch'] = "#basicSearch, #advancedSearch";
        if (legacyIds[_activeTabId]) {
            return legacyIds[_activeTabId];
        } 
        return "#" + _activeTabId;
    }
    
    function getActiveTabContext() {
        return _activeTabContext[_activeTabId];
    }
    
    var _labelLookup = {};
    function getLabelById(id) {
        if (typeof (id) == "undefined" || id == "") return "";
        if (_labelLookup[id]) return _labelLookup[id];
        _labelLookup[id] = $("label[for='" + id + "']:first", getActiveTabContext()).text();
        return _labelLookup[id];
    }
    
    function getCheckBoxLabel(obj) {
        // Check if the element has a label for it
        var label = getLabelById(obj.id);
        if (label != "") {
            return label;
        }
    
        var next = obj.nextSibling;
        while (next) {
            var v = jQuery.trim(next.nodeType != 1 ? next.nodeValue : $(next).text());
            if (v != "") {
                return v;
            }
            next = next.nextSibling;
        }
        return "";
    }
    
    function getPreviousSiblingText(obj) {
        var text = $(obj).parent().text();
        if (text != "") {
            text = jQuery.trim(text);
            text = jQuery.trim(text.substr(0, text.indexOf(":")));
            return text;
        }
        return "";
    }

    function getGroupName(input) {
        var groupName = "";
        var $featureListBox = $(input).closest(".featureListBox");
        if ($featureListBox.length > 0) {
            var featureListBoxId = $featureListBox[0].id;
            if (featureListBoxId.indexOf("feature_") != -1) {
                var featureListBoxIdx = featureListBoxId.substring(featureListBoxId.indexOf("_") + 1);
                var $featureDD = $("select[name='dd_Features']", getActiveTabContext());
                if ($featureDD.length === 0) {
                    $featureDD = $("select.featuresdd", getActiveTabContext());
                }
                if ($featureDD.length === 0) {
                    $featureDD = $("#mapsearch-criteria-features", getActiveTabContext());
                }                
                if ($featureDD.length > 0) {
                    groupName = $featureDD[0].options[parseInt(featureListBoxIdx, 10)].text;
                }
            }
        }
        return groupName;
    }
    
    function getInputText(input) {
        switch (input.type) {
        case "text":
            return input.value;
            
        case "select-one":
            if (input.name == "Criteria/ListingTypeID") {
                _hasListingTypeDropDown = true;
                var subitems = $("#propertyType_" + input.selectedIndex + " input:checked:enabled", getActiveTabContext());
                return subitems.length === 0 ? input.options[input.selectedIndex].text : "";
            }
            var prefix = "";
            if (input.name.indexOf("Groups/Group_") == 0) {
                prefix = getPreviousSiblingText(input);
                if (prefix != "") prefix += ": ";
            }
            return input.value == "" ? "" : prefix + input.options[input.selectedIndex].text;
            
        case "checkbox":
        case "radio":
            var label = getCheckBoxLabel(input);
            if (label === "") {
                return label;
            }
            if (input.name === "Criteria/PropertyTypeID" || input.name === "Criteria/ListingTypePropertyTypeID") {
                // Make sure this checkbox is visible
                if (!$(input).is(":visible")) {
                    return "";
                }
                var $listingTypeSelects = $("select[name='Criteria/ListingTypeID']", getActiveTabContext());
                if ($listingTypeSelects.length > 0) {
                    var listingTypeSelect = $listingTypeSelects[0];
                    var listingTypeSelectText = listingTypeSelect.options[listingTypeSelect.selectedIndex].text;
                    if (listingTypeSelectText !== "") {
                        label = listingTypeSelectText + ": " + label;
                    }
                }
            } else if (input.name === "Criteria/Status") {
                label = "Status: " + label;
            } else if (input.name.indexOf("Groups/Group_") != -1) {
                var groupName = getGroupName(input);
                if (groupName !== "") {
                    label = groupName + ": " + label;
                }
            }
            return label;
        }
        return "";
    }
    
    function getFormattedInput(input) {
        var formattedInput = {name: "", text: ""};
        for (var c = 0; c<_formats.length; c++) {
            var format = _formats[c];
            if (format.name.indexOf(input.name) != -1) {
                var formatNames = format.name.split("|");
                var formatText = format.format;
                for (var i=0; i<formatNames.length; i++) {
                    var formatName = formatNames[i];
                    var $el = $("select[name='" + formatName + "'],:input[name='" + formatName + "']", getActiveTabContext());
                    if ($el.length > 0) {
                        formatText = formatText.replace("{" + formatName + "}", getInputText($el[0]));
                    }
                    _namesFormatted.push(formatName);

                }
                formattedInput.name = format.name;
                formattedInput.text = formatText.replace(/(((-|\/) {[\w/]+}(.)*)|({[\w/]+}(.)*(-|\/) ))/gi, "");
                break;
            }
        }
        return formattedInput;
    }

    function getCssClass(fieldName) {
        if (!fieldName) {
            return "";
        }
        var cssClass = "remove-criteria";
        if (fieldName.indexOf("|") != -1) {
            fieldName = fieldName.split("|")[0];
        }
        var els = $("*[name='" + fieldName + "']");
        var el;
        if (els.length > 0) {
            el = els[0];
        }

        // If this is a select, and there's no empty option, don't allow removal
        if (el && el.nodeName.toLowerCase() === "select" && $("option[value='']", $(el)).length == 0) {
            cssClass = "";
        }
        return cssClass;
    }

    function getSummaryItems() {
        var items = [];
        _namesFormatted = [];

        // Locations
        var $locations = $("input[name='Criteria/Location']", getActiveTabContext());
        if ($locations.length > 0) {
            var locations = $locations.val().split("|");
            for (var i=0; i<locations.length; i++) {
                if (locations[i] && locations[i] !== "") {
                    items.push({ 
                        text: locations[i], 
                        name: "Criteria/Location",
                        value: locations[i]
                    });
                }
            }
        }

        // Other criteria
        $("select, input[type='text']:enabled, input[type='checkbox']:checked:enabled", getActiveTabContext()).each(function () {
            // We don't want the Features dropdowns in here
            if (this.id === 'Features' || this.id === 'mapsearch-criteria-features' || (this.type === 'select-one' && this.name.indexOf('Groups/Group_') != -1)) {
                return;
            }
            // Exclude the PropertyTypeID_X values
            if (this.name === 'Criteria/PropertyTypeID_X' || this.name == 'Criteria/ListingTypePropertyTypeID_X') {
                return;
            }
            // If we've already used this in a comboformat, don't do it again
            if ($.inArray(this.name, _namesFormatted) != -1) {
                return;
            }
            // If there's no text for this input, continue
            var inputText = getInputText(this);
            if (inputText === "") {
                return;
            }
            var formattedInput = getFormattedInput(this);
            if (formattedInput && formattedInput.text !== "") {
                items.push({
                    text: formattedInput.text,
                    name: formattedInput.name,
                    value: this.value
                });
            } else {
                var label = "";
                if (this.id && inputText.indexOf(":") === -1) {
                    label = getLabelById(this.id);
                }
                if (label !== "" && label !== inputText) {
                    inputText = label + ": " + inputText;
                }

                items.push({
                    text: inputText,
                    name: this.name,
                    value: this.value
                });
            }
        });

        return items;
    }
    
    function renderSummary() {

        var items = getSummaryItems();
        
        var summaryContent = "";
        if (items && items.length > 0) {
            summaryContent = "<ul>";
            for (var i=0; i<items.length; i++) {
                var item = items[i];
                if (item.text && item.text !== "") {
                    var fieldName = items[i].name;
                    var fieldVal = items[i].value;
                    if (!fieldVal) {
                        fieldVal = "";
                    }
                    summaryContent += "<li";
                    var cssClass = getCssClass(fieldName);
                    if (cssClass && cssClass.length > 0) {
                        summaryContent += " class='" + cssClass + "'";
                    }
                    summaryContent += " fieldname='" + fieldName + "'"
                    summaryContent += " fieldval='" + escape(fieldVal) + "'>" + items[i].text + "</li>";
                }
            }
            summaryContent += "</ul>";
        }
        $("#search-summary-content").html(summaryContent);

        $("#search-summary-content li.remove-criteria")
            .click(function() {
                var $this = $(this);
                $(document).trigger("removecriteria", [{
                    name: $this.attr("fieldname"), 
                    val: unescape($this.attr("fieldval"))
                }]);
            })
            .css("cursor", "pointer");
    }

    function setActiveTab(activeTabId) {
        _activeTabId = activeTabId;
        if (!getActiveTabContext()) {
            _activeTabContext[activeTabId] = $(getActiveTabSelector());
        }
    }
    
    this.load = function(activeTabId) {
        setActiveTab(activeTabId);
        
        var _isLoaded = document.all ? 0 : 1;
        $(document).bind("criteriachange", function(e, eventData) {
            if (!_isLoaded) {
                _isLoaded = 1;
                return;
            }
            setActiveTab(eventData.activeTab);
            renderSummary();
        });
        
        $(document).bind("criteriaitemchange", function(e, eventData) {
            renderSummary();
        });
    }
}

