var map = null;
var geocoder = null;

var currNav = ''; // Set current nav id

// 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 (target != 'nav_properties')
    {
        rollout('nav_properties');
        hideDiv('subnav');
    }
    if (target != 'nav_about')
    {
        rollout('nav_about');
        hideDiv('subnavAbout');
    }

    if (target != currNav)
    {
        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)
{
    if (target != currNav)
    {
        newImg = document.getElementById(target).src.replace(/\_over/g, "");
        document.getElementById(target).src = newImg;
    }
}

// Change the color of a particular id
function subnavSelect(target, color)
{
	if (color == undefined)
	{
		color = "#026331";
	}
	document.getElementById(target).style.color = color;
}

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

// Set active nav item
function setNav(target)
{
	rollover(target);
    currNav = target;
}

// 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];}}
}

// Slide open a div w/ scriptaculous
// Note that we need to include scriptaculous and prototype before trying this
function slideOpen(target)
{
    Effect.toggle(target, 'slide');
}

// Popup window - give me the url, width, and height, and I'll give you a popup
function popUp(url, x, y)
{
    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 checkFieldFr (val, field)
{
    var error = "";
    if (val == "")
    {
      error = "Vous devez écrire une valeur dans le domaine " + 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;
}
function checkEmailFr(val, field)
{
    var error = "";
    if ((val == "" || val.length < 3) ||
        (val.indexOf("@") == "-1") ||
        (val.indexOf(".") == "-1"))
    {
        error = "Veuillez écrire une adresse " + field + " valide.\n";
    }

    return error;
}


// Hide one div, unhide another
function openBlogStory()
{
	document.getElementById('storyPreview').style.display = 'none';
	document.getElementById('storyFull').style.display = 'block';
}

// Swap the current image number to another number
function swapNum(num)
{
	document.getElementById('curImgNum').innerHTML = num;
}

// Used to convert into square metres... this is like openBlogStory but with inline instead of block
function convert(oldNbusted, 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';
	}
}

function loadGoogleMap(address, citystate, title, lang, lat, lon)
{
  if (GBrowserIsCompatible())
  {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());

    geocoder = new GClientGeocoder();
    showAddress(address, citystate, title, lang, lat, lon);
  }
}

function showAddress(addressLine, citystate, title, lang, lat, lon)
{
	if (lang == undefined)
	{
		lang = 'en';
	}
  if (geocoder) {
    var address = addressLine + ' ' + citystate;
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point && lat == undefined) {
          // Crap, it's not there, erase the map!
          document.getElementById("mapHolder").style.display = 'none';
        } else {
        	if (lang == 'fr')
        	{
	        	var dirLink = "http://maps.google.fr/maps?f=q&hl=fr&q=" + address;
	        	var balloonText  = '<div class="black biggish" style="margin-bottom: 5px;"><b>' + title + "</b></div>";
	          balloonText += addressLine + "<br />" + citystate + "<br /><br />";
	          balloonText += '<a href="' + dirLink + '" target="_blank"><img src="images/car.gif" width="13" height="12" alt="" align="absmiddle" border="0" /></a>&nbsp;&nbsp;';
	          balloonText += '<a href="' + dirLink + '" target="_blank" class="uline">Comment s\'y rendre</a>';
        	} else {
	        	var dirLink = "http://maps.google.com/maps?f=q&q=" + address;
	        	var balloonText  = '<div class="black biggish" style="margin-bottom: 5px;"><b>' + title + "</b></div>";
	          balloonText += addressLine + "<br />" + citystate + "<br /><br />";
	          balloonText += '<a href="' + dirLink + '" target="_blank"><img src="images/car.gif" width="13" height="12" alt="" align="absmiddle" border="0" /></a>&nbsp;&nbsp;';
	          balloonText += '<a href="' + dirLink + '" target="_blank" class="uline">Get Directions</a>';
        	}
          if (lat && lon)
          {
          	map.setCenter(new GLatLng(lat, lon), 15);
          } else {
          	map.setCenter(point, 15);
          }
          var marker = new GMarker(map.getCenter());
          map.addOverlay(marker);
          marker.openInfoWindowHtml(balloonText);
        }
      }
    );
  }
}

// AJAX call to save property favorite
function saveFave(id, basePath, saveText)
{
    document.getElementById('fave' + id).innerHTML = saveText;
    var response = new Ajax.Request(basePath + 'property-details/add/' + id,
    {
      onSuccess: function(transport) {
      	document.getElementById('faveIcon' + id).src = basePath + 'images/added_to_faves.gif';
        document.getElementById('fave' + id).innerHTML = transport.responseText;
      }
    });
}

// AJAX call to save search - no id necessary, we use a CookieForm, yay!
function saveSearch(basePath, saveText)
{
    document.getElementById('searchText').innerHTML = saveText;
    var response = new Ajax.Request(basePath + 'properties/save_search',
    {
      onSuccess: function(transport) {
        document.getElementById('searchText').innerHTML = transport.responseText;
        document.getElementById('searchButton').style.display = 'none';
      }
    });
}

// AJAX call to save search title
function saveSearchEmail(id, turnedOn, basePath, saveText)
{
    document.getElementById('status').innerHTML = saveText;
    var response = new Ajax.Request(basePath + 'login/searches/email',
    {
      method: 'post',
      parameters: "id=" + id + "&email_toggle=" + +turnedOn,
      onSuccess: function(transport) {
        document.getElementById('status').innerHTML = transport.responseText;
        document.getElementById('actualTitle' + id).innerHTML = document.getElementById(id + '_title').value;
      }
    });
}

// AJAX call to save search title
function saveSearchTitle(id, basePath)
{
    document.getElementById('status').innerHTML = '...';
    var response = new Ajax.Request(basePath + 'login/searches/title',
    {
      method: 'post',
      parameters: "id=" + id + "&title=" + document.getElementById(id + '_title').value,
      onSuccess: function(transport) {
        document.getElementById('status').innerHTML = transport.responseText;
        document.getElementById('actualTitle' + id).innerHTML = document.getElementById(id + '_title').value;
        showDiv('realTitle' + id);
        hideDiv('inputTitle' + id);
      }
    });
}

// Prototype function to load MyLogin -> Faves -> Email Friend or Inquire page
// - manufacture props[] args from form checkboxes w/ propCheck class
// Needs the path and what subwave page we want (email or inquire)
function loadMyLoginPage(basePath, what)
{
	checks = document.getElementsByClassName('propCheck');
	var url = "";
	for (i=0;i<checks.length;i++)
	{
		if (checks[i].checked == true)
		{
			url += 'props[]=' + checks[i].value + '&';
		}
	}

	if (url != "")
	{
		location.href = basePath + "login/props/" + what + "?" + url;
	} else {
		alert("Sorry, you must first check the appropriate listings below.");
	}
}