// JavaScript Document
//**********************************************************************
//  AJAX Request reference list................
//	return "-1" Error occurs.
//	return "0"  Invalid Login.
//	return "1"  Request successfully sent.
//	return "2"  redirect to HomeAlert Home Page.
//  return "3"  Profile has been updated.
//  return "4"  LoginID has been used.
//  return "5"  Email has been sent.
//**********************************************************************

//*************************************************************************
// initialize the VE map
//*************************************************************************
function initVEMap(longitude,latitude,zoom)
{
      ve_map = new VEMap('divMap1');
	  ve_map.LoadMap();
		if(navigator.userAgent.indexOf("MSIE") >=0)
		{
			getObj('MSVE_navAction_ObliqueMapView').style.width="6.8em";
			getObj('MSVE_navAction_leftBar').style.backgroundColor = "#235087";
			getObj('MSVE_navAction_container').style.backgroundColor = "#235087";
			getObj('MSVE_navAction_toggleGlyphWrapper').style.display = "none";
		}	  	  
	  ve_map.SetCenterAndZoom(new VELatLong(longitude,latitude), zoom);
	  
	  g_veslPushpin = new VEShapeLayer();
	  ve_map.AddShapeLayer(g_veslPushpin);
	  g_veslArea = new VEShapeLayer();
	  ve_map.AddShapeLayer(g_veslArea);	 	  

	  ve_map.AttachEvent("ondoubleclick", CustomDoubleClick);
	  //ve_map.AttachEvent("onendpan", testfn);		  
	  
	  if (typeof VEShowDefaultDetail == 'undefined') ve_map.AttachEvent("onmouseover", PinHover);
	  
	  if (typeof drawPolygonMouseClick!='undefined') areaSearchVEmap();

	  if (typeof initGetPolygons != 'undefined') initGetPolygons();
}	

function testfn(e)
{
	MapFormSubmit();
}
function CustomDoubleClick(e)
{
	var currentZoomLevel;
	currentZoomLevel = ve_map.GetZoomLevel();
	var x = e.mapX/* + getDocumentBody().scrollLeft*/;
	var y = e.mapY/* + getDocumentBody().scrollTop;*/;
	pixel = new VEPixel(x, y);
	
	var LL = ve_map.PixelToLatLong(pixel);
	
	ve_map.SetCenterAndZoom(LL, currentZoomLevel + 2);
	
	return true;
}


//*************************************************************************
// initialize the VE map Area Search Feature
//*************************************************************************
function areaSearchVEmap()
{
	  g_divTooltip = document.getElementById('div_tooltip');
}

//*************************************************************************
// initialize the popupInfo Box for VE map
//*************************************************************************
function PinHover(e)
{   
	if(e.elementID)
	{
		var pin= ve_map.GetShapeByID(e.elementID);
			
		var k = pin.GetTitle();

		if (!IsNumeric(k) && k.length<=4) return;
		if (IsNumeric(k) && k.length<=4) return;
		if (!IsNumeric(k)) return;
		
 		pin.SetDescription("<div id='PropertyInfo_"+k+"' ><img src='"+DOCUMENT_ROOT+"/img/indicator.gif'/> Loading...</div>"); 
		getPopInfoVEmap(k,"PropertyInfo_"+k);

	}
}	

//*************************************************************************
// VE map - get property detail for a popup window
//*************************************************************************
function getPopInfoVEmap(k, DivID)
{
	$.ajax({
	  type: "GET",
	  url: DOCUMENT_ROOT + "/PHP/ProcessPropertyPopupInfo.php",
	  data: "withDetailLink=1&k="+k,
	  success: function(msg){
		$('#'+DivID).html(msg, true);
	  }
	});		
}

//*************************************************************************
// declare the icons for google map
//*************************************************************************
function initIcons()
{
	try
	{
		if (!g_basicIcon)
		{
			g_basicIcon = new GIcon();
			g_basicIcon.shadow = "http://www.idcglobal.com/maps/shadow.png";
			g_basicIcon.iconSize = new GSize(16, 16);
			g_basicIcon.shadowSize = new GSize(20, 22);
			g_basicIcon.iconAnchor = new GPoint(9, 34);
			g_basicIcon.infoWindowAnchor = new GPoint(9, 2);
			g_basicIcon.infoShadowAnchor = new GPoint(18, 25);
		}
		if (!g_houseIcon)
		{
					g_houseIcon = new GIcon(g_basicIcon);
					g_houseIcon.image = DOCUMENT_ROOT + "/img/Mappin.png";
		}
		if (!g_openHouseIcon)
		{
					g_openHouseIcon = new GIcon(g_basicIcon);
					g_openHouseIcon.image = DOCUMENT_ROOT + "/img/house_green.png";
		}			
		if (!g_schoolIcon)
		{
					g_schoolIcon = new GIcon(g_basicIcon);
					g_schoolIcon.image = DOCUMENT_ROOT + "/img/school.png";
		}			
		
	}catch(e){alert('initIcons: ' + e.description)}
}

