var map;

$(document).ready(function() {
    // Dropdown code - http://css-tricks.com/simple-jquery-dropdowns/
    $("ul#topnav li").hover(function() {
        $(this).addClass("hover");
        $('ul:first',this).css('visibility', 'visible');
    }, function() {
        $(this).removeClass("hover");
        $('ul:first',this).css('visibility', 'hidden');
    });
    
  $('#mapSearch input').bind("click", function(e) {
      updateMapCount(e);
      ionMap.poiPropsLoad();
    });
  $('#mapSearch select').bind("change", function(e) {
      updateMapCount(e);
      ionMap.poiPropsLoad();
    });

	$('#homeSearch .input').bind("click change",function(e){

		////////////////////////////////////////////////////////////////////////
		// The 'change' event wont fire in IE until
		// that item loses focus, so we bind the items to pick up on multiple
		// events (change & click) to accommidate IE's stupidity.  But now we
		// need to filter out irrelevant events for the drop downs so the form
		// isn't submitted twice and therefor more than likely stall out.
		//
		// Chris Steimonts 10/28/2009 7:40 AM PST
		//
		switch(this.tagName)
		{
			case "INPUT":
				if(e.type != "click") return;
				break;

			case "SELECT":
				if(e.type != "change") return;
				break;
		}

		$('#propCount').html('<img src="'+$('#homeSearch').attr('imgsrc')+'" style="margin-top:11px;" />');

		// Serialize our form and submit it via ajax
		var mrForm = $('#homeSearch');

		jQuery.ajax({
			data: mrForm.serialize(),
			url: $('#homeSearch').attr('qs_target'),
			type: 'POST',
			timeout: 4000,
			error: function() {
				$('#propCount').html("<div style='font-size:9px;font-weight:bold;padding-top:4px;'>Busy,<br />try&nbsp;again</div>");
			},
			success: function(r) {
				if (r == '')
					$('#propCount').html('0');
				else
				{
					$('#propCount').html(r);
				}
			}
		}); // ajax
	});

	$('#search_form .input').bind("click change keypress",function(e){
		////////////////////////////////////////////////////////////////////////
		// The 'change' event wont fire in IE until
		// that item loses focus, so we bind the items to pick up on multiple
		// events (change & click) to accommidate IE's stupidity.  But now we
		// need to filter out irrelevant events for the drop downs so the form
		// isn't submitted twice and therefor more than likely stall out.
		//
		// Chris Steimonts 10/28/2009 7:40 AM PST
		//
		switch(true)
		{
			case (this.tagName == "INPUT" && $(this).attr("type") == "text"):
				if(e.type != "keypress" && e.type != "change") return;
				break;

			case this.tagName == "INPUT":
				if(e.type != "click") return;
				break;

			case this.tagName == "SELECT":
				if(e.type != "change") return;
				break;
		}

		$('#propCount').html('<img src="'+$('#search_form').attr('imgsrc')+'" style="margin-top:21px;" />');

		// Serialize our form and submit it via ajax
		var mrForm = $('#search_form');

		jQuery.ajax({
			data: mrForm.serialize(),
			url: $('#search_form').attr('qs_target'),
			type: 'POST',
			timeout: 4000,
			error: function() {
				$('#propCount').html("<div style='font-size:9px;font-weight:bold;padding-top:14px;text-align:center;'>Busy,<br />try&nbsp;again</div>");
			},
			success: function(r) {
				if (r == '')
					$('#propCount').html('0');
				else
				{
					$('#propCount').html(r);
				}
			}
		}); // ajax
	});
});

// These two are for prop details
function statusOn(txt, lft, wid)
{
  $('#btn_prop_title').show();
  $('#btn_prop_title').html(txt);
  $('#btn_prop_title').css('left', lft+'px');
  $('#btn_prop_title').css('width', wid+'px');
}
function statusOff()
{
  $('#btn_prop_title').hide();
  $('#btn_prop_title').html('');
  $('#btn_prop_title').css('width', '0');
  $('#btn_prop_title').css('left', '0');
}

