$(document).ready(function(){
  
	if(typeof fixColumnHeight == 'function')
		fixColumnHeight(); 

  $('#forSale').click(function () { switchTabs('forSale'); });
  $('#pending').click(function () { switchTabs('pending'); });
  $('#sold').click(function () { switchTabs('sold'); });
  $('#rentals').click(function () { switchTabs('rentals'); });

    $("#first_date, #second_date").datepick({showOn: 'button', buttonImageOnly: true, buttonImage: ''+rel_path+'images/icon-date-picker.gif', minDate: +0, maxDate: '+1y'});

	$("input#first_date").change(function(){
		if($("input#second_date").attr('value') == "")
			$("input#second_date").attr('value',$("input#first_date").attr('value'));
	});
	
	$("#advancedSearch,.quick_advanced_search .close").click(function(){
		if($(".quick_advanced_search").css("display") == "block")
		{
			if ($("#advancedSearch").hasClass('modifySearch'))
			{
				$("#advancedSearch").css("background","url('"+rel_path+"images/btn-modify-search.png') no-repeat bottom left");
			} else {
				$("#advancedSearch").css("background","url('"+rel_path+"images/btn-advanced-search.png') no-repeat bottom left");
			}
			
		}
		else
		{
			advanced_quick_search();
			if ($("#advancedSearch").hasClass('modifySearch'))
			{
				$("#advancedSearch").css("background","url('"+rel_path+"images/btn-modify-search-on.png') no-repeat bottom left");
			} else {
				$("#advancedSearch").css("background","url('"+rel_path+"images/btn-advanced-search-on.png') no-repeat bottom left");
			}
		}
			
		$(".quick_advanced_search").slideToggle("slow");
	});
	
	$("#add_areas").click(function(){
		var areas = $('#areas').val();
		
		if(areas == null)
			return false;
		
		for(var i=0;i<areas.length;i++)
			if($("#selected_areas option[value='"+areas[i]+"']").length <= 0)
				if(areas[i].indexOf("c_") >= 0)
					$("#selected_areas").append("<option value='"+areas[i]+"'>"+areas[i].replace("c_","")+"</option>");
				else
					$("#selected_areas").append("<option value='"+areas[i]+"'>- "+areas[i]+"</option>");
				
		advanced_quick_search();
	});
	
	$("#areas").dblclick(function(){
		var areas = $('#areas').val();
		
		if(areas == null)
			return false;
		
		for(var i=0;i<areas.length;i++)
			if($("#selected_areas option[value='"+areas[i]+"']").length <= 0)
				if(areas[i].indexOf("c_") >= 0)
					$("#selected_areas").append("<option value='"+areas[i]+"'>"+areas[i].replace("c_","")+"</option>");
				else
					$("#selected_areas").append("<option value='"+areas[i]+"'>- "+areas[i]+"</option>");
				
		advanced_quick_search();
	});
	
	$("#remove_areas").click(function(){
		var areas = $('#selected_areas').val();
	
		if(areas == null)
			return false;
		
		for(var i=0;i<areas.length;i++)
			$("#selected_areas option[value='"+areas[i]+"']").remove();
			
		advanced_quick_search();
	});
	
	$("#login").mouseover(function(){
		if (isIE6() == false)
		{
			$('#weeLogin').css('top', '9px');
			if ($('#topSlider').is(':hidden'))
			{
				$('#topSlider').slideToggle();
				$('#qk_search').css('z-index', '10');
			}
		}	
	});
	
	$("#counties").change(function(){
		$("#areas").html("<option>Loading Areas...</option>");
		$.post($(this).attr("target"), {county : $(this).attr("value")},
			function(data){
				$("#areas").html(data);
			}
		);
	});
});

function closeTopLogin()
{
	$('#topSlider').slideToggle(function(){
		$('#qk_search').css('z-index', '1000');
		$('#weeLogin').css('top', '-900px');
	});
}

