
// initialize the page level events
$(document).ready(function() {

	$("button#updateButton","div#listingSearchMoreAreasPopup").click(function() {
		$("body").css({cursor:"wait"});

		// iterate through the selected checkboxes, create an object for each one,
		// and add it to the array that will be passed to the parent window.

		var inputs = $("#moreAreasContainer input:checked");

		var otherAreas = new Array();
		for (var i=0, n=inputs.length; i<n; i++) {
			var $checkbox = $(inputs[i]), $label = $checkbox.parent().children("label.checkbox");
			otherAreas[$checkbox.val()] = {"placeid":$checkbox.val(),"name":$label.text()};
		}

		// callers function
		if (window.parent) {
			var callback = $("#callbackHidden").val() || "setAreas";
			if (typeof window.parent[callback] == "function") {
				window.parent[callback](otherAreas);
			}
		}

		// close the more areas
		if(window.parent && window.parent.tb_remove) {
			window.parent.tb_remove();
		}
		else {
			window.close();
		}

		$("body").css({cursor:"default"});
	});

	$("button#cancelButton", "div#listingSearchMoreAreasPopup").click(function() {
		$("body").css({cursor:"wait"});

		// close the more areas popup
		if( window.parent && window.parent.tb_remove) {
			window.parent.tb_remove();
		}
		else {
			window.close();
		}

		$("body").css({cursor:"default"});
	});


	// tabs
	if ($("#moreAreasContainer", "div#listingSearchMoreAreasPopup").length > 0) {

		// load fist tab
		loadMoreAreas("/ajax/searcharea/getmoreareas/type/neighborhood/", "neighborhoods");

		// switching tabs
		$("div.view-nav-tabs ul#nav a").click(function() {
			var tabName = (this.parentNode.id || "").replace(/Tab$/, "");
			if(! $(this).hasClass("current") && tabName.length > 0) {

				// hide all divs
				$("#moreAreasContainer > div").hide();

				// show but only load once
				if ($("#" + tabName).show().html().length < 1) {
					loadMoreAreas(this.href, tabName);
				}

				// switch to tab 
				$("div.view-nav-tabs ul#nav a").removeClass("current").parent().removeClass("ui-tabs-selected");
				$(this).addClass("current").parent().addClass("ui-tabs-selected");
			}
			return false;
		});
	}
});

function loadMoreAreas(url, tab) {
	var selectedAreas = $("#selectedAreas").val() || "";

	if (selectedAreas.length > 0) {
		url = url + "areas/" + selectedAreas + "/";
		ajaxLoadContent(url, tab);
	}
}