//*************************************************************************
// initialize the google map
//*************************************************************************
function initGoogleMap(longitude,latitude,zoom)
{
	initIcons();
	g_map = new GMap2(getObj("divMap1"));

	g_map.addControl(new GMapTypeControl());
	g_map.addControl(new GSmallMapControl());

	g_map.setCenter(new GLatLng(longitude,latitude), zoom);
	
	if (mapSearch) 
	{
		setMapSearchLongLat();
		
		var g_mapMoveend = GEvent.addListener(g_map, "moveend", resubmitForm);	
		var g_mapZoomend = GEvent.addListener(g_map, "zoomend", resubmitForm);
	}
	
	GEvent.addListener(g_map, 'infowindowopen', function() 
	{
		g_CenterLat = g_map.getCenter().lat();
		g_CenterLng = g_map.getCenter().lng();
		if (mapSearch) 
		{	
			GEvent.removeListener(g_mapMoveend);
		}
	});
	
	if (mapSearch) 
	{	
		GEvent.addListener(g_map, 'infowindowclose', function() 
		{
			g_mapMoveend = GEvent.addListener(g_map, 'moveend',  resubmitForm);
			if (g_CenterLat != g_map.getCenter().lat() || g_CenterLng != g_map.getCenter().lng()) 
			{	
				resubmitForm();
			}
	
		});	
	}
	g_map.enableDoubleClickZoom();
	g_map.enableScrollWheelZoom();
}	


//*************************************************************************
// Google map - attach onclick event
//*************************************************************************
function createMarker(point, html, icon, k) 
{
   	var marker = new GMarker(point, icon);
   	GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml(html);
	getPopInfo(k);
	});
  return marker;
}

//*************************************************************************
// Google map - get property detail for a popup window
//*************************************************************************
function getPopInfo(k)
{
	$.ajax({
	  type: "GET",
	  url: DOCUMENT_ROOT + "/PHP/ProcessPropertyPopupInfo.php",
	  data: "withDetailLink=1&k="+k,
	  success: function(msg){
		 $('#div_'+k).html(msg, true);
	  }
	});		
}

//*********************************************************************************
// Check the user login status[Simple]
//*********************************************************************************
function checkLoginSimple()
{
	$.ajax({
		  type: "POST",
		  url: DOCUMENT_ROOT+"/PRC/ProcessCheckLogin.php",
		  data: "section=checkLogin",
		  success: function(msg){
			if ($.trim(msg)=='0') HomeAlertLogin = false;
			else HomeAlertLogin = true;
		}
	});
}

//*********************************************************************************
// Check the user login status and return Contact Information
//*********************************************************************************
function checkLoginWithDataReturn(functionName, MsgID)
{
	$('#'+MsgID).html('<img src="'+DOCUMENT_ROOT+'/img/indicator.gif" border="0"> Retriving data...');
	$.ajax({
		  type: "POST",
		  url: DOCUMENT_ROOT+"/PRC/ProcessCheckLogin.php",
		  data: "",
		  success: function(msg){
			$('#'+MsgID).html('');
			if ($.trim(msg)=='0') HomeAlertLogin = false;
			else {
				dataArray = msg.split("?");
				HomeAlertLogin = true;
				eval(functionName+"();");
			}
		}
	});
}