function advanced_quick_search()
{
	$('.results_wrapper .results .value').html('<img src="'+$('#quick_advanced_search_form').attr('imgsrc')+'" style="margin-top:5px;">');
	$('#selected_areas option').attr('selected','selected');

	$(".save_search_adv").css("display","block");
	$(".remove_search_adv").css("display","none");

	// Serialize our form and submit it via ajax
	var mrForm = $('#quick_advanced_search_form');
	jQuery.ajax({
		data: mrForm.serialize(),
		url: $('#quick_advanced_search_form').attr('qs_target'),
		type: 'POST',
		timeout: 8000,
		error: function() {
			$('.results_wrapper .results .value').html('<span style="font-size: 0.4em;">Busy, try&nbsp;again</span>');
		},
		success: function(r) {
			if (r == '')
				$('.results_wrapper .results .value').html('0');
			else
			{
				$('.results_wrapper .results .value').html(r);
			}
		}
	}); // ajax
}

function save_search_title(id)
{
	var mrForm = $('#title_form_'+id);
	jQuery.ajax({
		data: mrForm.serialize(),
		url: $('#title_form_'+id).attr("url"),
		type: 'POST',
		timeout: 2000,
		error: function() {
			$("#title_"+id+" span.message").html(" - Error in saving title, please try again...");
			$("#title_"+id+" span.message").css("color","#cd0210");
			$("#title_div_"+id).slideToggle("slow");
		},
		success: function(r) {
			$("#title_"+id+" span.text").html($("#title_form_"+id+" input[type=text]").attr('value'));
			$("#title_"+id+" span.message").html(" - Title has been saved");
			$("#title_"+id+" span.message").css("color","#04b908");
			$("#title_div_"+id).slideToggle("slow");
		}
	}); // ajax
}

function save_search_email(id)
{
	$(".saved_search span.message").html("");
	var mrForm = $('#email_form_'+id);
	jQuery.ajax({
		data: mrForm.serialize(),
		url: $('#email_form_'+id).attr("url"),
		type: 'POST',
		timeout: 2000,
		error: function() {
			$("#email_me_"+id+" span.message").html(" - Error, please try again");
			$("#email_me_"+id+" span.message").css("color","#cd0210");
		},
		success: function(r) {
			$("#email_me_"+id+" span.message").html(" - Saved");
			$("#email_me_"+id+" span.message").css("color","#04b908");
		}
	}); // ajax
}

function saveprop(url,prop_id)
{	
	jQuery.post(url, {},
		function(data){
			if(data >= 0)
			{
				$("#save_"+prop_id).css("display","none");
				$("#remove_"+prop_id).css("display","block");
			}
		}
	);
}

function removeprop(url,prop_id)
{	
	jQuery.post(url, {},
		function(data){
			if(data >= 0)
			{	
				$("#save_"+prop_id).css("display","block");
				$("#remove_"+prop_id).css("display","none");
			}
		}
	);
}

function savesearch(url,criteria,suffix)
{	
	jQuery.post(url, {criteria : criteria},
		function(data){
			if(data >= 0)
			{
				$(".save_search"+suffix).css("display","none");
				$(".remove_search"+suffix).css("display","block");
			}
		}
	);
}

function removesearch(url,criteria,suffix)
{
	jQuery.post(url, {criteria : criteria},
		function(data){
			if(data >= 0)
			{
				$(".save_search"+suffix).css("display","block");
				$(".remove_search"+suffix).css("display","none");
			}
		}
	);
}

// Replace a text field with a value
function replaceValue(target, defaultText, newValue)
{
	if (target.value == defaultText) target.value = newValue;
}

// Set left and sometimes top nav
function setNav(sideNav, topNav)
{	
	if (sideNav != undefined)
	{
		if (document.getElementById(sideNav)) {
			document.getElementById(sideNav).className = 'current';
		}
	}
	if (topNav != undefined)
	{
		if (document.getElementById(topNav)) {
			document.getElementById(topNav).className = 'current';
		}
	}	
}

// Used to convert into square metres... this is like openBlogStory but with inline instead of block
function convert(oldNbusted, newNfresh)
{
	if (document.getElementById(oldNbusted) && document.getElementById(newNfresh))
	{
		toast = document.getElementById(oldNbusted);
		fresh = document.getElementById(newNfresh);
		if (toast.style.display == 'inline')
		{
			toast.style.display = 'none';
			fresh.style.display = 'inline';
		} else {
			toast.style.display = 'inline';
			fresh.style.display = 'none';
		}
	}	
}

