﻿if (!BackAgent) { var BackAgent = {}; };
BackAgent.FavoritePage = {
	_activeLists: [],
	_compare: "all",
	_sort: "listprice",
	init: function() {
		var page;
		if (!(page = $("FavoritePage"))) { return; }
		// on load:
		// get active lists and save to local data
		var lists = $$("#FavoriteLists div.ListName.ActiveList");
		var listIds = lists.map(function(e) {
			return e.id.replace("List_", "");
		});
		BackAgent.FavoritePage._activeLists = listIds;
		// do filtering and sync UI (handleMultiple -> setCompare -> filterProperties -> updateSession)
		// could do a noFilter here, but we'll let it double-check and also set good session vars
		BackAgent.FavoritePage._hListsChanged(true);
		// sort the properties
		BackAgent.FavoritePage.setSort(BackAgent.FavoritePage._sort);
		BackAgent.FavoritePage.Editor.init();
	},
	_hListsChanged: function(noUpdate) {
		if (BackAgent.FavoritePage._activeLists.length > 1) {
			if (BackAgent.FavoritePage._compare == "none") { BackAgent.FavoritePage._compare = "all"; }
			BackAgent.FavoritePage.setCompare(BackAgent.FavoritePage._compare, noUpdate);
		} else {
			BackAgent.FavoritePage.setCompare('none', noUpdate);
		}
	},
	_updateSession: function() {
		var xhr = new Ajax.Request("/service/favorite_page.aspx", {
			method: "post",
			parameters: {
				"l": BackAgent.FavoritePage._activeLists, 
				"c": BackAgent.FavoritePage._compare,
				"s": BackAgent.FavoritePage._sort
			}
		});
	},
	addList: function(listId, skipHandler) {
		if (!BackAgent.FavoritePage._activeLists.include(listId)) {
			var div = $("List_" + listId);
			if (div) {
				div.addClassName("ActiveList");
			}
			BackAgent.FavoritePage._activeLists.push(listId);
			if (!skipHandler) {
				BackAgent.FavoritePage._hListsChanged();
			}
		}
	},
	removeList: function(listId, skipHandler) {
		if (BackAgent.FavoritePage._activeLists.include(listId)) {
			if (BackAgent.FavoritePage._activeLists.length <= 1) { return; }	// don't remove last
			var div = $("List_" + listId);
			if (div) {
				div.removeClassName("ActiveList");
			}
			BackAgent.FavoritePage._activeLists = BackAgent.FavoritePage._activeLists.without(listId);
			if (!skipHandler) {
				BackAgent.FavoritePage._hListsChanged();
			}
		}
	},
	setList: function(listId) {
		BackAgent.FavoritePage.addList(listId, true);
		var actives = BackAgent.FavoritePage._activeLists.clone();
		actives.each(function(id) {
			if (id != listId) {
				BackAgent.FavoritePage.removeList(id, true);
			}
		});
		BackAgent.FavoritePage._hListsChanged();
	},
	setCompare: function(mode, noUpdate) {
		mode = mode.toLowerCase();
		BackAgent.FavoritePage._compare = mode;
		if (mode == 'all') {
			$("FavoritePropertiesCompNone").hide();
			$("FavoritePropertiesCompAll").show();
			$("FavoritePropertiesCompMatch").hide();
		} else if (mode == 'match') {
			$("FavoritePropertiesCompNone").hide();
			$("FavoritePropertiesCompAll").hide();
			$("FavoritePropertiesCompMatch").show();
		} else {
			$("FavoritePropertiesCompNone").show();
			$("FavoritePropertiesCompAll").hide();
			$("FavoritePropertiesCompMatch").hide();
		}
		BackAgent.FavoritePage.Results.filterProperties(noUpdate);
	},
	setSort: function(sort, noUpdate) {
		sort = sort.toLowerCase();
		BackAgent.FavoritePage._sort = sort;
		var elements = $$("#FavoritePropertiesSort a");
		elements.each(function(element) {
			if (element.hasClassName(sort)) {
				element.addClassName("ActiveSort");
			} else {
				element.removeClassName("ActiveSort");
			}
		});
		BackAgent.FavoritePage.Results.sortProperties(noUpdate);
	},
	List: {
		click: function(element) {
			if (!(element = $(element))) { return false; }
			var div = element.up("div");
			if (!div) { return false; }
			var listId = div.id.replace("List_", "");
			if (div.hasClassName("ActiveList")) {
				BackAgent.FavoritePage.removeList(listId);
			} else {
				BackAgent.FavoritePage.addList(listId);
			}
			element.blur();
			return false;
		},
		dblclick: function(element) {
			if (!(element =  $(element))) { return false; }
			var div = element.up("div");
			if (!div) { return false; }
			var listId = div.id.replace("List_", "");
			BackAgent.FavoritePage.setList(listId);
			element.blur();
			return false;
		}
	},
	Editor: {
		data: {},
		init: function() {
			var dialogDiv = $("FavoriteEditor");
			if (!dialogDiv) { return; }
			var backingDiv = $("ScreenGrayout");
			var formElement = $("FavoriteEditorForm");
			Object.extend(BackAgent.FavoritePage.Editor.data, {
				dialog: dialogDiv,
				backing: backingDiv,
				form: formElement
			});
			//dialogDiv.absolutize();
		},
		_positionDialog: function() {
			var data = BackAgent.FavoritePage.Editor.data;
			var screenDim = document.viewport.getDimensions();
			var dialogDim = data.dialog.getDimensions();
			var setLeft = 0, setTop = 0;
			if (screenDim.width > dialogDim.width) {
				setLeft = parseInt((screenDim.width - dialogDim.width) / 2);
			}
			if (screenDim.height > dialogDim.height) { 
				setTop = parseInt((screenDim.height - dialogDim.height) / 2);
			}
			data.dialog.setStyle({left: setLeft + "px", top: setTop + "px"});
		},
		open: function() {
			var data = BackAgent.FavoritePage.Editor.data;
			$("ListEditorOK").disabled = false;
			if (data.backing) {
				data.backing.show(); 
			}
			BackAgent.FavoritePage.Editor._positionDialog();
			new Effect.Appear(data.dialog, { duration: 0.25 });
			return false;
		},
		cancel: function() {
			var data = BackAgent.FavoritePage.Editor.data;
			if (data.backing) {
				new Effect.Fade(data.backing, { duration: 0.25 });
			}
			data.dialog.hide();
			data.dialog.select(".ListItemEdit").invoke("show");
			data.dialog.select(".ListItemDeleted").invoke("hide");
			data.form.reset();
			return false;
		},
		deleteItem: function(listId) {
			var item = $("ListItemEdit_" + listId);
			var deleted = $("ListItemDeleted_" + listId);
			var input = $("ListDelete_" + listId);
			if (item && deleted && input) { 
				item.hide();
				deleted.show(); 
				input.value = "1";
			}
			return false;
		},
		save: function() {
			var data = BackAgent.FavoritePage.Editor.data;
			$("ListEditorOK").disabled = true;
			data.form.submit();
			return false;
		}
	},
	Results: {
		_effectDuration: 0.25,
		flash: function() {
			//return;
			var flasher = $("FavoritePropertiesFlasher");
			if (!flasher) { return; }
			if (BackAgent.FavoritePage.Results._effect) { return; }	// single flash only
			var place = $("FavoriteProperties");
			var title = $("FavoritePropertiesTitle");
			// get background color:
			var bgColor = "transparent", element = place;
			while (bgColor == "transparent" && element) {
				bgColor = element.getStyle("backgroundColor");
				element = $(element.parentNode);
			}
			// position & color
			flasher.setStyle({ backgroundColor: bgColor });
			flasher.absolutize();
			var heightDiff = title.offsetHeight;	// NOTE hardcoded 10s for margin/padding
			flasher.clonePosition(place, { offsetTop: heightDiff });
			flasher.setStyle({ height: (place.offsetHeight - heightDiff) + "px" });
			// fade effect
			flasher.show();
			BackAgent.FavoritePage.Results._effect = new Effect.Fade(flasher, { duration: BackAgent.FavoritePage.Results._effectDuration });
			BackAgent.FavoritePage.Results.flashReset.delay(BackAgent.FavoritePage.Results._effectDuration);
		},
		flashReset: function() {
			BackAgent.FavoritePage.Results._effect = null;
		},
		sortProperties: function(noUpdate) {
			//return;
			// flash the screen to show activity
			if (!noUpdate) {
				BackAgent.FavoritePage.Results.flash();
			}
			// set up sort method
			var sort = BackAgent.FavoritePage._sort;
			var sortUp = function(a, b) {
				if (a[1] < b[1]) { return -1; }
				if (a[1] > b[1]) { return 1; }
				return 0;
			}
			var sortDown = function(a, b) {
				if (a[1] > b[1]) { return -1; }
				if (a[1] < b[1]) { return 1; }
				return 0;
			}
			var sortFn = sortDown;
			if (sort == "subdivision") { sortFn = sortUp; }
			
			// sort data arrays
			var propertyDivs = $$("#FavoritePropertiesResults > div.Property");
			var propertyIDs = propertyDivs.pluck("id");
			var propertyVals = propertyDivs.map(function(div) {
				var dataVal = "";
				var data = div.select("dfn." + sort);
				if (data) { dataVal = data[0].getText(); }
				return dataVal;
			});
			var propIDVals = propertyIDs.zip(propertyVals);
			var propIDValsSorted = propIDVals.sort(sortFn);
			// sort divs in the page
			propIDValsSorted.each(function(item) {
				var div = $(item[0]);
				var parent = div.parentNode;
				parent.removeChild(div);
				parent.appendChild(div);				
				// hide/show data fields
				if (sort == "listprice" || sort == "rating" || sort == "subdivision") {
					div.select("span.subdivision").invoke("show");
					div.select("span.sqft").invoke("hide");
					div.select("span.yearbuilt").invoke("hide");
				}
				if (sort == "sqft") {
					div.select("span.subdivision").invoke("hide");
					div.select("span.sqft").invoke("show");
					div.select("span.yearbuilt").invoke("hide");
				}
				if (sort == "yearbuilt") {
					div.select("span.subdivision").invoke("hide");
					div.select("span.sqft").invoke("hide");
					div.select("span.yearbuilt").invoke("show");
				}
			});
			// update session variables
			if (!noUpdate) {
				BackAgent.FavoritePage._updateSession();
			}
		},
		filterProperties: function(noUpdate) {
			//return;
			// flash the screen to show activity
			if (!noUpdate) {
				BackAgent.FavoritePage.Results.flash();
			}
			var activeLists = BackAgent.FavoritePage._activeLists;
			var compare = BackAgent.FavoritePage._compare;
			var numLists = activeLists.length;
			var numShown = 0, numAvail = 0, numMatch = 0;
			// update property results
			var propertyDivs = $$("#FavoritePropertiesResults div.Property");
			propertyDivs.each(function(propDiv) {
				//var mlsNum = propDiv.id.replace("Property_", "");
				var listInputs = propDiv.select("input.PropertyData");
				var listIds = listInputs.pluck("value");
				var comparator = function(id) {
					return listIds.include(id);
				}
				var matchAll = activeLists.all(comparator);
				var matchAny = matchAll || activeLists.any(comparator);
				var show = (compare == "match") ? matchAll : matchAny;

				if (matchAll) { numMatch++; }
				if (matchAny) { numAvail++; }
				if (show) { numShown++; }

				propDiv[(show) ? "show" : "hide"]();
			});
			// update compare helper nums
			var compDiv = $("FavoritePropertiesComp");
			
			var spans = compDiv.select(".NumActiveLists");
			spans.invoke("update", numLists);
			spans = compDiv.select(".NumActiveListsUnit");
			spans.invoke("update", ((numLists != 1) ? "lists" : "list"));
			
			spans = compDiv.select(".NumTotalShown");
			spans.invoke("update", numShown);
			spans = compDiv.select(".NumTotalShownUnit");
			spans.invoke("update", ((numShown != 1) ? "properties" : "property"));
			
			spans = compDiv.select(".NumActiveMatch");
			spans.invoke("update", numMatch);
			spans = compDiv.select(".NumActiveMatchUnit");
			spans.invoke("update", ((numMatch != 1) ? "properties" : "property"));
			
			spans = compDiv.select(".NumTotalAvail");
			spans.invoke("update", numAvail);
			spans = compDiv.select(".NumTotalAvailUnit");
			spans.invoke("update", ((numAvail != 1) ? "properties" : "property"));
			
			if (numMatch < 1 && compare == "all") { compDiv.select(".CompButton").invoke("hide"); }
			else { compDiv.select(".CompButton").invoke("show"); }
			
			// hide the 0/0 message
			if (numLists == 0) { $("FavoritePropertiesCompNone").hide(); }
			
			// update session variables
			if (!noUpdate) {
				BackAgent.FavoritePage._updateSession();
			}
		}
	}
};
Event.observe(window, "load", BackAgent.FavoritePage.init.bind(BackAgent.FavoritePage));


