$(function() {
	$("a#adv_search").click(function() {
		showAdvancedSearchForm();
		return false;
	});
	
	$(".gallery img.thumb").live("mouseover", function() {
		showHover($(this));
	});
	
	$(".gallery img.thumb").live("mouseout", function() {
		hideHover($(this));
	});
	
	$("a#mls_search").click(function() {
		showMLSSearchForm();
		return false;
	});
	
	$("div#mls_search_form #close_btn").click(function() {
		hideMLSSearchForm();
		return false;
	});
	
	$("a#search_btn").click(function() {
		showSearchResults();
		return false;
	});
	
	bindActions();
	
	$("#searchType").change(function() {
		updateCities($(this), "#searchCity");
	});

	$("#mls_search_btn").click(function() {
		$("#mls_search_frm").submit();
	});
	
	$("#featuredListings").jcarousel({
		scroll: 1,
		initCallback: featuredListingsCarousel,
		auto: 7,
		animation: 'fast',
		wrap: 'circular'
	});

	$(".button, input:submit").button();
	
	preloadImages();
});

function bindActions() {
	$("a.saveListing, a.removeSavedListing").unbind('click');
	
		
	$("a.saveListing, a.removeSavedListing").click(function() {
		saveListing($(this));
		return false;
	});
	
	$("a.saveSearch, a.removeSavedSearch").unbind('click');
	
	$("a.saveSearch, a.removeSavedSearch").click(function() {
		saveSearch($(this));
		return false;
	});
	
	$("a.share").unbind('click');
	
	$("a.shareListing").click(function() {
		shareListing($(this));
		return false;
	});
	
	$("input.alertSearch").unbind('click');
	
	$("input.alertSearch").click(function() {
		alertSearch($(this));
	});
	
	$("a.preview").unbind('click');
	
	$("a.preview").click(function() {
		showPreview($(this));
		return false;
	});
}

function showAdvancedSearchForm() {
	if (!$('#advSearchDialog').length) {
        $('body').append('<div id="advSearchDialog" class="dialog" title="Advanced Search"></div>');

        $.ajax({
			url: "/ajax/adv_search.php?" + ((typeof advSearchQueryString !== "undefined") ? advSearchQueryString : ""),
			dataType: 'html',
			type: 'get',
			success: function(html) {
				$("#advSearchDialog").html(html);
				showAdvDialog();
				$(".button, input:submit").button();
			}
		});
	} else {
		showAdvDialog();
	}
	
	function showAdvDialog() {
		$("#advSearchDialog").dialog({
			title: "Advanced Search",
			width: 500,
			height: 200,
			resizable: false,
			modal: true
		});
	}
}

function showMLSSearchForm() {
	if (jQuery.browser.msie) {
		$('#mls_search_form').show();
		$("#mls_search_form input#mls_no").focus();
	} else {
		$('#mls_search_form').slideDown("fast", function() {
			$("#mls_search_form input#mls_no").focus();
		});
	}
}

function hideMLSSearchForm() {
	if (jQuery.browser.msie) {
		$('#mls_search_form').hide();
	} else {
		$('#mls_search_form').slideUp("fast");
	}
}

function showSearchResults() {
	$.ajax({
		url: "ajax/search.php",
		success: function(data) {
			$("div.interiorcontent").html(data);
		}
	});
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    
    return this;
}

function showPreview(obj) {
	if (!$('#previewDialog').length) {
        $('body').append('<div id="previewDialog" class="dialog" title="Preview"><div id="content"></div></div>');
	}
	
	$.ajax({
		url: "/ajax/preview.php?id=" + obj.attr("id") + "&t=" + obj.attr("type"),
		dataType: 'json',
		success: function(data) {
			$("#previewDialog #content").html("");
			$("#previewDialog #content").html(data.content);
			
			$("#previewDialog").dialog({
				title: data.title,
				width: 575,
				height: 300,
				resizable: false,
				open: function() {
					bindActions();
				}
			});
		}
	});
}