//*********************************************************************************
// Check the user login status
//*********************************************************************************
function checkLogin(divID, info, index)
{
	// 1 = Save Search
	// 2 = Save Listing
	// 3 = Save Area
	$.ajax({
		  type: "POST",
		  url: DOCUMENT_ROOT+"/PRC/ProcessCheckLogin.php",
		  data: "section=checkLogin",
		  success: function(msg){
			if ($.trim(msg)=='0')
			{
				ConfirmMsg = confirm("You have to login in order to use this feature. Would you like to login now?");	
				if (ConfirmMsg) 
				{
					if (index == '1')
						tb_show('Home Alert Login', DOCUMENT_ROOT + '/POP/HomeAlertLoginPopup.php?width=300&height=120&divID='+divID+'&i='+index, '');
					else if (index == '2')
						tb_show('Home Alert Login', DOCUMENT_ROOT + '/POP/HomeAlertLoginPopup.php?width=300&height=120&i='+index+'&divID='+divID+'&info='+info, '');
					else if (index == '3')
						tb_show('Home Alert Login', DOCUMENT_ROOT + '/POP/HomeAlertLoginPopup.php?width=300&height=120&i='+index+'&divID='+divID, '');
					else if (index == '4')
						tb_show('Home Alert Login', DOCUMENT_ROOT + '/POP/HomeAlertLoginPopup.php?width=300&height=120&i='+index+'&divID='+divID+'&info='+info, '');
				}
			}else
			{
				if (index=='1')
					callHomeAlertSaveSearch(divID);
				else if (index=='2')
					saveProperty(divID, info);					
				else if (index=='3')
					saveAreaSearch(divID, info);
				else if (index == '4')
					removeProperty(divID, info);
			}			
		}
	});
}



//******************************************************************************
//	Save the current property into user's favorite list
//******************************************************************************
function saveProperty(divID, MLSNumber)
{
	$('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/img/indicator.gif" border="0"/>');
	$.ajax({
	  type: "POST",
	  url: DOCUMENT_ROOT+"/PRC/ProcessHomeAlertAddProperty.php",
	  data: "MLSNum="+MLSNumber,
	  success: function(msg){
		if ($.trim(msg)=='1')		$('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/IMG/btn_propertySaved.jpg">');
		else if ($.trim(msg)=='0')	$('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/IMG/btn_propertySaved.jpg">');
		else if ($.trim(msg)=='-1')	$('#' + divID).html('Error on saving');
		$('#' + divID).css('color','red');
	  }
	});
}


//******************************************************************************
//	Delete a saved search for a user
//******************************************************************************
function deleteHomeAlert(divID, SearchCriteriaKEY)
{
	var confirmDelete = confirm('Are you going to delete this saved search?');
	if (confirmDelete)
	{
		$('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/img/indicator.gif" border="0"/> Deleting a saved search');
		$.ajax({
		  type: "POST",
		  url: DOCUMENT_ROOT+"/PRC/ProcessDeleteHomeAlert.php",
		  data: "SearchCriteriaKEY="+SearchCriteriaKEY,
		  success: function(msg){
			if ($.trim(msg)=='1'){
				$('#' + divID).html('A saved search is deleted');
				$('#SavedSearch_'+SearchCriteriaKEY).slideUp('fast');
			}
			else if ($.trim(msg)=='-1')	$('#' + divID).html('Error on removing a saved search');
			$('#' + divID).css('color','red');
		  }
		});
	}
}

//******************************************************************************
//	Remove the current property from user's favorite list
//******************************************************************************
function removeProperty(divID, MLSNumber)
{
	$('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/img/indicator.gif" border="0"/> Removing Property');
	$.ajax({
	  type: "POST",
	  url: DOCUMENT_ROOT+"/PRC/ProcessHomeAlertRemoveProperty.php",
	  data: "MLSNum="+MLSNumber,
	  success: function(msg){
		if ($.trim(msg)=='1')		$('#' + divID).html('Property is removed');
		else if ($.trim(msg)=='-1')	$('#' + divID).html('Error on removing property');
		$('#' + divID).css('color','red');
		removedProperty = true;
		getTotalResult();		
	  }
	});
}

//*********************************************************************************
// Set the Search Criteria Name
//********************************************************************************* 
function saveSearch(SearchCriteriaName, divID)
{
	$('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/img/indicator.gif" border="0"> Submiting request...');	
	$.ajax({
	  type: "POST",
	  url: DOCUMENT_ROOT+"/PRC/ProcessResults.php",
	  data: "section=saveSearch&SearchCriteriaName="+SearchCriteriaName+"&session_id=" + randID,
	  success: function(msg){
		if (msg=='1')	$('#' + divID).html('This search has been saved.');
		else		    $('#' + divID).html('Submitting error. Please contact the web administrator.');
	  }
	});
}

