<!--//
// JavaScript Document
//*************************************************************************
// Configuration Variables
//*************************************************************************
var ContactKEY = 0;
var ContactEmail = null;
var previewProperty		= false;					// turn on the preview property function
var returnAsJSON		= false;				// less AJAX calls in the detail page
var blockWhenLoading	= true;
var AjaxManagerContact  = null;
//Ajax Lib
//var enumServices = new __DataFloat__Agora__Services();

//Page name define
var searchPage 			= DOCUMENT_ROOT + '/Search.aspx?content=search';
var resultPage 			= DOCUMENT_ROOT + '/SearchResult.aspx?content=searchResults';
var detailPage 			= DOCUMENT_ROOT + '/ListingDetail.aspx?content=listingDetail';
var mapSearchPage 		= DOCUMENT_ROOT + '/contentPage.php?content=mapSearch';
var printDetailPage 	= DOCUMENT_ROOT + '/POP/Print.php';
var homeAlertFolder		= DOCUMENT_ROOT;
var PageParameter		= 'content';
var homeAlertHome		= homeAlertFolder + '/UserAccount.aspx';
var contentArea			= '.contentArea';

//Processing Page Name
var ProcessResultPage  				= DOCUMENT_ROOT + '/Services/ProcessResults.aspx';
var ProcessSpotLightPage  			= DOCUMENT_ROOT + '/Services/ProcessSpotLight.aspx';
var ProcessOpenHousePage  			= DOCUMENT_ROOT + '/Services/ProcessOpenHouse.aspx';
var ProcessPropertyPopUpInfo 		= DOCUMENT_ROOT + "/Services/ProcessPropertyPopupInfo.aspx";
var ProcessCheckLogin				= DOCUMENT_ROOT + "/Services/ProcessCheckLogin.aspx";
var ProcessHomeAlertAddProperty 	= DOCUMENT_ROOT + "/Services/ProcessHomeAlertAddMatchedProperty.aspx";
var ProcessHomeAlertRemoveProperty 	= DOCUMENT_ROOT + "/Services/ProcessHomeAlertRemoveMatchedProperty.aspx";
var ProcessDeleteHomeAlert			= DOCUMENT_ROOT + "/Services/ProcessDeleteSearchCriteria.aspx";
var ProcessAgentListingCheck 		= DOCUMENT_ROOT + "/Services/ProcessAgentListingCheck.aspx";
var ProcessGetMapInformation        = DOCUMENT_ROOT + "/Services/SearchMapDetails.aspx"
var ProcessHomeAlertLogin           = DOCUMENT_ROOT + "/Services/ProcessHomeAlertLogin.aspx";
var ProcessAddSearchCriteria        = DOCUMENT_ROOT + "/Services/ProcessHomeAlertEditSearchCriteria.aspx";
var ProcessRateThisProperty         = DOCUMENT_ROOT + "/Services/ProcessRateThisProperty.aspx";

// PopUp Page
var HomeAlertPopupLogin             = DOCUMENT_ROOT + '/POP/HomeAlertLoginPopup.aspx';

//For Map Search
var mapSearchArea		= '#mapSearch_container';
var mapSearchDetailArea	= '#propertyDetailArea';
var maxProprtiesShow 	= 50;
var default_Latitude 	= 38.9;
var default_Longitude 	= -77.0;
var default_ZoomLevel 	= 9;

//For Agent Site
var hideSectionInAgentSite = Array('#logoMontage', '#ListingQuickSearch1', '#primaryNav', '#Header', '#leftbarSeparator','#dropShadow_left','#leftbar', '#detpg_topnav_container', '#dropShadow_right','#footer');

//For Result Page
var ViewType			= 1;		// 1: Thumbnail 2: ListView 3: MapView

//For Detail Page
var sectionRender = new Array("homeinfo");

var printSectionRender = new Array("printSection");

//*************************************************************************
// Initialize some common variables
//*************************************************************************
var rateArray 			= new Array();
var ReturnArr 			= new Array();
var g_map 				= null;
var ve_map				= null;
var g_veslPushpin		= null;
var g_basicIcon 		= null;
var g_houseIcon 		= null;
var g_openHouseIcon 	= null;
var g_schoolIcon		= null;
var returnedJSON 		= null;
var MLSArray			= null;
var MLSInfoArray		= null;
var	processTasks 		= 0;

