$(function(){
	jQuery.ajaxSettings.traditional = true;
	
	// date picker
	$(".datepicker").livequery(function(){
		$(this).datepicker({ showOn:'both', buttonImage:'/images/calendar.gif', buttonImageOnly:true, duration:"" });
	});

	// multiple select
	$(".multiselect").multiSelect();
	
	// input hints
	$("input[title!='']").hint();
	
	// towns/villages expand/contract
	$("a.county").click(function(){
		var $this = $(this), isOpen = $this.hasClass("expand");
		$this.addClass( isOpen ? 'contract' : 'expand' ).removeClass( isOpen ? 'expand' : 'contract' ).nextUntil('div').next().toggle();
		return false;
	});
	$("input.town").click(function(){
		var villagecontainer = $(this).parent().next("div.village-container");
		
		if(this.checked)
			{ villagecontainer.show().find("input:checkbox").attr("checked", "checked"); }
		else
			{ villagecontainer.hide().find("input:checkbox").removeAttr("checked"); }
		
		return true;
	});
	
	// check all towns
	$("#check-all-towns").click(function(){
		var toDisable = this.name ? this.name : false;
		var subcontainers = $("#select-towns div");
		var checkboxes = subcontainers.find("input:checkbox");
		subcontainers.show();
		checkboxes.attr("checked","checked");
		if(toDisable){ checkboxes.attr("disabled","disabled"); }
		return false;
	});
	
	// uncheck all towns
	$("#uncheck-all-towns").click(function(){
		$("div.county-container div").hide(); // contracts the village divs if they exist
		$("#select-towns").find("input:checkbox").removeAttr("checked").removeAttr("disabled");
		return false;
	});
	
	// detail page photos
	$("#detailContainer").find("#photos a").click(function(e){
		$("#placeholder")[0].src = this.href;
		e.preventDefault();
	});
	
	// login dialog
	$('a.login').click(function(){
		var referer = this.name, $dialog = $("#modal-login"), $warning = $dialog.find("#warning");
		
		$('#modal-login')
		.dialog({ 
			width:400,
			height:275,
			title:'Login to MLS-Navigator',
			modal:true, 
			buttons:{
				"Login": function(){ $dialog.find("form").submit(); },
				"Close": function(){ $(this).dialog("close"); }
				}
			})
		.show()
		.dialog('open')
		.find("form")
		.ajaxForm({ 
			success: function(responseText, statusText){
				responseText = $.trim(responseText);
				var response = responseText.split('|'), success = response[0], refresh = response[1];

				if(success === 'false'){
					alert('Unable to find your username and password combination.  Please try again.');
				} else {
					('#modal-login').dialog('close');
					
					if(refresh === 'true'){
						window.location.reload(); 
					} else { 
						$('#modal-save-search').show().dialog('open'); 
					}
				}
			}
		})
		.find("input[name='referer']")
		.val(referer);
		
		// toggle the warning if the referer is anything but login.  login means that just the 'login' link was clicked.
		if(referer !== 'login'){
			$warning.show();
			if(referer === 'savesearch')
				$warning.find('span').html('save searches');
			else if(referer === 'address')
				$warning.find('span').html('view this address');
			else if(referer === 'makedailyalert')
				$warning.find('span').html('subscribe to DailyAlert!');
		} else {
			$warning.hide();
		}
		
		return false;
	});
	
	
	// request more information dialogs - DEPRICATED 6/16/09
	/*
	$('.request-information').click(function(){
		var data = this.name.split("|");
		var mlsno = data[0];
		var feedID = data[1];
		$('body').append('<div id="modal-request-information">Please wait...</div>');
		$('#modal-request-information')
			.dialog({ title:'Request More Information', width:650, height:450 }, function(){ $(this).remove(); })
			.load('index.cfm?page=detail&action=request-more-information&ajax=true', { mlsno:mlsno, feedID:feedID })
			.dialog('open');
		return false;
	});*/

	// mortgage calculator
	/*
	$('.mortgage-calculator').click(function(){
		var price = $(this).attr('name');
		$('body').append('<div id="modal-mortgage-calculator">Please wait...</div>');
		$('#modal-mortgage-calculator')
			.dialog({ title:'Mortgage Calculator', width:550, height:500 }, function(){ $(this).remove(); })
			.load('index.cfm?page=detail&action=mortgage-calculator&ajax=true', { price:price })
			.dialog('open');
		return false;
	});*/
	
	// tell a friend
	/*
	$('.tellafriend').click(function(){
		var data = this.name.split("|");
		var mlsno = data[0];
		var feedID = data[1];
		$('body').append('<div id="modal-tellafriend">Please wait...</div>');
		$('#modal-tellafriend')
			.dialog({ title:'Tell a Friend', width:550, height:450 }, function(){ $(this).remove(); })
			.load('index.cfm?page=detail&action=tellafriend&ajax=true', { mlsno:mlsno, feedID:feedID })
			.dialog('open');
		return false;
	});
	*/
	
	// save search
	$('#modal-save-search').dialog({ width:600, height:125, modal:true, buttons:{"Close":function(){ $(this).dialog("close");} }}).dialog('close');
	$('a.savesearch').click(function(){
		$('#modal-save-search').show().dialog('open');
		return false;
	});

	// rename search
	$('#modal-rename-search').dialog({ width:600, height:100 }).dialog('close');
	$('.rename').click(function(){
		var id = $(this).attr('name');
		$('#modal-rename-search')
			.load('index.cfm?page=members&action=favorites&do=renamesearchmodal&ajax=true&id='+id+'&nocache='+Math.random())
			.show()
			.dialog('open');
		return false;
	});
	
	// make search dailyalert
	$('a.makedailyalert').click(function(){
		$('body').append('<div id="modal-makedailyalert" style="display:none;">Please wait...</div>');
		$('#modal-makedailyalert')
			.dialog({ width:500, height:200, title:'Make this Search Your DailyAlert!', modal:true, buttons:{"Close":function(){ $(this).dialog("close");}} })
			.load('index.cfm?page=dailyalert&action=modal-makedailyalert&ajax=true')
			.show()
			.dialog('open');
		return false;
	});
	
	// home page mls number auto complete
	$("#search-mlsno").find("input[name='mlsno']").autocomplete("index.cfm", {
		extraParams: {page:"listings", action:'autocomplete', ajax:true},
		delay: 10,
		minChars:1,
		max:25,
		cacheLength:10,
		formatItem: function(data){ return data[0]; },
		formatResult: function(data){ return data[0]; },
		selectFirst: false
	});
	
	// search form addlpropertytypes
	$("#search").find("input[name='propertytype']").click(function(){
		var checked = this.checked, proptype = $(this).attr("title"), scope = $("#search #addlpropertytype-"+proptype);
		
		if(checked)
			{ scope.show().find(":checkbox").attr("checked","checked"); } 
		else 
			{ scope.hide().find(":checkbox").removeAttr("checked"); }
	});
	
	// form validation
	$("#search, #dailyalert").submit(function(){
		var numpropertytypes = $(this).find("[name='propertytype']:checked").length;
		var numtowns = $(this).find("[name='towns']:checked,[name='town']:checked").length;
		
		if(numpropertytypes == 0){
			alert("Please choose at least one property type.");
			return false;
		}
		if(numtowns == 0){
			alert("Please choose at least one town.");
			return false;
		}
		
		return true;
	});

	// contact flag
	$("#contactflag").change(function(){
		var selected = $(this).find("option:selected").val();
		var $phone = $(this).siblings("span");

		// on phone or both...
		if(selected == "P" || selected == "B"){
			$phone.show();
		} else {
			$phone.val("").hide();
		}
	});

	// dialog
	$("a.dialog").live("click", function(e){
		// config exists in elements name attribute in JSON format.
		var config = (this.name.length) ? eval('(' + $(this).attr("name") + ')') : {};
		var params = (config.params) ? config.params : {};
		var w = parseInt(config.width) || 500;
		var h = parseInt(config.height) || 400;
		var modal = (config.modal) ? config.modal : true;
		var title = config.title || "MLS-Navigator";
		var d = $('<div id="dialog" class="center"><div style="font-size:20px;text-align:center;"><img src="/images/indicator1.gif" /><br />Loading, please wait...</div></div>').appendTo("body");

		d.load( $(this).attr("href")+"&ajax=true", params )
		 .dialog({width:w, 
			     height:h, 
			     title:title,
			     modal:modal,
			     close:function(ev,ui){ $(this).remove(); },
			     buttons:{ 
			     	"Close":function(){ $(this).dialog("close");}
			     }
			   })
		 .dialog("open");
		
		e.preventDefault();
	});
});