//*********************************************************************************
// Call the Home Alert Save Search Pop to name the new search
//********************************************************************************* 
function callHomeAlertSaveSearch(divID)
{
	tb_show('Name this search', DOCUMENT_ROOT + '/POP/HomeAlertSaveSearchPopup.php?width=270&height=100&divID='+divID, '');
}

function changeSortByValue(FK)
{
	getObj('SortBy').value = FK;
	getObj('SearchForm').submit();
}

//*********************************************************************************
// Validate form elements and make sure all the required fields are being filled
//********************************************************************************* 
function form_validation(formID, ProcessPage, MsgID)
{
	var inputFields = $('input[@type=text]').get();
	for (var i = 0; i<inputFields.length; i++)
	{
		if (inputFields[i].id.indexOf('req')!=-1 && $.trim(inputFields[i].value)=='')
		{
// 			alert("Missing required field. ["+ inputFields[i].name + "]");
			alert("Missing required field. "+ inputFields[i].title);
			inputFields[i].focus();
			return;
		}
	}

	processForm(formID, ProcessPage, MsgID);
}

//*********************************************************************************
// Submit the form to a processing page thru ajax
//********************************************************************************* 
function processForm(formID, ProcessPage, MsgID)
{
	$('#'+MsgID).html('<img src="'+DOCUMENT_ROOT+'/img/indicator.gif" border="0"> Now sending request...');	
	$.ajax({
	  type: "POST",
	  url: ProcessPage,
	  data: $("input[@type=hidden]",$("#"+formID)).serialize() + '&' + $("textarea",$("#"+formID)).serialize() + '&' + $("input[@type=text]",$("#"+formID)).serialize() + '&' + $("input[@type=checkbox]",$("#"+formID)).serialize() + '&'  + $("input[@type=radio]",$("#"+formID)).serialize() + '&' + $("input[@type=password]",$("#"+formID)).serialize() + '&' + $("select",$("#"+formID)).serialize(),
	  success: function(msg){
		if ($.trim(msg)=='1')       $('#'+MsgID).html('Request has been sent.');
		else if ($.trim(msg)=='0')  $('#'+MsgID).html('Invalid Login');
		else if ($.trim(msg)=='2')  window.location.href = homeAlertHome;
		else if ($.trim(msg)=='3')  $('#'+MsgID).html('Profile has been updated.');
		else if ($.trim(msg)=='4')  $('#'+MsgID).html('LoginID has been used.');
		else if ($.trim(msg)=='5')  
		{
			$('#'+MsgID).html('<font color="red">Email has been sent.</font>');
			tb_remove();
		}
		else if ($.trim(msg)=='6')  window.location.href = homeAlertSearchCriteriaList;
		else if ($.trim(msg)=='7')  $('#'+MsgID).html('<font color="red">Error, Invalid Email or system error.</font>');
		else if ($.trim(msg)=='-1') $('#'+MsgID).html('<font color="red">-1 Error, please contact our web administrator.</font>');	
		else $('#'+MsgID).html('<font color="red">Error, please contact our web administrator.</font>');	
		
	  }
	});
}

//*************************************************************************
// Go to the detail of single property
//*************************************************************************
function gotoSingleDetail(k)
{
	window.location.href = detailPage+'&MLSNum='+k+'&current=0';
}

//*************************************************************************
// Remove the value when the element is on focus
//*************************************************************************
function cleanFieldOnFocus(ID)
{
	$('#'+ID).val('');
}

//*************************************************************************
// Return the window document
//*************************************************************************
function getDocumentBody()
{
	if (window.document.documentElement && (window.document.documentElement.clientWidth || window.document.documentElement.clientHeight)) 
		return window.document.documentElement;
	else if (window.document.body && (window.document.body.clientWidth || window.document.body.clientHeight))
		return window.document.body;
}
//*****************************************************************************
// put back value when element is blurred
//*****************************************************************************
function restoreValue(ID, value)
{
	if ($.trim($('#'+ID).val())=='')
		$('#'+ID).val(value);
}

//***************************************************************************************************
// Go back to the search page with current criteria preselected.
//***************************************************************************************************
function refineSearch()
{
	window.location.href = searchPage + "&session_id="+randID;
}

//***************************************************************************************************
// Go back to a new search page
//***************************************************************************************************
function performNewSearch()
{
	window.location.href = searchPage;
}