/*** Property functions ***/
function loadGoogleMap(lat, lon, address, citystate, dir)
{
  if (GBrowserIsCompatible())
  {
    var width  = 242;
    var height = 226;

    map = new GMap2(document.getElementById("propMap"), { size: new GSize(width,height) } );
    map.setUIToDefault();

    // Make info window content
    var fullAddress = address + ' ' + citystate;
    var dirLink = "http://maps.google.com/maps?f=q&q=" + fullAddress;
    var balloonText  = '<div style="margin-bottom: 5px;"><b>' + address + "</b></div>";
    balloonText += citystate;

    if (dir == true)
    {
      balloonText += '<br /><br /><a href="' + dirLink + '" target="_blank">Get Directions</a>';
    }

    map.setCenter(new GLatLng(lat, lon), 16);
    var marker = new GMarker(map.getCenter());

    GEvent.addListener(marker, 'click', function(){
      marker.openExtInfoWindow(
        map,
        "extInfoWindow",
        balloonText,
        {beakOffset: 2}
      );
    });
    map.addOverlay(marker);
  }
}

function showAddress(address, balloonText)
{
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          // Crap, it's not there, erase the map!
          document.getElementById("propMap").style.display = 'none';
        } else {
          map.setCenter(point, 15);
          var marker = new GMarker(point);
          map.addOverlay(marker);
          marker.bindInfoWindowHtml(balloonText);
        }
      }
    );
  }
}

/*********************/

// Everybody's friend, the Dreamweaver Image Preloader
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

// Popup window - give me the url, width, and height, and I'll give you a popup
function popUp(url, x, y)
{
	if (isIE() == true)
	{
		y += 40;
	}
    var args = "width=" + x + ",height=" + y;
    var date = new Date();
    var now = date.getTime();
    var newName = (now).toString(10);

    window.open(url,newName,args);
}


/*** Form checking functions ***/
function checkField (val, field)
{	
    var error = "";
    if (val == "")
    {
      error = "You must enter a value in the " + field + " field.\n";
    }
    return error;
}
function checkEmail(val, field)
{	
    var error = "";
    if ((val == "" || val.length < 3) ||
        (val.indexOf("@") == "-1") ||
        (val.indexOf(".") == "-1"))
    {
        error = "Please enter a valid " + field + " address.\n";
    }
    return error;
}

// For popup thing
function isIE()
{
	//Detect IE5.5+
	version=0;
	if (navigator.appVersion.indexOf("MSIE")!=-1) {
		temp=navigator.appVersion.split("MSIE");
		version=parseFloat(temp[1]);
	}
	if (version >= 5.5)
	{ //NON IE browser will return 0
		return true;
	} else {
		return false;
	}	
}

function isIE6()
{
	//Detect <= IE6
	version=0;
	if (navigator.appVersion.indexOf("MSIE")!=-1) {
		temp=navigator.appVersion.split("MSIE");
		version=parseFloat(temp[1]);
		if (version <= 6)
		{
			return true;
		}	

	}
	return false;
}

function showDiv(target)
{
	document.getElementById(target).style.display = 'block';
}
function hideDiv(target)
{
	document.getElementById(target).style.display = 'none';
}

function swapRental(val, saleMn, saleMx, rentMn, rentMx)
{
	if (val == 'RN' && $('#'+saleMn).css('display') != 'none')
	{
		// Show rental prices
		$('#'+saleMn).hide();
		$('#'+saleMx).hide();
		$('#'+saleMn).attr('name', 'mn!price_sale');
		$('#'+saleMx).attr('name', 'mx!price_sale');
		
		$('#'+rentMn).show();
		$('#'+rentMx).show();
		$('#'+rentMn).attr('name', 'mn!price');
		$('#'+rentMx).attr('name', 'mx!price');
	} else if (val != 'RN' && $('#'+rentMn).is(":visible"))
	{
		// Show sale prices
		$('#'+saleMn).show();
		$('#'+saleMx).show();
		$('#'+saleMn).attr('name', 'mn!price');
		$('#'+saleMx).attr('name', 'mx!price');
		
		$('#'+rentMn).hide();
		$('#'+rentMx).hide();
		$('#'+rentMn).attr('name', 'mn!price_rent');
		$('#'+rentMx).attr('name', 'mx!price_rent');
	}
}