//****************************************************************************
// Variables for Area map search
//****************************************************************************
var g_veslArea = null;
var g_currentShape = null;
var g_shapePoints = new Array();
var g_shapeCollection = new Array();
var g_tempShape = null;
var g_tempPoints = null;
var g_fldUserSetting = null;
var g_arrShapeIDs = null;
var g_areaStyle = 'font-weight:bold;font-size:10px;text-decoration:none;background-color:#000000;color:#FFFFFF';
var g_divTooltip = null;
var startMsg	= 'Click to start drawing a shape';
var drawingMsg	= 'Click to continue drawing this shape or right click to end this shape';
var endMsg	= 'Click to continue drawing this shape or right click to end this shape';
var shapeTitle = null;
var cursorX	 = 0;
var cursorY	 = 0;
var polygonCounter = 0;
var areaSearchFeature = true;

//**********************************************************************
//  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 be sent.
//**********************************************************************

var urlArray;

    $(document).ready(function(){
        var urlArray = window.location.href.replace("http://","").split("/");
        
        if (urlArray[0]!='wwwqa.pruysu.com' && urlArray[0]!='www.pruysu.com' && urlArray[0]!='pruysu.com' && urlArray[0]!='www.prucarolinas.com' && urlArray[0]!='prucarolinas.com' && urlArray[0]!='wwwqa.prucarolinas.com'&&  urlArray[0].indexOf('localhost') < 0)
        {
                $("#PhoneNumberImage").hide();
                $("#AgentOfficeSearch").hide();
                $("#onesrch").hide();
                //$("#phonenum").hide();
                $(".hideinagentsite").hide();
        }
   	});

//*************************************************************************
// initialize the VE map
//*************************************************************************
function initVEMap(longitude,latitude,zoom)
{
      ve_map = new VEMap('divMap1');
	  ve_map.LoadMap();
	  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);	 	  
	  
	  
	  if (typeof VEShowDefaultDetail == 'undefined') ve_map.AttachEvent("onmouseover", PinHover);
	  
	  if (typeof drawPolygonMouseClick!='undefined') areaSearchVEmap();

		if (typeof initGetPolygons != 'undefined') initGetPolygons();
}	

function onMouseOverCE()
{
	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)) return;

 		pin.SetDescription("<div id='PropertyInfo_"+k+"' style='width:300px' ><img src='"+DOCUMENT_ROOT+"/images/bg_loading.gif'/> Loading...</div>"); 
		
		getPopInfoVEmap(k,"PropertyInfo_"+k);
		
	}
}	
/*
function PinHover(x, y, title, details)
{   
	var ID = title;
	var DivID = "VPOP" + ID;
	var e=document.getElementById(ID+"_"+ve_map.GUID);
	if(e!=null&&e!="undefined")
	{    
		window.ero.setBoundingArea(
		new Msn.VE.Geometry.Point(0,0),
		new Msn.VE.Geometry.Point(document.body.clientWidth,
			document.body.clientHeight));
		window.ero.setContent("<div id='" + DivID + "'><img src='"+DOCUMENT_ROOT+"/images/bg_loading.gif'/> Loading...</div>");
		window.ero.dockToElement(e);
		getPopInfoVEmap(ID,DivID);
	}
}
*/
//*************************************************************************
// VE map - get property detail for a popup window
//*************************************************************************
function getPopInfoVEmap(k, DivID)
{
	$.ajax({
	  type: "GET",
	  url: ProcessGetMapInformation,
	  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 + "/images/Mappin.png";
		}
		if (!g_openHouseIcon)
		{
					g_openHouseIcon = new GIcon(g_basicIcon);
					g_openHouseIcon.image = DOCUMENT_ROOT + "/images/house_green.png";
		}			
		if (!g_schoolIcon)
		{
					g_schoolIcon = new GIcon(g_basicIcon);
					g_schoolIcon.image = DOCUMENT_ROOT + "/images/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 + "/Services/SearchMapDetails.aspx",
	  data: "withDetailLink=1&k="+k,
	  success: function(msg){
		 $('#div_'+k).html(msg, true);
	  }
	});		
}


