
// ************************************************************************** //
// 								AJAX CODE									  //
// ************************************************************************** //

function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

var http = getHTTPObject(); // We create the HTTP Object

var url = "http://www.hellobeach.com/includes/ajax.php"; // The server-side script

function ajaxFetchData(parameters, callback_function) {
	// get the list of towns
	// post to the PHP
	var full_url = url + "?" + parameters;
	http.open("GET", full_url, true);
	// wait for things to return
	http.onreadystatechange = function() {
		if (http.readyState == 4) {
			data = http.responseText;
			if (data == "NO ACTION SPECIFIED") {
				alert("AJAX Error");
				return;
			}
/*			if (data == "" || data == null) {
				alert("No AJAX data returned");
				return;
			}*/
			callback_function(data);
		}
	}
	// ???
	http.send(null);
}

var county;
var county_id;
var town;
var town_id;
var neighborhood;
var neighborhood_id;
var include_other = false;

function updateTowns(county, town) {
	updateTownNeighborhoods(county, town, null);
}

function updateTownNeighborhoods(c, t, n, i) {
	county = c;
	town = t;
	neighborhood = n;
	county_id = county.value;
	town_id = town.value;
	include_other = i;
	
	if (neighborhood == null) {
		// do stuff
		neighborhood_id = "";
	} else {
		neighborhood_id = neighborhood.value;
	}

	emptyDropdown(town);
	
	ajaxFetchData("action=fetch_towns&county_id=" + county_id, updateTownData);
}

function updateNeighborhoods(c, t, n, i) {
	county = c;
	town = t;
	neighborhood = n;
	county_id = county.value;
	town_id = town.value;
	neighborhood_id = neighborhood.value;
	include_other = i;
	
	emptyDropdown(neighborhood);
	
	ajaxFetchData("action=fetch_neighborhoods&county_id=" + county_id + "&town_id=" + town_id, updateNeighborhoodData);
}

function massageReturnData(data) {
	var rows = new Array();
	if (data !== "" && data !== null) {
		results = data.split("{}");
		for (var key in results) {
			var row = results[key].split("%%");
			// pull out pair
			rows[key] = new Array(row[0], row[1]);
		}
	}
	return rows;
}

function updateTownData(data) {
	// Split the comma delimited response into an array
	var towns = massageReturnData(data);
	
	if (include_other) {
		additional_options = new Array(new Array("Select...", ""));
	} else {
		additional_options = new Array(new Array("No Preference", ""));
	}

	// fill dropdown
	populateDropdown(town, additional_options, towns, town_id);
	
	// update neighborhoods
	if (neighborhood !== null) {
		updateNeighborhoods(county, town, neighborhood, include_other);
	}
}

function updateNeighborhoodData(data) {
	// Split the comma delimited response into an array
	var neighborhoods = massageReturnData(data);
	
	if (include_other) {
		additional_options = new Array(new Array("Select...", ""), new Array("Other", "-1"));
	} else {
		additional_options = new Array(new Array("No Preference", ""));
	}
	
	// fill dropdown
	populateDropdown(neighborhood, additional_options, neighborhoods, neighborhood_id);
}

function emptyDropdown(dropdown) {
	// remove all options from the list
	while (dropdown.length > 0) {
		dropdown.options[0] = null;
	}	
}

function populateDropdown(dropdown, additional_options, values, selected) {
	var i = 0;
	for (var index in additional_options) {
		var option = additional_options[index];
		dropdown.options[i++] = new Option(option[0], option[1], (selected == option[1]));
	}
	for (var key in values) {
		var this_option = values[key];
		dropdown.options[i++] = new Option(this_option[1],
										this_option[0],
										(selected == this_option[0]),
										(selected == this_option[0]));
	}
	if (values.length == 0) {
		if (additional_options.length == 2) {
			dropdown.options[0] = null; // remove select if no other options for neighborhood dropdown (force-choose "Other");
		} else {
			dropdown.disabled = true;
		}
	} else {
		dropdown.disabled = false;
	}
}

// ************************************************************************** //
// 								FAVORITES CODE								  //
// ************************************************************************** //

function addToFavorites(div_id, id) {
	var div = document.getElementById(div_id);
	// get existing favorites
	var cookieData = getCookie("hb_my_favorites");
//	alert("existing cookie: " + cookieData);
	if (cookieData == "") {
		cookieData = id;
	} else {
		cookieData += "," + id;
	}
//	alert("new cookie: " + cookieData);
	
	// Use this variable to set the name of the cookie
	var cookieName = "hb_my_favorites";
		
	// Set the cookie
	setCookie(cookieName, cookieData, 360, "/");
	
	// update page text to show that the favorite has been added
//	div.innerHTML = '<div class="arrow_button"><a href="javascript: removeFromFavorites(\'favorites' + id + '\', ' + id + ');">Remove From My Favorites</a></div>';// + getCookie("hb_my_favorites");
	div.innerHTML = '<div class="arrow_button"><a href="http://www.hellobeach.com/listings/my_favorites.php?back=aHR0cDovL3d3dy5oZWxsb2JlYWNoLmNvbS9pbmNsdWRlcy9qYXZhc2NyaXB0LnBocA==">In My Favorites</a></div>';
}