function saveListing(obj) {
	var cleared = true;

	if ((obj.html().match(/saved/i)) || (obj.html().match(/remove/i))) {
		cleared = confirm("Are you sure you want to remove this saved listing?");
	}
	
	if (cleared) {
		$.ajax({
			url: "/ajax/save_listing.php?id=" + obj.attr("id") + "&t=" + obj.attr("type"),
			dataType: 'json',
			success: function(data) {
				if (data.authorized) {
					if (data.saved) {
						obj.html(obj.html().replace("Save", "Saved"));
					} else {
						obj.html(obj.html().replace("Saved", "Save"));
						if (obj.closest("#tabs").html()) {
							obj.closest(".listing").fadeOut("fast", function() {
								obj.closest(".listing").remove();
								$("#tabs").tabs("load", 0);
							});
						}
					}
					showNotification(data.content);
				} else {
					showDialog(data.title, data.content, 800, 350);
				}
			}
		});
	}
}

function saveSearch(obj) {
	var cleared = true;

	if ((obj.html().match(/saved/i)) || (obj.html().match(/remove/i))) {
		getConfirmation(
			"Are you sure you want to remove this search?", 
			function(){
				cleared =  true;
			}, 
			function(){
				cleared =  false;
			}
		);
		console.log(cleared);
	}
	
	if (cleared) {
		$.ajax({
			url: "/ajax/save_search.php?q=" + escape(window.location.href),
			dataType: 'json',
			success: function(data) {
				if (data.authorized) {
					if (data.saved) {
						obj.html(obj.html().replace("Save", "Saved"));
					} else {
						obj.html(obj.html().replace("Saved", "Save"));
						if (obj.closest("#tabs").html()) {
							obj.closest(".search").fadeOut("fast", function() {
								obj.closest(".search").remove();
								$("#tabs").tabs("load", 1);
							});
						}
					}
					showNotification(data.content);
				} else {
					showDialog(data.title, data.content, 800, 350);
				}
			}
		});
	}
}

function shareListing(obj) {
	if (!$('#shareDialog').length) {
        $('body').append('<div id="shareDialog" class="dialog" title="Share"><div id="content">coming soon...</div></div>');
	}
	
	$.ajax({
		url: "/ajax/share.php?id=" + obj.attr("id") + "&t=" + obj.attr("type"),
		dataType: 'json',
		success: function(data) {
			$("#shareDialog #content").html("");
			$("#shareDialog #content").html(data.content);
			
			$("#shareDialog").dialog({
				title: data.title,
				width: 500,
				height: 500,
				resizable: false,
				modal: true,
				buttons: {
					Send: function() {
						$("#share_frm").submit();
					}
				}
			});
		}
	});
}

function sendSharedListing() {
	// TODO: add spinner
	
	alert('spinner needed');
	
	$.ajax({
		url: "/ajax/share.php?" + $("#share_frm").serialize(),
		dataType: 'json',
		success: function(data) {
			$("#shareDialog").dialog("close");
			showNotification(data.content);
		}
	});
}

function alertSearch(obj) {
	$.ajax({
		url: "/ajax/save_search.php?alert=" + obj.val() + "&checked=" + obj.is(":checked") ,
		dataType: 'json',
		success: function(data) {
			if (data.saved) {
				showNotification(data.content);
			} else {
				showWarning(data.content);
			}
		}
	});
}

function updateCities(type, citySel) {
	var city = $(citySel);
	var currentCity = city.val();
	
	$.ajax({
		url: "/ajax/search_options.php?option=city&type=" + type.val(),
		dataType: 'json',
		success: function(data) {
			city.find("option").remove();
			city.append($('<option value="">Any</option>'));
			
			$.each(data, function(key, val) {
				var option = $("<option />");
				option.text(val.text);
				option.val(val.value);
				if ( val.value == currentCity ) {
					option.attr("selected", "selected");
				}
				city.append(option);
			});
		}
	});
}