//*********************************************************************************
// Check the user login status (Do not Delete)
//*********************************************************************************
function checkLogin(divID, info, index)
{
	// 1 = Save Search
	// 2 = Save Listing
	// 3 = Save Area
	// 4 = Remove Listing
    // 5 = Rating Property
    
    var params = "section=checkLogin&returnFields=Contact.ContactKEY";
    var oAjaxManager = new DataFloat.Agora.AjaxManager(params);
        oAjaxManager.NewSystemRequest(ProcessCheckLogin, 1, function(msg){
            ContactKEY = 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) 
				{

				    switch (index)
				    {
				        case "1":   tb_show('My Home Finder Login', HomeAlertPopupLogin + '?width=400&height=200&divID='+divID+'&index='+index, '');
				                    break;
					    case "2":   tb_show('My Home Finder Login', HomeAlertPopupLogin + '?width=400&height=180&index='+index+'&divID='+divID+'&info='+info, '');
					                break;
					    case "3":   tb_show('My Home Finder Login', HomeAlertPopupLogin + '?width=400&height=180&index='+index+'&divID='+divID+'&info='+info, '');
					                break;
					    case "4":   tb_show('My Home Finder Login', HomeAlertPopupLogin + '?width=400&height=180&index='+index+'&divID='+divID+'&info='+info, '');
					                break;
					    case "5":   tb_show('My Home Finder Login', HomeAlertPopupLogin + '?width=400&height=180&index='+index+'&divID='+divID+'&info='+info, '');
					                break;
					    case "6":   tb_show('My Home Finder Login', HomeAlertPopupLogin + '?width=400&height=180&index='+index+'&divID='+divID+'&info='+info, '');
					                break;
					    default: alert("javascript error in [check login]");
					}
				}
			}else
			{
			    switch(index)
			    {
			        case "1":   callHomeAlertSaveSearch(divID, ContactKEY);
			                    break;
				    case "2":   rateThisProperty(divID, info, ContactKEY);					
				                break;
				    case "3":   saveAreaSearch(divID, info, ContactKEY);
				                break;
				    case "4":   removeProperty(divID, info, ContactKEY);
				                break;
				    case "5":   rateThisProperty(divID, info, ContactKEY);
				                break;
				    case "6":   rateThisProperty(divID, ContactKEY);
			                    break;
				    default:    alert("javascript error in [check login]");
			    }
			}
        }
    )    
}

function rateThisProperty(divID, info, ContactKEY)
{
    var tempArray = info.split("_");
    var MLSNum = tempArray[0];
    var PropertyType = tempArray[1];
    var rating = tempArray[2];
    var ratingClass = '';
    switch (rating)
    {
        case "1": ratingClass="one-star-active"; break;
        case "2": ratingClass="two-stars-active"; break;
        case "3": ratingClass="three-stars-active"; break;
        case "4": ratingClass="four-stars-active"; break;
        case "5": ratingClass="five-stars-active"; break;
        default : ratingClass=""; break;
    }
    
    if (ratingClass!="")
        $('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/images/bg_loading.gif" border="0"/> Rating Property');
    else $('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/images/bg_loading.gif" border="0"/> Saving Property');
    
    checkIsRatedProperty(divID, info, MLSNum, PropertyType, rating, ratingClass, ContactKEY);
}

function checkIsRatedProperty(divID, info, MLSNum, PropertyType, rating, ratingClass, ContactKEY)
{
//HERE

    var params = "0030="+MLSNum+"&RecordType=14&0020="+PropertyType+"&n_dt=1&0010_n_k="+ContactKEY+"&ActionType=4";
    var oAjaxManager = new DataFloat.Agora.AjaxManager(params);
        oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerSetData, 1, function(msg){

            var params2 = "0030="+MLSNum+"&RecordType=14&0020="+PropertyType+"&n_dt=0&0010_n_k="+ContactKEY;
            var oAjaxManager2 = new DataFloat.Agora.AjaxManager(params2);
                oAjaxManager2.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerCount, 1, function(msg){
                    var actionType ="1";
                    if ($.trim(msg)!="0") actionType = "2";
                    submitRatingProperty(divID, info, MLSNum, PropertyType, rating, ratingClass, ContactKEY, actionType);
                })
         })
}