BackAgent.FavoritePanelMover = {
	init: function() {
		var panel = $("FavoritePanel");
		if (!panel) { return; }
		this._panel = panel;
		
		panel.absolutize();
		panel.setStyle({ left: parseFloat(panel.getStyle("left")) - parseFloat(panel.getStyle("margin-left")),
			height: "auto" 
		});
		
		this._startCumTop = panel.cumulativeOffset().top;
		this._startPosTop = panel.positionedOffset().top;
		this.move();
	},
	move: function() {
		if (!this._panel) { return; }
		var startTop = this._startCumTop;
		var currentTop = this._panel.cumulativeOffset().top;
		var scrollTop = document.viewport.getScrollOffsets().top;
		if (scrollTop + 10 > startTop) {
			// move down if the scrolloffset is greater than the original offset
			var deltaTop = scrollTop + 10 - startTop;
			var newTop = this._startPosTop + deltaTop;
			this._panel.setStyle({ top: newTop + "px" });
		} else if (currentTop > startTop) {
			// reset when the current offset is greater than the original offset
			this._panel.setStyle({ top: this._startPosTop + "px" });
		}
	}
};
Event.observe(window, "load", BackAgent.FavoritePanelMover.init.bind(BackAgent.FavoritePanelMover));
Event.observe(window, "scroll", BackAgent.FavoritePanelMover.move.bind(BackAgent.FavoritePanelMover));
Event.observe(window, "resize", BackAgent.FavoritePanelMover.move.bind(BackAgent.FavoritePanelMover));

