function SearchSummary() {
    var _activeTabId;
    var _activeTabContext = {}
    var _hasListingTypeDropDown = false;
	
	var FieldReplacer = new (function () {
		var _formats = [
			{ format: "{Criteria/LocationBox}" },
			{ format: "Price: {Criteria/MinPrice} - {Criteria/MaxPrice}" },
			{ format: "Beds: {Criteria/MinBedrooms}" },
			{ format: "Baths: {Criteria/MinBathrooms}" },
			{ format: "Sq Footage: {Criteria/SquareFootage} - {Criteria/MaxSquareFootage}" },
			{ format: "Acreage: {Criteria/MinAcreage} - {Criteria/MaxAcreage}" },
			{ format: "{Criteria/City} - {Criteria/ZipCodeAdvanced}" },
			{ format: "{Neighborhood}" },
			{ format: "{HardCodedCriterion}" },
			{ format: "{Criteria/ListingTypeID}" }, 
			{ format: "{Criteria/PropertyTypeID}" },
			{ format: "{Criteria/ListingTypePropertyTypeID}" },
			{ format: "Open House Dates: {Criteria/OpenHouseStartDtm} - {Criteria/OpenHouseStopDtm}" },
			{ format: "Built: {Criteria/MinYearBuilt} - {Criteria/MaxYearBuilt}" },
			{ format: "Days on Market: {Criteria/CumulativeDaysOnMarket}" },
			{ format: "Street: {Criteria/AS_StreetName}" },
			{ format: "City: {Criteria/AS_City}" },
			{ format: "State: {Criteria/AS_StateOrProvinceCode}" },
			{ format: "Zip: {Criteria/AS_ZipCodeAdvanced}" },
			{ format: "{Criteria/AS_FilterByAddress}" },
			{ format: "Listing Number: {Criteria/ListingNumber}" },
			{ format: "Status: {Criteria/Status}" },
			{ format: "Remarks: {Criteria/PublicRemarks}" }
		];
		
		function getReplacedString(format, fields, usedFieldMap) {
			var displayString = format;
			var matches = format.match(/{[\w/]+}/gi);
			var replacedFields = [];
			
			$.each(matches, function () {
				var key = this.replace(/[{}]+/gi, "");
				if (fields[key]) {
					displayString = displayString.replace(this, fields[key].text);
					replacedFields.push(this);
					usedFieldMap[key] = 1;
				}
			});
			
			if (replacedFields.length == 0) {
				return "";
			}
			
			return displayString.replace(/(((-|\/) {[\w/]+}(.)*)|({[\w/]+}(.)*(-|\/) ))/gi, "");
		}
		
		this.reformatFeatureString = function (text) {
			var matches = text.match(/(, (All|Any))/i, "");
			if (matches && matches.length > 2) {
				return "Match (" + matches[2] + "): " + text.replace(/(, (All|Any))/i, "");
			}
			return text;
		}
		
		this.replace = function (d, items, usedFieldMap) {
			for (var key in _formats) {
				var replacedString = getReplacedString(_formats[key].format, items, usedFieldMap);
				if (replacedString != "") {
					d.push(replacedString);
				}
			}
		}
	})();
	
	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];
    }
    
    function isBasicAdvancedTabSelected() {
        return _activeTabId.toLowerCase().indexOf("basic") != -1 ||
               _activeTabId.toLowerCase().indexOf("advanced") != -1;
    }
    
    
    
	
	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 getCheckedItemsDisplayString(items) {
		var d = [];
		$(items).each(function () {
			d.push(getCheckBoxLabel(this));
		});
		return d.length ? d.join(', ') : '';
	}
	
	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", getActiveTabContext());
				if (subitems.length) {
					return input.options[input.selectedIndex].text + ": " + getCheckedItemsDisplayString(subitems);
				}
			}
			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":
			return getCheckBoxLabel(input);
		}
		return "";
	}
	
	function getSummaryItems() {
        var items = {}, t;
		
		// Textfields and select elements
		$("select:not([name^='Groups/Group_']), input[type='text']:enabled, input[type='checkbox']:checked:not([name^='Groups/Group_'])", getActiveTabContext()).each(function () {
			if ((this.id && (this.id == 'Features' || this.id == 'mapsearch-criteria-features')) ||
			    (this.name && (this.name.indexOf('Criteria/PropertyTypeID') != -1 || this.name == 'Criteria/ListingTypePropertyTypeID'))) {
				return;
			}
			
			var key = this.name ? this.name : this.id;
			if (key == "HardCodedCriterion") key = this.id;
			
			var text = getInputText(this);
			if (text == "") {
				return;
			}
			
			// Append text if the item already exists, as in the case of multiple checkboxes with the same name
			if (items[key]) {
			    text = items[key].text + ", " + text;
			}
			
			items[key] = { text: text, type: this.type, id: this.id };
		});
		

		if (isBasicAdvancedTabSelected() && !_hasListingTypeDropDown) {
		    var subitems = $("input[name='Criteria/PropertyTypeID']:checked", getActiveTabContext());
			if (subitems.length) {
		        items['Criteria/PropertyTypeID'] = { text: getCheckedItemsDisplayString(subitems) };
		    }
		}
		
		
		// Other features
		t = [];
		$(":input[name*='Groups/Group_OSF']", getActiveTabContext()).each(function () {
			if (this.checked) {
				t.push(getCheckBoxLabel(this));
			}
		});
		if (t.length > 1) items['Groups/Group_OSF'] = { text: FieldReplacer.reformatFeatureString(t.join(', ')) };
		
		
		
		// Advanced features
		var featureSelect = getFeatureDropDownList();
		if (featureSelect) {		
			if (featureSelect.options && featureSelect.options.length) {
				for (var i=0; i<featureSelect.options.length; i++) {
					var key;
					t = [];
					$(getFeatureInputs(i)).each(function () {
						if (this.checked || this.selectedIndex) {
							key = this.name;
							t.push(getInputText(this));
						}
					});
					if (t.length && (t[0] == 'Any' || t[0] == 'All')) {
						continue;
					}
					if (t.length) items[key] = { text: FieldReplacer.reformatFeatureString(featureSelect.options[i].text + ': ' + t.join(', ')) };
				}
			}
		}
		
        return items;
    }
	
	var _featureDropDownList = "";
	function getFeatureDropDownList() {
		if (_featureDropDownList == "") {
			_featureDropDownList = document.getElementById("Features");
			if (!_featureDropDownList) _featureDropDownList = document.getElementById("mapsearch-criteria-features");
		}
		return isBasicAdvancedTabSelected() ? _featureDropDownList : null;
	}
	
	var _featureInputs = {};
	function getFeatureInputs(i) {
		if (_featureInputs[i]) return _featureInputs[i];
		var f = $("#feature_" + i);
		_featureInputs[i] = $(":input", f);
		return _featureInputs[i];
	}
    
    function renderSummary() {
		var usedFieldMap = {};
		var items = getSummaryItems();
        var d = [];
		
		FieldReplacer.replace(d, items, usedFieldMap);
		
		for (var i in items) {
			if (usedFieldMap[i]) {
				continue;
			}
			
			var field = items[i];
			
			var label = "";
			if (typeof(field.type) != "undefined" && typeof(field.id) != "undefined" && field.type != "checkbox") {
				label = getLabelById(field.id);
			}
			
			var itemString;
			if (label != "") {
				itemString = label + ": " + field.text;
			} else {
				itemString = field.text;
			}
			
			d.push(itemString);
			usedFieldMap[i] = 1;
		}
        $("#search-summary-content").html(d.length == 0 ? "" : '<ul><li>' + d.join("</li><li>") + '</li></ul>');
    }

    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();
		});
    }
}