function submitRatingProperty(divID, info, MLSNum, PropertyType, rating, ratingClass, ContactKEY, s)
{
    var oAjaxManager0 = new DataFloat.Agora.AjaxManager("item=Contact.OWNER");
        oAjaxManager0.NewSystemRequest(DataFloat.Agora.Services.ServiceSessionManagerGetSessionVariable, 1, function(msg){
        var params = "ActionType="+s+"&n_dt=0&0070=3&0030="+MLSNum+"&RecordType=14&0020="+PropertyType+"&0010_n_k="+ContactKEY;
        n_uc = JSON.parse(msg)
        if (s=='1') params += "&n_uc=" + n_uc.ContactOWNER;
            if (ratingClass!="") params += "&0060="+rating;
            var oAjaxManager = new DataFloat.Agora.AjaxManager(params);
            oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerSetData, 1, function(msg){
                    
                    DataFloat.Agora.NewTrackAjax(DataFloat.Agora.NewTrack.TrackingType.SaveProperty, ContactKEY, PropertyType, MLSNum, '', function(){})
                    
                    if (ratingClass!="")
                    {$('#'+info).attr('class', ratingClass); 
                        $('#'+divID).html("Property is rated");
                    }else{ 
                        $('#'+divID).html("Property is Added<br/>Marked for Notification");
                        alert('This property has been added to your search.  You will receive notification of any changes.');
                    
                    }
                    $('#' + divID).css('color','red');
            })
        })
}

//*********************************************************************************
// Set the Search Criteria Name (Do not delete me)
//********************************************************************************* 
function removeProperty(removeDiv, MLSNumberWithPT)
{
    var confirmDelete = confirm('Are you going to remove this property from favorite list?');
    if (confirmDelete)
    {
        var tempArr = MLSNumberWithPT.split("_");
        var MLSNum  = tempArr[0];
        var PropertyType      = tempArr[1];
        $('#' + removeDiv).html('<img src="'+DOCUMENT_ROOT+'/images/bg_loading.gif" border="0">Removing Favorite Property...');	
        var oAjaxManager = new DataFloat.Agora.AjaxManager("RecordType=14&ActionType=3&0010_n_k="+ContactKEY+"&0020="+PropertyType+"&0030="+MLSNum+"&n_dt=0");
        oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerSetData, 1, function(msg){
		    alert('Property is removed');
		    $('#'+removeDiv).slideUp();
        })
    }
}

//*********************************************************************************
// Set the Search Criteria Name (Do not delete me)
//********************************************************************************* 
function saveSearch(SearchCriteriaName, divID, ContactKEY)
{
    $('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/images/bg_loading.gif" border="0"> Submiting request...');	
      var myDate=new Date();
      var month = myDate.getMonth()+1;
      var year = myDate.getYear();
      var day = myDate.getDate();
      if(day<10) day = "0" + day;
      if(month<10) month= "0" + month ;
      if(year<1000) year+=1900;
      var ThreeMonthsLater = year + "" + month + "" + day;
      
    var params = "0020="+SearchCriteriaName+"&0010_n_k="+ContactKEY+"&0110=25&0120_exception=-1&0130=1&0030=1&0060=1&ActionType=1&SearchCriteriaFieldKEY=0050&RecordType=9&0040="+ThreeMonthsLater+"&";
    
    var formParamArray = AspNet_formParams.split("&");
    var NewformParams = "";
    $.each( formParamArray, function(i, items){
      if (items!="")
      {
          var elements = items.split("=");
          if (elements[0]=="RecordType") 
            NewformParams += "SubRecordType=" + elements[1] + "&";
          else if (!isNaN(parseInt(elements[0].substring(0,4))))
            NewformParams += "sc_" + elements[0] + "=" + elements[1] + "&";
          else if (elements[0]!="")
            NewformParams += elements[0] + "=" + elements[1] + "&";
      }
    });
    var WholeCriteria = params + NewformParams
    
    var oAjaxManager0 = new DataFloat.Agora.AjaxManager("item=Contact.OWNER");
        oAjaxManager0.NewSystemRequest(DataFloat.Agora.Services.ServiceSessionManagerGetSessionVariable, 1, function(msg){
            var CREATOR = JSON.parse(msg);
            var oAjaxManager = new DataFloat.Agora.AjaxManager(WholeCriteria+"&n_uc="+CREATOR.ContactOWNER);
            oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerSetData, 1, function(msg){
                $('#' + divID).html('This search has been saved.');
                })
        })
}