function featuredListingsCarousel(c) {
	c.clip.hover(function() {
		c.stopAuto();
	}, function() {
		c.startAuto();
	});
	
	$("#featuredListingsNav #featuredListingsPrev").click(function() {
		c.prev();
    });
    
	$("#featuredListingsNav #featuredListingsNext").click(function() {
        c.next();
    });
    
	$("#featuredListingsNav .featuredListingsIndex").click(function() {
		c.scroll(parseInt($(this).html()) - 1);
		return false;
    });
}

function showDialog(title, msg, w, h, resizable) {
	if (!$("#dialog").length) {
        $("body").append('<div id="dialog" title="'+ title +'"><div id="content"></div></div>');
	}
	
	$("#dialog #content").html(msg);
	
	if (!w) {
		w = 300;
	}
	
	if (!h) {
		h = 200;
	}
	
	if (!resizable) {
		resizable = false;
	}
	
	$("#dialog").dialog({
		width: w,
		height: h,
		title: title,
		resizable: resizable,
		modal: true
	});
}

function hideDialog() {
	$("#dialog").dialog("close");
}

function showWarning(msg) {
	if (!$("#warningDialog").length) {
        $("body").append('<div id="warningDialog" class="dialog" title="Warning"><div id="content"></div></div>');
	}
	
	$("#warningDialog #content").html('<span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-alert"></span>' + msg);
	
	$("#warningDialog").dialog({
		width: 350,
		height: 250,
		resizable: false,
		modal: true,
		buttons: {
			Ok: function() {
				$(this).dialog("close");
			}
		}
	});
}

function showNotification(msg) {
	if (! $("#notification-shade").html()) {
		$(document.body).append('<div id="notification-shade"><span id="msg"></span><span class="ui-icon ui-icon-closethick pointer close"></span></div>');
	}
	
	$("#notification-shade #msg").html(msg);
	$("#notification-shade").slideDown("fast");
	
	$("#notification-shade .close").click(function() {
		$("#notification-shade").clearQueue();
		$("#notification-shade").slideUp("slow");
	});
	
	$("#notification-shade").delay(10000).slideUp("slow");
}

function showHover(obj) {
	var i = new Image();
	i.src = obj.attr('src').replace("thmb", "disp");
	
	if (!$("#overlay").length) {
        $("body").append('<div id="overlay"><div id="content"></div></div>');
	}
	
	$("#overlay").css("top", obj.offset().top );
	$("#overlay").css("left", obj.offset().left - i.width - 12);
	$("#overlay").width(i.width + 10);
	$("#overlay").height(i.height + 10);
	$("#overlay #content").html('<img src="' + i.src + '" />');
	$("#overlay").show();
}

function hideHover(obj) {
	$("#overlay").hide();
}

function preloadImages() {
	$("body").find("img").each(function() {
		if ($(this).attr("src").indexOf("thmb") != -1) {
			var i = new Image();
			i.src = $(this).attr('src').replace("thmb", "disp");
			i.src = $(this).attr('src').replace("thmb", "large");
		}
	});
}


function getConfirmation(msg, okCallback, cancelCallback) {
	if (!$("#confirmDialog").length) {
        $("body").append('<div id="confirmDialog" title="Confirm"><div id="content"></div></div>');
	}
	
	$("#confirmDialog #content").html(msg);
	
	$("#confirmDialog").dialog({
		width: 350,
		height: 150,
		title: "Confirm",
		resizable: false,
		modal: true,
		buttons: {
			OK: function() {
				if (typeof okCallback == 'function') {
					okCallback.call();
				}
				$(this).dialog("close");
			},
			Cancel: function() {
				if (typeof cancelCallback == 'function') {
					cancelCallback.call();
				}
				$(this).dialog("close");
			}
		}
	});
}

function showLogin() {
	alert('showLogin');
}