// Subdivision show/hide in community dropdowns
function showSubs(parentId)
{
  $('.child'+parentId).show();
  $('#show'+parentId).hide();
  $('#hide'+parentId).show();
}
function hideSubs(parentId)
{
  $('.child'+parentId).hide();
  $('#show'+parentId).show();
  $('#hide'+parentId).hide();
}

function openArea(what, areaid)
{
  $('#commSelect').val(what+'|'+areaid).attr("selected", "selected");
  $('.buyCommList ul').removeClass('current');
  $('#area'+areaid).addClass('current');
  $('.areaDetails:visible').slideUp('normal', function() {
    $(".areaDetails[name='"+what+"']").show('slow');
  });
}

function openComboArea(what)
{
  var arr = what.split('|');
  openArea(arr[0], arr[1]);
}

// Closing Costs calculator
function compute( ) {
  var financed = parseInt($('#financed').val());
  var rate = parseInt($('#rate').val());

  if (financed > 1)
  {
    // Buyer
    $('#stamptax').html( Math.round((financed / 100) * 0.35) );
    $('#intangible').html( Math.round((financed / 1000) * 2) );
    var totalBuyLow = $('#stamptax').html() - - $('#intangible').html() - - 500 - - 400 - - 40;
    var totalBuyHigh = totalBuyLow - - 200 - - 20 - - 50;
    $('#totalbuy').html("$"+totalBuyLow+" to $"+totalBuyHigh+"<br /><span style=\"font-size: 0.7em;\">(plus Recording Fees, Taxes and Insurance and other fees)<\/span>");

    // Seller
    $('#stamptaxdeed').html( Math.round((rate * 7) / 1000 ));

    var ownins = 0;
    if (rate <= 100000)
    {
      ownins = Math.round((rate * 5.75) / 1000);
    }
    if (rate > 100000)
    {
      ownins = Math.round((100000 * 5.75) / 1000);
      ownins += Math.round(((rate - 100000) * 5.00) / 1000);
    }
    if (rate > 1000000)
    {
      ownins += Math.round(((rate - 1000000) / 1000) * 250);
    }
    $('#ownerins').html( ownins );

    var totalSellLow = $('#stamptaxdeed').html() - - $('#ownerins').html() - - 70 - - 600;
    var totalSellHigh = totalSellLow - - 80 - - 50;
    $('#total').html("$"+totalSellLow+" to $"+totalSellHigh +"<br /><span style=\"font-size: 0.7em;\">(plus commissions and any other fees)<\/span>");
  } else {
    // Nuthin'
    $('#stamptax').html('--');
    $('#intangible').html('--');
    $('#totalbuy').html('$--');
    $('#stamptaxdeed').html('--');
    $('#ownerins').html('--');
    $('#total').html('$--');
  }
}

/*** Review below this line ***/

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...
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();
    map.setMapType(G_HYBRID_MAP);

    // 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);
}
function popUpScroll(url, x, y)
{
  if (isIE() == true)
  {
    y += 40;
  }
    var args = "scrollbars=1,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';
}


// MAP SEARCH FORM live search number updater
function updateMapCount(e){
		// Copying this from Mr. Steimonts' fine code above
		switch(this.tagName)
		{
			case "INPUT":
				if(e.type != "click") return;
				break;
			case "SELECT":
				if(e.type != "change") return;
				break;
		}

		$('#propCount').html('<img src="'+$('#mapSearch').attr('imgsrc')+'" style="margin-top:11px;" />');

		// Serialize our form and submit it via ajax
		var mrForm = $('#mapSearch');

		jQuery.ajax({
			data: mrForm.serialize(),
			url: $('#mapSearch').attr('qs_target'),
			type: 'POST',
			timeout: 4000,
			error: function() {
				$('#propCount').html("<div style='font-size:9px;font-weight:bold;padding-top:4px;'>Busy,<br />try&nbsp;again</div>");
			},
			success: function(r) {
				if (r == '')
					$('#propCount').html('0');
				else
				{
					$('#propCount').html(r);
				}
			}
		}); // ajax
	}