//*********************************************************************************
// Call the HomeAlert Save Search Pop to name the new search
//********************************************************************************* 
function callHomeAlertSaveSearch(divID, ContactKEY)
{
    var SearchCriteriaKEY = DataFloat.Agora.Util.Request.QueryString['SearchCriteriaKey'];
    
    var FullSearch = DataFloat.Agora.Util.Request.QueryString['FullSearch'];
    
    if(FullSearch == 1 && SearchCriteriaKEY != undefined && isNumeric(SearchCriteriaKEY))
    {
        tb_show('Name this search', DOCUMENT_ROOT + '/POP/HomeAlertSaveSearchPopup.aspx?width=400&height=200&divID='+divID+'&ContactKEY='+ContactKEY+'&SearchCriteriaKEY='+SearchCriteriaKEY, '');
    }    
    else if (FullSearch == 0 && SearchCriteriaKEY!= undefined && isNumeric(SearchCriteriaKEY))
    {
        tb_show('Name this search', DOCUMENT_ROOT + '/POP/HomeAlertSaveSearchPopup.aspx?width=450&height=290&divID='+divID+'&ContactKEY='+ContactKEY+'&SearchCriteriaKEY='+SearchCriteriaKEY, '');
    }
   else
    {
	    tb_show('Name this search', DOCUMENT_ROOT + '/POP/HomeAlertSaveSearchPopup.aspx?width=400&height=200&divID='+divID+'&ContactKEY='+ContactKEY, '');
	}
}

//*********************************************************************************
// [Return True or False]Validate form elements and make sure all the required fields are being filled
//********************************************************************************* 
function form_validationOnly(formID, 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("Please fill in the required field.");
			inputFields[i].focus();
			return false;
		}
	}
	return true;
}


//*********************************************************************************
// [Go to Process Page]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("Please fill in the required field.");
			inputFields[i].focus();
			return;
		}
	}
	processForm(formID, ProcessPage, MsgID);
}
    
//*********************************************************************************
// Serialize all form elements into a string
//********************************************************************************* 
function serializeForm(formID)
{
    var params = $('#'+formID).fastSerialize();
    var fragment = $.param( params );
    return fragment;
}

//*********************************************************************************
// Submit the form to a processing page thru ajax
//********************************************************************************* 
function processForm(formID, ProcessPage, MsgID)
{
    var formData = serializeForm(formID);
    $('#'+MsgID).html('<img src="'+DOCUMENT_ROOT+'/images/bg_loading.gif" border="0"> Now sending request...');	
	$.ajax({
	  type: "POST",
	  url: ProcessPage,
	  data: formData,
	  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('Email has be sent.');
			tb_remove();
		}
		else if ($.trim(msg)=='-1') $('#'+MsgID).html('Error, please contact our web administrator.');			
		
	  }
	});
}

//*************************************************************************
// 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);
}


//***************************************************************************************************
// Email the property to a friend from result page
//***************************************************************************************************
function emailProperty(MLSNum)
{
	tb_show('Email Friend', DOCUMENT_ROOT + '/POP/EmailProperty.aspx?height=200&width=480&k=' + MLSNum,'');	
}

//***************************************************************************************************
// Open Up Driving driection page
//***************************************************************************************************
function drivingDirection(MLSNum)
{
	//tb_show('Driving Direction', DOCUMENT_ROOT + '/POP/DrivingDirection.aspx?height=200&width=480&k=' + MLSNum,'');	
	window.open(DOCUMENT_ROOT + '/POP/DrivingDirection.aspx?k=' + MLSNum);
}

//***************************************************************************************************
// Check the if it is a number
//***************************************************************************************************
function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
	  {
	  Char = sText.charAt(i);
	  if (ValidChars.indexOf(Char) == -1)
		 {
		 IsNumber = false;
		 }
	  }
   return IsNumber;
}



//***************************************************************************************************
// Home Alert Login Function for C#.net
//***************************************************************************************************

function emptyFunction(){}

var swipeFunction = null;    var swipeParam = null;    
    