function removeFromFavorites(div_id, id, refresh) {
	var div = document.getElementById(div_id);
	// get existing favorites
	var cookieData = getCookie("hb_my_favorites");
//	alert("existing cookie: " + cookieData + "\n from " + document.cookie);
	var parts = cookieData.split(",");
	cookieData = new Array();
	var i = 0;
	for (var key in parts) {
		var nid = parts[key];
		if (nid != id && nid != null && nid != "null") {
			cookieData[i++] = nid;
		}
	}
	cookieData = cookieData.join(",");
//	alert("removing: " + id + "new cookie: " + cookieData);
	
	// Use this variable to set the name of the cookie
	var cookieName = "hb_my_favorites";
	
	// Set the cookie
	setCookie(cookieName, cookieData, 360, "/");
	
	if (refresh) {
		div.innerHTML = 'Removing Favorite...';// + getCookie("hb_my_favorites");
		window.location.reload();
	} else {
		// update page text to show that the favorite has been added
		div.innerHTML = '<div class="arrow_button"><a href="javascript: addToFavorites(\'favorites' + id + '\', ' + id + ');">Add To My Favorites</a></div>';// + getCookie("hb_my_favorites");
	}
}


/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Public Domain (Thanks to Dustin Diaz) :: http://www.dustindiaz.com/top-ten-javascript/ */

function getCookie(name) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
						( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
						( ( path ) ? ";path=" + path : "" ) +
						( ( domain ) ? ";domain=" + domain : "" ) +
						( ( secure ) ? ";secure" : "" );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) {
		document.cookie = name + "=" +
						( ( path ) ? ";path=" + path : "") +
						( ( domain ) ? ";domain=" + domain : "" ) +
						";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}



// ************************************************************************** //
// 								POPUPS CODE									  //
// ************************************************************************** //

/*
function showPhoto(show_id, hide_id) {
	var show_block = document.getElementById("photo" + show_id);
	var hide_block = document.getElementById("photo" + hide_id);
	hide_block.style.display = "none";
	show_block.style.display = "block";
}
*/

function popPhoto(id) {
	var imageWindow = window.open('http://www.hellobeach.com/property/photo.php?id=' + id, 'imageWindow', 'width=646,height=523,scrollbars=no,status=no,resizable=no');
	imageWindow.focus();
}

function popHelp(id) {
	var imageWindow = window.open('http://www.hellobeach.com/info/help.php?id=' + id, 'helpWindow', 'width=646,height=523,scrollbars=yes,status=no,resizable=no');
	imageWindow.focus();
}

function winPop(imageName) {
	var imageWindow = window.open('photo.php?id='+imageName ,'_blank','width=480,height=395,scrollbars=no,status=no,resizable=yes');
	imageWindow.focus();
}

// ************************************************************************** //
// 								FLASH CODE									  //
// ************************************************************************** //

function displayFlash() {
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="570" height="321" id="emc001_hpMap" align="middle">');
	document.write('<param name="allowScriptAccess" value="sameDomain" />');
	document.write('<param name="movie" value="http://www.hellobeach.com/images/callout/emc001_hpMap.swf?root_path=http://www.hellobeach.com" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="bgcolor" value="#ffffff" />');
	document.write('<embed src="http://www.hellobeach.com/images/callout/emc001_hpMap.swf?root_path=http://www.hellobeach.com" quality="high" bgcolor="#ffffff" width="570" height="321" name="emc001_hpMap" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	document.write('</object>');
}



/* BEGIN FLASH DETECTION JAVASCRIPT */
// -----------------------------------------------------------------------------
	// Globals
	// Major version of Flash required
	var requiredMajorVersion = 6;
	// Minor version of Flash required
	var requiredMinorVersion = 0;
	// Minor version of Flash required
	var requiredRevision = 0;
	// the version of javascript supported
	var jsVersion = 1.0;
	// -----------------------------------------------------------------------------



	// Detect Client Browser type
	var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
	var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
	var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
	jsVersion = 1.1;
	// JavaScript helper required to detect Flash Player PlugIn version information
	function JSGetSwfVer(i){
		// NS/Opera version >= 3 check for Flash plugin in plugin array
		if (navigator.plugins != null && navigator.plugins.length > 0) {
			if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
				var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
				var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
				descArray = flashDescription.split(" ");
				tempArrayMajor = descArray[2].split(".");
				versionMajor = tempArrayMajor[0];
				versionMinor = tempArrayMajor[1];
				if ( descArray[3] != "" ) {
					tempArrayMinor = descArray[3].split("r");
				} else {
					tempArrayMinor = descArray[4].split("r");
				}
				versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
				flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
			} else {
				flashVer = -1;
			}
		}
		// MSN/WebTV 2.6 supports Flash 4
		else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
		// WebTV 2.5 supports Flash 3
		else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
		// older WebTV supports Flash 2
		else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
		// Can't detect in all other cases
		else {
			
			flashVer = -1;
		}
		return flashVer;
	} 
	
	// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
	function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) 
	{
		reqVer = parseFloat(reqMajorVer + "." + reqRevision);
		// loop backwards through the versions until we find the newest version	
		for (i=25;i>0;i--) {	
			if (isIE && isWin && !isOpera) {				
				versionStr = VBGetSwfVer(i);
			} else {				
				versionStr = JSGetSwfVer(i);		
			}
			if (versionStr == -1 ) { 				
				return false;
			} else if (versionStr != 0) {
				if(isIE && isWin && !isOpera) {
					tempArray         = versionStr.split(" ");
					tempString        = tempArray[1];
					versionArray      = tempString .split(",");				
				} else {
					versionArray      = versionStr.split(".");
				}
				versionMajor      = versionArray[0];
				versionMinor      = versionArray[1];
				versionRevision   = versionArray[2];
				
				//alert(versionMajor + ' ' + versionMinor + ' ' + versionRevision);
				
				versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
				versionNum        = parseFloat(versionString);
				// is the major.revision >= requested major.revision AND the minor version >= requested minor
				if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
					return true;
				} else {
					return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );	
				}
			}
		}	
	}
/* END FLASH DETECTION JAVASCRIPT */

