$(document).ready(function() {
	//
	jQuery("#search_form select").change(function(){
		jQuery(".listings_found strong").html("<img src='"+jQuery("#search_form").attr("imgsrc")+"' style='margin:0px 0px 5px 30px;' />");
		submitForm("search_form",ajaxUpdateLiveSearchCount,jQuery("#search_form").attr("qs_target"));
	});
});

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

// Handle rollover images - insert '_over' and take it out again
function rollover(target)
{
  if (document.getElementById(target).src.indexOf('_over') == -1) {
      newImg = document.getElementById(target).src.replace(/\.(.{3,4})$/g, "_over.$1");
      document.getElementById(target).src = newImg;
  }
}

function rollout(target)
{
  newImg = document.getElementById(target).src.replace(/\_over/g, "");
  document.getElementById(target).src = newImg;
}

/*** Property functions ***/
function loadGoogleMap(lat, lon, address, city, link)
{
  // Geocode if no lat/lng
  if (lat == 0 || lon == 0)
  {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address+" "+city}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK && results[0].types[0] == 'street_address') {
        lat = results[0].geometry.location.lat();
        lon = results[0].geometry.location.lng();
        loadGoogleMap(lat, lon, address, city, link);
      } else {
        // No lat/long or not accurate enough, sorry
        document.getElementById("propMap").style.display = 'none';
        document.getElementById("propMapBar").style.display = 'none';
      }
    });
  }

  // No lat/long?  Abort!
  if (lat == 0 || lon == 0)
  {
    return;
  }

  map = new google.maps.Map(document.getElementById('propMap'), {
    center: new google.maps.LatLng(lat, lon),
    zoom: 12,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    navigationControlOptions: {
      style: google.maps.NavigationControlStyle.SMALL
    }
  });

  // Make info window content
  var dirLink = "http://maps.google.com/maps?f=q&q=" + link;
  var balloonText  = '<div class="big" style="margin-bottom: 5px;"><b>' + address + "</b></div>";
  balloonText += city + "<br /><br />";
  balloonText += '<a href="' + dirLink + '" target="_blank">Get Directions</a>';

  mapInfoWindow = new google.maps.InfoWindow({content: balloonText});

  marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lon),
    map: map,
    title: address,
    clickable: true
  });

  google.maps.event.addListener(marker, 'click', function(e) {
    mapInfoWindow.open(map, marker);
  });
}

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

// 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);
}
// Popup window - this one has scrollbares, resizing, the whole 9
function popUpDeluxe(url, x, y)
{
  if (isIE() == true)
  {
    y += 40;
  }
    var args = "width=" + x + ",height=" + y + ",status=1,resizable=1,scrollbars=1,menubar=1,location=1";
    var date = new Date();
    var now = date.getTime();
    var newName = (now).toString(10);

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

// Popup a 'frame' - just a popup w/ more options and a standard width/height
function popFrame(url)
{
  if (isIE() == true)
  {
    var args = "width=780,height=640,resizable=1";
  } else {
    var args = "width=780,height=600,resizable=1";
  }
    var date = new Date();
    var now = date.getTime();
    var newName = (now).toString(10);

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

/** Send to box **/
var sendToTimer;
// Prop send-to box
function activateSendTo()
{
  clearTimeout(sendToTimer);
  showDiv('sendToBoxBg');
  showDiv('sendToBoxBg2');
  showDiv('sendToBoxBg3');
  showDiv('sendToBoxBg4');
  showDiv('sendToBox');
}

function setSendToTimer()
{
  sendToTimer = setTimeout(deactivateSendTo, 10000);
}

function deactivateSendTo()
{
  hideDiv('sendToBoxBg');
  hideDiv('sendToBoxBg2');
  hideDiv('sendToBoxBg3');
  hideDiv('sendToBoxBg4');
  hideDiv('sendToBox');
}

/*** 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 submitForm(form,callBackFunction,urlOverride)
{
	var formObj = jQuery("#"+form);
	var url = jQuery(formObj).attr("action");
	if(urlOverride)
		url = urlOverride;

	jQuery.ajax({
		data: formObj.serialize(),
		url: url,
		type: 'POST',
		timeout: 8000,
		error: function() {
			//alert("ERROR: Could not submit form.");
		},
		success: function(r) {
			if(callBackFunction)
				return callBackFunction(r);
			else
			{
				var response = eval('('+r+')');

				if(response.Error)
					alert(response.ErrorMessage);
				else
					alert(response.Message);
			}
		}
	}); // ajax
}

var ajaxUpdateLiveSearchCount = function(r){

	if (r == '' || r == '0')
		alert("ERROR: Ajax issues, please try again.");
	else
	{
		var response = eval('('+r+')');

		if(response.Error)
			alert(response.ErrorMessage);
		else
			jQuery(".listings_found strong").html(response.Message);
	}
}