BackAgent.FavoritePanel = {
	_listId: "",
	_listName: "",
	_defaultListName: "My Favorites",
	_mlsNum: "",
	_action: "Add",
	_mode: "Existing",
	_addBehavior: "addItem",
	_removeBehavior: "removeItemCurrent",
	_effectDuration: 0.25,
	_cancelOpenAjax: function() {
		if (BackAgent.FavoritePanel._xhr) {
			BackAgent.FavoritePanel._xhr.transport.abort();
			BackAgent.FavoritePanel._xhr = null;
		}
	},
	init: function() {
		var picker;
		if (!(picker = $("FavoriteListPicker"))) { return; }
		var _effectOptions = { duration: BackAgent.FavoritePanel._effectDuration };
		popup = new Widgets.Popup(picker, null, {
			behavior: "click",
			position: "relativeFar",
			positionAlign: "right top",
			positionOffset: { x: 10, y: -10 },
			showEffect: BackAgent.FavoritePanel.Effects.appear.bind(BackAgent.FavoritePanel.Effects, _effectOptions),
			hideEffect: BackAgent.FavoritePanel.Effects.fade.bind(BackAgent.FavoritePanel.Effects, _effectOptions),
			onBeforeShow: BackAgent.FavoritePanel.Picker.init,
			onShow: BackAgent.FavoritePanel.Picker.initShown
		});
		BackAgent.FavoritePanel.popup = popup;
		BackAgent.FavoritePanel.ListChange.init();
	},
	reset: function() {
		var trigger = BackAgent.FavoritePanel._trigger;
		if (trigger) {
			trigger.locked = null;
			BackAgent.FavoritePanel._trigger = null;
		}
		BackAgent.FavoritePanel._xhr = null;
	},
	cancel: function(force) {
		BackAgent.FavoritePanel.popup.hide(force);
		BackAgent.FavoritePanel.reset();
	},
	addItem: function(trigger, mlsNum) {
		if (!(trigger = $(trigger))) { return; }
		if (BackAgent.FavoritePanel._trigger && BackAgent.FavoritePanel._trigger != trigger) {
			BackAgent.FavoritePanel.cancel(true);
		}
		BackAgent.FavoritePanel._trigger = trigger;
		BackAgent.FavoritePanel._mlsNum = mlsNum;
		BackAgent.FavoritePanel._action = "Add";
		BackAgent.FavoritePanel.popup.showByElement(trigger);
	},
	addItemCurrent: function(trigger, mlsNum) {
		if (!(trigger = $(trigger))) { return; }
		BackAgent.FavoritePanel._trigger = trigger;
		var params = { 
			"m": "a",
			"mls": mlsNum,
			"li": BackAgent.FavoritePanel._listId
		};
		BackAgent.FavoritePanel._cancelOpenAjax();
		BackAgent.FavoritePanel._xhr = new Ajax.Updater("FavoritePanelListItems", "/service/favorite_panel.aspx", {
			method: "post",
			parameters: params,
			onCreate: BackAgent.FavoritePanel.PickerAjax.onCreate,
			onSuccess: BackAgent.FavoritePanel.PickerAjax.onSuccess,
			onFailure: BackAgent.FavoritePanel.PickerAjax.onFailure,
			onException: BackAgent.FavoritePanel.PickerAjax.onException
		});
	},
	removeItem: function(trigger, mlsNum) {
		if (!(trigger = $(trigger))) { return; }
		if (BackAgent.FavoritePanel._trigger && BackAgent.FavoritePanel._trigger != trigger) {
			BackAgent.FavoritePanel.cancel(true);
		}
		BackAgent.FavoritePanel._trigger = trigger;
		BackAgent.FavoritePanel._mlsNum = mlsNum;
		BackAgent.FavoritePanel._action = "Remove";
		BackAgent.FavoritePanel.popup.showByElement(trigger);
	},
	removeItemCurrent: function(trigger, mlsNum) {
		if (!(trigger = $(trigger))) { return; }
		BackAgent.FavoritePanel._trigger = trigger;
		if (!confirm("Are you sure you want to remove this listing?")) { 
			BackAgent.FavoritePanel.cancel(true);
			return ; 
		}
		var params = { 
			"m": "r",
			"mls": mlsNum,
			"li": BackAgent.FavoritePanel._listId
		};
		BackAgent.FavoritePanel._cancelOpenAjax();
		BackAgent.FavoritePanel._xhr = new Ajax.Updater("FavoritePanelListItems", "/service/favorite_panel.aspx", {
			method: "post",
			parameters: params,
			onCreate: BackAgent.FavoritePanel.PickerAjax.onCreate,
			onSuccess: BackAgent.FavoritePanel.PickerAjax.onSuccess,
			onFailure: BackAgent.FavoritePanel.PickerAjax.onFailure,
			onException: BackAgent.FavoritePanel.PickerAjax.onException
		});
	},
	toggleItem: function(trigger, mlsNum) {
		if (!(trigger = $(trigger))) { return; }
		if (!trigger.hasClassName("ListingResultFavorite")) {
			trigger = trigger.up("div.ListingResultFavorite");
			if (!trigger) { return; }
		}
		if (trigger.locked) { return; }	// prevent double-click
		trigger.locked = true;
		if (trigger.hasClassName("NotListed")) { 
			// add
			var method = BackAgent.FavoritePanel._addBehavior;
			BackAgent.FavoritePanel[method](trigger, mlsNum);
		} else if (trigger.hasClassName("ActiveListing")) {
			// remove
			var method = BackAgent.FavoritePanel._removeBehavior;
			BackAgent.FavoritePanel[method](trigger, mlsNum);
		}
	},
	toggleTrigger: function() {
		var trigger = BackAgent.FavoritePanel._trigger;
		if (!trigger) { return ; }
		if (trigger.hasClassName("NotListed")) {
			trigger.removeClassName("NotListed");
			trigger.addClassName("ActiveListing");
		} else {
			trigger.addClassName("NotListed");
			trigger.removeClassName("ActiveListing");
		}
	},
	Effects: {
		appear: function(options, element) {
			return Effect.Appear(element, options);
		},
		fade: function(options, element) {
			return Effect.Fade(element, options);
		}
	},
	ListChange: {
		_effectOptions: { duration: 0.25 },
		_showing: false,
		init: function() {
			var chooser;
			if (!(chooser = $("FavoriteListChooser"))) { return; }
			var _effectOptions = { duration: BackAgent.FavoritePanel._effectDuration };
			popup = new Widgets.Popup(chooser, null, {
				behavior: "click",
				position: "relativeFar",
				positionAlign: "right under",
				positionOffset: { x: 0, y: 2 },
				showEffect: BackAgent.FavoritePanel.Effects.appear.bind(BackAgent.FavoritePanel.Effects, _effectOptions),
				hideEffect: BackAgent.FavoritePanel.Effects.fade.bind(BackAgent.FavoritePanel.Effects, _effectOptions)
			});
			BackAgent.FavoritePanel.ListChange.popup = popup;
			BackAgent.FavoritePanel.ListChange._showing = chooser.visible();
		},
		showByElement: function(trigger) {
			BackAgent.FavoritePanel.ListChange.popup.showByElement(trigger);
			BackAgent.FavoritePanel.ListChange._showing = true;
		},
		hide: function() {
			BackAgent.FavoritePanel.ListChange.popup.hide();
			BackAgent.FavoritePanel.ListChange._showing = false;
		},
		toggle: function(trigger) {
			if (!(trigger = $(trigger))) { return; }
			if (BackAgent.FavoritePanel.ListChange._showing) {
				BackAgent.FavoritePanel.ListChange.hide();
			} else {
				BackAgent.FavoritePanel.ListChange.showByElement(trigger);
			}
		},
		select: function(listId) {
			var params = { 
				"m": "v",
				"li": listId
			};
			BackAgent.FavoritePanel._cancelOpenAjax();
			BackAgent.FavoritePanel._xhr = new Ajax.Updater("FavoritePanelListItems", "/service/favorite_panel.aspx", {
				method: "post",
				parameters: params,
				onCreate: BackAgent.FavoritePanel.PickerAjax.onCreate,
				onSuccess: BackAgent.FavoritePanel.PickerAjax.onSuccess,
				onFailure: BackAgent.FavoritePanel.PickerAjax.onFailure,
				onException: BackAgent.FavoritePanel.PickerAjax.onException
			});
			BackAgent.FavoritePanel.ListChange.hide();
		}
	},
	Picker: {
		init: function() {
			var action = BackAgent.FavoritePanel._action;
			if (action == "Remove") {
				$("FavoriteListPickPrompt").update("Remove this property from:");
				$("FavoriteListPickChoose").show();
				$("FavoriteListPickCreateLink").hide();
				$("FavoriteListPickCreateInput").hide();
				//$("FavoriteListPickOK").writeAttribute("value", "Remove Listing");
				$("FavoriteListPickOK").value = "Remove Listing";
				$("FavoriteListPickHelpLink").show();
				$("FavoriteListPickHelp").hide();
				$("FavoriteListPickOK").disabled = false;
				// todo filter select box for assigned lists
//				var listDef = BackAgent.FavoritePanel._listDef;
//				var sel = $("FavoriteListPickID");
//				$A(sel.options).each(function(opt) {
//					var list = listDef.find(function(item) {
//						return (item.value == BackAgent.FavoritePanel._listId);
//					});
//					if (list) {
//						opt.disabled = list.items.include(BackAgent.FavoritePanel._mlsNum);
//					}
//				});
			} else {
				$("FavoriteListPickPrompt").update("Assign this property to:");
				$("FavoriteListPickChoose").show();
				$("FavoriteListPickCreateLink").show();
				$("FavoriteListPickCreateInput").hide();
				//$("FavoriteListPickOK").writeAttribute("value", "Add Listing");
				$("FavoriteListPickOK").value = "Add Listing";
				$("FavoriteListPickHelpLink").show();
				$("FavoriteListPickHelp").hide();
				$("FavoriteListPickOK").disabled = false;
			}
			BackAgent.FavoritePanel._mode = "Existing";
		},
		initShown: function() {
			var sel = $("FavoriteListPickID");
			if (sel.options.length == 0) {
				//$("FavoriteListPickCreateName").writeAttribute("value", BackAgent.FavoritePanel._defaultListName);
				$("FavoriteListPickCreateName").value = BackAgent.FavoritePanel._defaultListName;
				BackAgent.FavoritePanel.Picker.showCreate();
			} else {
				//alert("test check");
				//$("FavoriteListPickCreateName").writeAttribute("value", "");
				$("FavoriteListPickCreateName").value = "";
				Form.Field.setValue(sel.form, sel.name, BackAgent.FavoritePanel._listId);
			}
		},
		showCreate: function() {
			$("FavoriteListPickChoose").hide();
			$("FavoriteListPickCreateInput").show();
			//$("FavoriteListPickOK").writeAttribute("value", "Create & Add Listing");
			$("FavoriteListPickOK").value = "Create & Add Listing";
			BackAgent.FavoritePanel._mode = "New";
			var x = function() {
				$("FavoriteListPickCreateName").select();
				$("FavoriteListPickCreateName").focus();
			};
			x.delay(BackAgent.FavoritePanel._effectDuration);
		},
		showHelp: function() {
			$("FavoriteListPickHelpLink").hide();
			$("FavoriteListPickHelp").show();
		},
		submit: function() {
			var params = {
				"m": BackAgent.FavoritePanel._action.substr(0, 1).toLowerCase(),
				"mls": BackAgent.FavoritePanel._mlsNum
			};
			if (BackAgent.FavoritePanel._mode == "New") {
				Object.extend(params, {
					"ln": $("FavoriteListPickCreateName").getValue(),
					"li": ""
				});
			} else {
				Object.extend(params, {
					"li": $("FavoriteListPickID").getValue(),
					"ln": ""
				});
			}
			$("FavoriteListPickOK").disabled = true;
			BackAgent.FavoritePanel._cancelOpenAjax();
			BackAgent.FavoritePanel._xhr = new Ajax.Updater("FavoritePanelListItems", "/service/favorite_panel.aspx", {
				method: "post",
				parameters: params,
				onCreate: BackAgent.FavoritePanel.PickerAjax.onCreate,
				onSuccess: BackAgent.FavoritePanel.PickerAjax.onSuccess,
				onFailure: BackAgent.FavoritePanel.PickerAjax.onFailure,
				onException: BackAgent.FavoritePanel.PickerAjax.onException
			});
			BackAgent.FavoritePanel.popup.hide();
		}
	},
	PickerAjax: {
		onCreate: function(poReq, poXHR) {
			$("FavoritePanelListItems").update("<p style=\"text-align: center;\">Loading...<br /><img src=\"/common/theme/image/bigcircle_transp_black.gif\" alt=\"\"/></p>")
		},
		onSuccess: function(poXHR, poJSON) {
			var status = poJSON.status;
			if (status == 0) {
				var listCount = poJSON.listDef.length;
				var listChange = (poJSON.listId != BackAgent.FavoritePanel._listId);
				BackAgent.FavoritePanel._listId = poJSON.listId;
				BackAgent.FavoritePanel._listName = poJSON.listName;
				BackAgent.FavoritePanel._mlsNums = poJSON.mlsNums;
				BackAgent.FavoritePanel._mlsTotal = poJSON.mlsTotal;
				BackAgent.FavoritePanel._listDef = poJSON.listDef;
				if (listChange) {
					// show/hide the drop-arrow
//					if ($("FavoritePanelTitleDrop")) {
//						$("FavoritePanelTitleDrop")[(listCount > 1) ? "show" : "hide"]();
//					}
//					// update list name html
					if ($("FavoritePanelTitle")) {
						$("FavoritePanelTitle").update(BackAgent.FavoritePanel._listName);
					}
					if ($("FavoriteSummaryTitle")) {
						$("FavoriteSummaryTitle").update(BackAgent.FavoritePanel._listName);
					}
					// update search result buttons for current list
					BackAgent.FavoritePanel.ResultUpdater.updateListings();
					BackAgent.FavoritePanel.ResultUpdater.updatePicker();
				}
				else {
					// toggle the trigger button
					BackAgent.FavoritePanel.toggleTrigger();
				}
				BackAgent.FavoritePanel.ResultUpdater.updateChooser();	// always (for counts)
				BackAgent.FavoritePanel.ResultUpdater.updateStats();
			}
			BackAgent.FavoritePanel.reset();
		},
		onFailure: function(poXHR, poJSON) {
			$("FavoritePanelListItems").update("<p>ERROR!</p>");
			BackAgent.FavoritePanel.reset();
		},
		onException: function(poXHR, poException) {
			alert(poException);
			BackAgent.FavoritePanel.reset();
		}	
	},
	ResultUpdater: {
		updateListings: function() {
			// loop through search results using mls array and set class to active or inactive
			var elements = $$("div.ListingResultFavorite, div.ListingResultFavoriteDetail");
			elements.each(function(element) {
				var anchor = element;//.down("a");
				var mlsNum = anchor.id.substr("QuickAddLinkXXX".length);
				if (BackAgent.FavoritePanel._mlsNums.include(mlsNum)) {
					anchor.removeClassName("NotListed");
					anchor.addClassName("ActiveListing");
				} else {
					anchor.addClassName("NotListed");
					anchor.removeClassName("ActiveListing");
				}
			});
		},
		updateChooser: function() {
			// update choosers
			var listDef = BackAgent.FavoritePanel._listDef;
			var div = $("FavoriteListChooseItems");
			if (div) {
				var divText = "";
				listDef.each(function(def) {
					divText += "<p><a href=\"/help/support/browser/\" onclick=\"BackAgent.FavoritePanel.ListChange.select('" + def.value + "');return false;\">" + def.text + " (" + def.items.length + ")</a></p>";
				});
				div.update(divText);
			}
		},
		updatePicker: function() {
			// update choosers
			var listDef = BackAgent.FavoritePanel._listDef;
			var oldSel = $("FavoriteListPickID");
			if (oldSel) {
				var sel = oldSel.cloneNode(false);
				oldSel.parentNode.replaceChild(sel, oldSel);
				listDef.each(function(def) {
					sel.options[sel.options.length] = new Option(def.text, def.value);
				});
			}
		},
		updateStats: function() {
			if ($("FavoriteSummaryMLSCount")) {
				var count = BackAgent.FavoritePanel._mlsNums.length;
				var s = (count != 1) ? "s" : "";
				var text = count + " saved listing" + s + ".";
				$("FavoriteSummaryMLSCount").update(text);
			}
			if ($("FavoriteSummaryMLSTotal")) {
				var count = BackAgent.FavoritePanel._mlsTotal;
				var s = (count != 1) ? "s" : "";
				var text = count + " saved listing" + s + ".";
				$("FavoriteSummaryMLSTotal").update(text);
			}
			if ($("FavoriteSummaryListCount")) {
				var count = BackAgent.FavoritePanel._listDef.length;
				var s = (count != 1) ? "s" : "";
				var text = count + " list" + s + ".";
				$("FavoriteSummaryListCount").update(text);
				$("FavoriteSummaryListCount")[(count > 1) ? "show" : "hide"]();
			}
			if ($("FavoritePanelMultiHelp")) {
				var count = BackAgent.FavoritePanel._listDef.length;
				$("FavoritePanelMultiHelp")[(count > 1) ? "show" : "hide"]();
			}
		}
	}
};
Event.observe(window, "load", BackAgent.FavoritePanel.init.bind(BackAgent.FavoritePanel));