//***************************************************************************************************
// Resize the iframe size after the page is loaded.
//***************************************************************************************************
function resizeIframeForAgentSite()
{
	if (window.parent!=window)
	{
		frameID = window.parent.document.getElementsByTagName("iframe")[0].id;

		window.parent.document.getElementById(frameID).style.height = ($(".contentArea").height() + 100) + 'px';

		if (window.parent.document.getElementsByTagName("iframe")[1])
		{
			frameID = window.parent.document.getElementsByTagName("iframe")[1].id;
			window.parent.document.getElementById(frameID).style.height = ($(".contentArea").height() + 100) + 'px';		
		}
	}
}

//***************************************************************************************************
// Compare Properties
//***************************************************************************************************
function addPropertyCompare(k)
{
	var propertyList = readCookie('CompareProperties');
	var tmp=0;
	var tmp2=0;

	var properties = new Array();
	
	if ($.trim(propertyList)!=''){
		var properties = propertyList.split(',');
		tmp2 = properties.length; 
		for (var i=0; i<properties.length; i++){
			if (properties[i]==k){

				properties[i]='';

				tmp=1;
				tmp2--;
			}
		}

		//because we have 3 + 1 property selected, so 4
		if (tmp2>3) 
		{
			alert('You can only compare four properties at a time.')
			return false;
		}
		
	}else{
		properties[0]=k;
		tmp=1;
	}
	
	propertyList = '';

	cleanPropertyList();
	
	var first=0;
	
	for (var i=0; i<5; i++){

		if ($.trim(properties[i])!='') {
			if (first==0){ 
				propertyList += properties[i]; first=1; 
			}else {
				propertyList += ',' + properties[i];
			}
		}	
	}
	if(tmp==0) propertyList += ',' + k;
	
	
	createCookie('CompareProperties', propertyList, 3);

	return true;
}

function checkCompare(){

	var propertyList = readCookie('CompareProperties');
	
	if (propertyList==null)
		propertyList = '';
	else if ($.trim(propertyList)!='')
	{
		var properties = propertyList.split(',');

		for (var i=0; i<properties.length; i++){

			if($("#compare_" + properties[i]).size()){
				$("#compare_" + properties[i]).attr({ checked: "checked" });
			}
		}
	}
}


function getComparePropertyList()
{
	alert(readCookie('CompareProperties'));
}

function cleanPropertyList()
{
	eraseCookie('CompareProperties');
}
function removeChecked(){
	$("input").removeAttr("checked");
}


function compareProperties()
{
	var propertyList = readCookie('CompareProperties');
	if (propertyList==null)
	{
		alert('Please select at least two properties to compare');
		return;		
	}
	
	var properties = propertyList.split(',');
	
	if (properties.length<2) 
	{
		alert('Please select at least two properties to compare');
		return;
	}
	if (getParentObj("PublicWebID"))
		window.open(DOCUMENT_ROOT+'/POP/CompareProperties.php?mlsnum='+propertyList+'&agent='+getParentObj("PublicWebID").value);
	else
		window.open(DOCUMENT_ROOT+'/POP/CompareProperties.php?mlsnum='+propertyList);
}

function ShowingTimeLink(Link)
{
	EscapeLink = encodeURI(Link);
	window.open(EscapeLink);
}

function isInteger(string){
	if (string!=''){
		if (string.toString().search(/^-?[0-9]+$/) != 0){ 
			return false; 
		}else{ 
			return true;
		}
	}
}

function isLong(string){
	if (string.length<10) return true;
	else return false;
}

function quickSearchMLSNumValidate(string){
	if (string!='' && string!='MLS Numbers'){
		if (!isInteger(string)){
			alert('This field has to be numeric'); 
			return false;
		}else
		if (!isLong(string)){
			alert('This MLS Number is too long');
			return false;
		}else return true;
	}else return true;
}

function cleanQuickSearch(){
	
	if (!validateZip($('#1086_quickSearch').val())) return false;
	else if (!quickSearchMLSNumValidate($('#0110_quickSearch').val())) return false;
	else {
	if ($('#1050_quickSearch').val()=='Address') $('#1050_quickSearch').val("");
	if ($('#1086_quickSearch').val()=='Zip Code') $('#1086_quickSearch').val("");
	if ($('#0110_quickSearch').val()=='MLS Numbers') $('#0110_quickSearch').val("");
	return true;
	}
	
}

function showPicture(Img)
{	
	$("#mainPhoto").attr("src",Img.src);
}

function checkDefault(field)
{
	if($('#'+ field).val()=='-1')
	{
		alert("Please select an option");
		return false;
	}else return true;	
}