// legacy, depricated code
function checkUncheckVillages(townID){
	var parentTown = "town"+townID;

	$('.'+townID).each(function(){
		if( $('#'+parentTown).attr('checked') == true )
			$(this).attr('checked', 'checked');
		else
			$(this).removeAttr('checked');
	});
	
}

// ajax compare
function compare(action,mlsnumber,feedID,proptype,currentrow){
	var url = 'index.cfm?page=compare&action=ajax', remove = (action == 1) ? false : true;
	var $result = $('#result' + currentrow).html('<img src="/images/loader.gif" alt="Updating" /> Updating your compare list...');

	$.get(url, { mlsno:mlsnumber, feedID:feedID, proptype:proptype, ajax:true, nocache:Math.random(), remove:remove }, function(data){
		$result.html( $.trim(data) ); 
	});

	if(action === 1){
		$("#a"+currentrow).hide()
		$("#r"+currentrow).show()
		$("#add"+currentrow).removeAttr("checked");
		$("#remove"+currentrow).attr("checked","checked");
	} else {
		$("#r"+currentrow).hide()
		$("#a"+currentrow).show()
		$("#add"+currentrow).removeAttr("checked");
		$("#remove"+currentrow).removeAttr("checked");
	}
}


// picture toggler on detail page
/* depricated 1/25/09
function showPic(whichpic){
	document.getElementById('placeholder').src = whichpic.href;
	return false;
}
*/

// compare toggle
function ChangeExpandIcon(id){
	var thisimg = document.getElementById(id);
	
	if(String(thisimg.src).substring(String(thisimg.src).length, String(thisimg.src).length-15) == "tree_expand.gif")
		{ thisimg.src = "/images/tree_contract.gif"; } 
	else 
		{ thisimg.src = "/images/tree_expand.gif"; }
}

// compare toggle
function toggleNameVisible(name){
	var el = document.getElementsByName(name), s = "";

	for(var i=0, len=el.length; i<len; i++){
		s=el[i].style.display;
		el[i].style.display=(s==''||s=='none')?'block':'none';
	}}