function LoginForHomeAlert(formID, MsgID, fucOnSuccess)
{
    
    if (DataFloat.Agora.Util.ValidateForm(formID)){
        $('#' + MsgID).html('<img src="'+DOCUMENT_ROOT+'/images/bg_loading.gif" border="0">Checking login...');	
        var oAjaxManager = new DataFloat.Agora.AjaxManager(serializeForm(formID));
        
        oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerRetriveContactData, 1, function(msg){
            
            if ($.trim(msg)!='0'){
                if (fucOnSuccess!=undefined) fucOnSuccess($.trim(msg)) 
                else{
                    ContactEmail = $("#7300_req").val();
                    ContactKEY = $.trim(msg);
                    DataFloat.Agora.NewTrackAjax(DataFloat.Agora.NewTrack.TrackingType.Login, ContactKEY, '', '', '', function(){})
                    AjaxManagerContact = new DataFloat.Agora.AjaxManager("item=Contact.OWNER&item=Contact.ContactKEY");
                    AjaxManagerContact.NewSystemRequest(DataFloat.Agora.Services.ServiceSessionManagerGetSessionVariable, 1, CheckContactAgent);
                  
                    //window.location.href = "/UserAccount.aspx"; //alert(msg);
                } 
            }else alert('Invalid Email and/or Password.'); $('#'+MsgID).html('');    
        }
        )
    }
}

function CheckContactAgent(data){
    agentResult = JSON.parse(data);

    ContactOWNER = agentResult.ContactOWNER;
    RedirectPage = (DataFloat.Agora.Util.IsEmptyOrNull(DataFloat.Agora.Util.Request.QueryString['ref'])) ? "/UserAccount.aspx?" : DataFloat.Agora.Util.ReplaceAll(DataFloat.Agora.Util.Request.QueryString['ref'], "##", "&");

    if (ContactOWNER != Agora_Default_Agent_Key){
        AspNet_formParams = "HtmlInterface=TransformToJSON&fld_0630=AgentWebsite&RecordType=3&n_dt=0&Agora__ItemPerPage=9999&n_k=" + ContactOWNER;
        AjaxManagerContact.FormParams = AspNet_formParams;
        AjaxManagerContact.ItemPerPage = 2;
        AjaxManagerContact.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerGetContentJSON, 1, RedirectUser);
    }else{
        if (DataFloat.Agora.Util.IsEmptyOrNull(swipeFunction))
            window.location.href = RedirectPage;
        else
            swipeFunction(swipeParam);
    }
}

function RedirectUser(agentResult){
    agentResult = JSON.parse(agentResult);
    if (agentResult.length == 1){
        if (agentResult[0].AgentWebsite != undefined){

            if (!DataFloat.Agora.Util.IsEmptyOrNull(swipeFunction))
                swipeFunction(swipeParam); //It wont work because the page will redirect first.
            if (agentResult[0].Key!="10") window.location.href = 'http://' + agentResult[0].AgentWebsite + '/HomeAlertListHashLogin.aspx?ContactEmail=' + ContactEmail + '&ContactKEY=' + ContactKEY + "&ref=" + DataFloat.Agora.Util.ReplaceAll(RedirectPage.replace("?", "####"), "&", "##");
            else window.location.href = '/HomeAlertListHashLogin.aspx?ContactEmail=' + ContactEmail + '&ContactKEY=' + ContactKEY + "&ref=" + DataFloat.Agora.Util.ReplaceAll(RedirectPage.replace("?", "####"), "&", "##");
            
        }else{
            if (!DataFloat.Agora.Util.IsEmptyOrNull(swipeFunction))
                window.location.href = RedirectPage + "&AgentWebsite=0";
            else
                swipeFunction(swipeParam);
            
        }
    }else{
        if (DataFloat.Agora.Util.IsEmptyOrNull(swipeFunction))
            window.location.href = RedirectPage;
        else
            swipeFunction(swipeParam);    
    }
}


// For QuickSearch special Property Type combo dropdown
function triggerPropertyTypeChange(Val)
{
    var arr = Val.split("_");
    var fldKey = arr[0];
    var eVal = arr[1];
    $('#0040').val('');
    $('#0050').val('');    
    $('#'+fldKey).val(eVal);
}

//*****************************************************************************************************
// Common function for showing up thickbox
//*****************************************************************************************************
function showThickBox(title, url)
{
    tb_show(title,url.replace(/ /g,"%20"),'');
}

function popUp(url, width, height)
{
    window.open(url,'','width='+width+',height='+height);
}