$(document).ready(function(){
	if (document.getElementById('skyline'))
	{
		swfobject.embedSWF(basePath+"flash/boston-skyline.swf", "skyline", "956", "167", "8.0.0", '#262626', {}, {wmode: "transparent"});
	}

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

	$("#propSearch INPUT[type='checkbox']").click(updateSearchNum);
  $("#propSearch INPUT[type='radio']").click(updateSearchNum);
  $("#propSearch SELECT").change(updateSearchNum);

	$('.my_login .saved_search .rename_title, .my_login .saved_search .close').click(function(){
		var id = $(this).attr("id");
		$(".saved_search span.message").html("");
		$("#title_div_"+id).slideToggle("slow");
	});

	$(".my_login .frame .row .check .checkbox").click(function(){
		if($(this).attr("checked"))
			$(".my_login .frame .row .check[prop_id="+$(this).attr('prop_id')+"]").css("background","#fbdd88");
		else
			$(".my_login .frame .row .check[prop_id="+$(this).attr('prop_id')+"]").css("background","#f1eeea");
	});

  $('a, button').focus(function(){ this.blur();} );
});

var updateSearchNum = function()
{
  $('#fullResults').html('<img src="'+$('#propSearch').attr('imgsrc')+'" style="margin-left: 28px;" />');

  // Serialize our form and submit it via ajax
  var mrForm = $('#propSearch');
  jQuery.ajax({
    data: mrForm.serialize(),
    url: $('#propSearch').attr('qs_target'),
    type: 'POST',
    timeout: 4000,
    error: function() {
      $('#fullResults').html('<div id="numResults">0</div>Listings found');
    },
    success: function(r) {
      if (r == '')
        $('#fullResults').html('<div id="numResults">0</div>Listings found');
      else
      {
        if (r == 1)
        {
          $('#fullResults').html('<div id="numResults">'+r+'</div>Listing found');
        } else {
          $('#fullResults').html('<div id="numResults">'+r+'</div>Listings found');
        }
      }
    }
  }); // ajax
}

function selectAll(cityList, toggler)
{
	$("div#"+cityList+" input").attr('checked', $('#'+toggler).attr('checked'));
}

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","inline");
			}
		}
	);
}

function removesearch(url,criteria,suffix)
{
	jQuery.post(url, {criteria : criteria},
		function(data){
			if(data >= 0)
			{
				$(".save_search"+suffix).css("display","inline");
				$(".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, width)
{
  if (GBrowserIsCompatible())
  {
    if (width == undefined) var width  = 315;
    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 showDiv(target)
{
	document.getElementById(target).style.display = 'block';
}
function hideDiv(target)
{
	document.getElementById(target).style.display = 'none';
}

switchTabs = function(selected_tab) {
  var tabs = ['forSale', 'pending', 'sold', 'rentals'];
  for (i in tabs) {
    $('#'+tabs[i]+'Data').hide();
    $('#'+tabs[i]).removeClass('selected');
  }
  $('#'+selected_tab+'Data').css('display', 'inline');
  $('#'+selected_tab).addClass('selected');
}
