// 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;
var RedirectPage        = null;
var CREATOR;


//Date
var now = new Date();
var Month = (now.getMonth()+1).toString();
if (Month.length==1) Month = "0" + Month;
var FullDate = now.getFullYear().toString() + Month + now.getDate().toString();   

//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;

//*************************************************************************
// 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.
//**********************************************************************

//*********************************************************************************
// Check the user login status (Do not Delete)
//*********************************************************************************
function checkLogin(divID, info, index, ListingAgent, PropertyIDE)
{
	// 1 = Save Search
	// 2 = Save Listing
	// 3 = Save Area
	// 4 = Remove Listing
    // 5,6 = Rating Property
    // 7 = Property Notes
    
    var params = "section=checkLogin&returnFields=Contact.ContactKEY";
    var oAjaxManager = new DataFloat.Agora.AjaxManager(params);
        oAjaxManager.NewSystemRequest(ProcessCheckLogin, 1, function(msg){
        //alert(msg);
            ContactKEY = msg;
            PropertyIDE = (escape(PropertyIDE));
            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('Home Alert Login', HomeAlertPopupLogin + '?width=430&height=250&divID='+divID+'&index='+index, '');
				                    break;
					    case "2":   tb_show('Home Alert Login', HomeAlertPopupLogin + '?width=430&height=250&index='+index+'&divID='+divID+'&info='+info+'&ListingAgent='+ListingAgent+'&PropertyIDE='+PropertyIDE, '');
					                break;
					    case "3":   tb_show('Home Alert Login', HomeAlertPopupLogin + '?width=430&height=250&index='+index+'&divID='+divID+'&info='+info+'&ListingAgent='+ListingAgent+'&PropertyIDE='+PropertyIDE, '');
					                break;
					    case "4":   tb_show('Home Alert Login', HomeAlertPopupLogin + '?width=430&height=250&index='+index+'&divID='+divID+'&info='+info+'&ListingAgent='+ListingAgent+'&PropertyIDE='+PropertyIDE, '');
					                break;
					    case "5":   tb_show('Home Alert Login', HomeAlertPopupLogin + '?width=430&height=250&index='+index+'&divID='+divID+'&info='+info+'&ListingAgent='+ListingAgent+'&PropertyIDE='+PropertyIDE, '');
					                break;
					    case "6":   tb_show('Home Alert Login', HomeAlertPopupLogin + '?width=430&height=250&index='+index+'&divID='+divID+'&info='+info+'&ListingAgent='+ListingAgent+'&PropertyIDE='+PropertyIDE, '');
					                break;
                        case "7":   tb_show('Home Alert Login', HomeAlertPopupLogin + '?width=430&height=250&index='+index+'&divID='+divID+'&info='+info+'&ListingAgent='+ListingAgent+'&PropertyIDE='+PropertyIDE, '');
					                break;
					    default: alert("javascript error in [check login]");
					}
				}
			}else
			{
			    switch(index)
			    {
			        case "1":   callHomeAlertSaveSearch(divID, ContactKEY);
			                    break;
				    case "2":   rateThisProperty(divID, info, ContactKEY, ListingAgent, PropertyIDE, true);					
				                break;
				    case "3":   saveAreaSearch(divID, info, ContactKEY);
				                break;
				    case "4":   removeProperty(divID, info, ContactKEY);
				                break;
				    case "5":   rateThisProperty(divID, info, ContactKEY, ListingAgent, PropertyIDE, false);
				                break;
				    case "6":   rateThisProperty(divID, ContactKEY, ListingAgent, PropertyIDE);
			                    break;
                    case "7":   saveNotes(divID, info, ContactKEY, ListingAgent, PropertyIDE);
			                    break;
				    default:    alert("javascript error in [check login]");
			    }
			}
        }
    )    
}


function saveNotes(divID, info, ContactKEY, ListingAgent, PropertyIDE){
    //NotesFeedback_{$PT}_{@k}
    // info is the Note textarea ID
    var arrData = info.split('_');
    var mlsNumber = arrData[2];
    var propertyType = arrData[1];
    var note = $('#'+divID).val();
    
    var GetSessions = new DataFloat.Agora.AjaxManager("item=Contact.OWNER");
        GetSessions.NewSystemRequest(DataFloat.Agora.Services.ServiceSessionManagerGetSessionVariable, 1, function(msg){
        returnSession = (JSON.parse(msg));
        
        //Check to is if already exist a note
        
        //When the field type is 0, means that needs to create some foreign key
        //For that, the field name must have a "special name", it means add "_n_k" on the end
        //ActionType=1 = INSERT
        //ActionType=2 = UPDATE
        //ActionType=4 = UNDELETED
        //if exists
        PropertyIDE = escape(PropertyIDE);
        
        var params = "0070=5&0090=" + PropertyIDE + "&0030="+mlsNumber+"&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){        
        
        
            //To Check if this property is saved to my porfolio
            // If this property is already saved in my porfolio
            // We do a update, otherwise we will insert
            // Recordtype 14 is dft_matchedproperty
            // n_partial = 1
            // 0040 is mlsnum
            // 0020 is PropertyType
            // n_dt DELETED=0
            // 0010_n_k MPLINKCONTACT 
            // 
            var params2 = "0070=5&0030="+mlsNumber+"&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"; //Default is insert.
                    if ($.trim(msg)!="0") actionType = "2"; // Update
                    
                    ListingAgent = (ListingAgent == '') ? Agora_Default_Agent_Key : ListingAgent;
                    
                    // To set the value of the creator as per the agent slctd by the user//
                    var oAjaxManager0 = new DataFloat.Agora.AjaxManager("item=Contact.OWNER");
                    oAjaxManager0.NewSystemRequest(DataFloat.Agora.Services.ServiceSessionManagerGetSessionVariable, 1, function(msg){
                        
                        var data = JSON.parse(msg);                        
                        CREATOR = data.ContactOWNER;
                    
                    
                    //alert("CREATOR "+CREATOR);
                    
                    if(CREATOR != null && CREATOR != undefined)
                    {
                        ListingAgent = CREATOR;
                    }
                    
                    //alert("ListingAgent "+ListingAgent);
                    
                    // To set the value of the creator as per the agent slctd by the user//
                    
                    var Params = "0070=5&RecordType=14&ActionType="+actionType+"&0090=" + PropertyIDE + "&0020=" + propertyType + "&0030=" + mlsNumber + "&0010_n_k=" + ContactKEY + "&n_uc=" + ListingAgent + "&n_ub=" + ListingAgent + "&n_partial=1&0050=" + $("#" + divID).val();
                    var InsertObject = new DataFloat.Agora.AjaxManager(Params);
                    InsertObject.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerSetData, 1, function(msg){
                        alert('Notes saved');
                    });
                    
                    });
                })        
  
           })
    });
}


function rateThisProperty(divID, info, ContactKEY, ListingAgent, PropertyIDE, isFavorite)
{
    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="/images/ran_bg_loading.gif" border="0"/> Rating Property');
    else $('#' + divID).html('<img src="/images/ran_bg_loading.gif" border="0"/> Saving Property');
    
    checkIsRatedProperty(divID, info, MLSNum, PropertyType, rating, ratingClass, ContactKEY, ListingAgent, PropertyIDE ,isFavorite);
}

function checkIsRatedProperty(divID, info, MLSNum, PropertyType, rating, ratingClass, ContactKEY, ListingAgent, PropertyIDE, isFavorite)
{
//HERE
    // ActionType = 4 is undeleted
    var mpusage;
    if (isFavorite)
        mpusage = "&0070=1";
    else
        mpusage = "&0070=3";
        
    var params = "0030="+MLSNum+"&RecordType=14&0020="+PropertyType+"&n_dt=1&0010_n_k="+ContactKEY+"&ActionType=4" + mpusage;
    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 + mpusage;;
            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, ListingAgent, PropertyIDE, isFavorite);
                })
         })
}


function submitRatingProperty(divID, info, MLSNum, PropertyType, rating, ratingClass, ContactKEY, s, ListingAgent, PropertyIDE, isFavorite)
{
        ListingAgent = (ListingAgent == '') ? Agora_Default_Agent_Key : ListingAgent;
        
        // To set the value of the creator as per the agent slctd by the user//
        var oAjaxManager0 = new DataFloat.Agora.AjaxManager("item=Contact.OWNER");
        oAjaxManager0.NewSystemRequest(DataFloat.Agora.Services.ServiceSessionManagerGetSessionVariable, 1, function(msg){
            
            var data = JSON.parse(msg);
            CREATOR = data.ContactOWNER;
        
        
        //alert("CREATOR "+CREATOR);
        
        if(CREATOR != null && CREATOR != undefined)
        {
            ListingAgent = CREATOR;
        }
        
        //alert("ListingAgent "+ListingAgent);
        // To set the value of the creator as per the agent slctd by the user//
        
        var mpusage;
        if (isFavorite)
        {
            mpusage = "&0070=1";
            DataFloat.Agora.NewTrackAjax(DataFloat.Agora.NewTrack.TrackingType.SaveProperty, ContactKEY, '', '', '', function(){})
        }else
        {
            mpusage = "&0070=3";
        }
        var params = "ActionType="+s+"&n_dt=0&0090=" + PropertyIDE + "&0080=1&0030="+MLSNum+"&RecordType=14&0020="+PropertyType+"&0010_n_k="+ContactKEY+mpusage;
        //if (s=='2') params+="&n_partial=1";        
        n_uc = ListingAgent;
        if (s=='1') params += "&n_uc=" + ListingAgent;
            if (ratingClass!="") params += "&0060="+rating;
            var oAjaxManager = new DataFloat.Agora.AjaxManager(params);
            oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerSetData, 1, function(msg){
                    if (ratingClass!="")
                    {
                        $('#'+MLSNum+'_'+PropertyType+'_1').removeClass("one-star-active").attr('class', 'one-stars'); 
                        $('#'+MLSNum+'_'+PropertyType+'_2').removeClass("two-star-active").attr('class', 'two-stars'); 
                        $('#'+MLSNum+'_'+PropertyType+'_3').removeClass("three-star-active").attr('class', 'three-stars'); 
                        $('#'+MLSNum+'_'+PropertyType+'_4').removeClass("four-star-active").attr('class', 'four-stars'); 
                        $('#'+MLSNum+'_'+PropertyType+'_5').removeClass("five-star-active").attr('class', 'five-stars'); 
                        
                        $('#'+info).attr('class', ratingClass);
                        $('#'+divID).html("Property is rated");
                    }else{
                         $('#'+divID).hide();
                         $('#removeListing'+divID.substring(divID.indexOf('_'))).show();
                        //$('#'+divID).html("Marked as favorite");
                        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(divID, MLSNumberWithPT, ContactKEY)
{
    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];
        $('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/images/ran_bg_loading.gif" border="0">Removing Favorite Property...');	
        var oAjaxManager = new DataFloat.Agora.AjaxManager("RecordType=14&ActionType=3&0070=1&0010_n_k="+ContactKEY+"&0020="+PropertyType+"&0030="+MLSNum+"&n_dt=0");
        oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerSetData, 1, function(msg){
		    //$('#' + divID).html('Property is removed');
		    $('#' + divID).hide();
		    $('#saveListing'+divID.substring(divID.indexOf('_'))).show();
		    $('#' + divID).css('color','red');
        })
    }
}

//*********************************************************************************
// Set the Search Criteria Name (Do not delete me)
//********************************************************************************* 
function saveSearch(SearchCriteriaName, divID, ContactKEY)
{
    $('#' + divID).html('<img src="'+DOCUMENT_ROOT+'/images/ran_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'];
    
    if (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=450&height=290&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/ran_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 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.GuidKEY&item=Contact.Email");
                    AjaxManagerContact.NewSystemRequest(DataFloat.Agora.Services.ServiceSessionManagerGetSessionVariable, 1, CheckContactAgent);
                    
                    //window.location.href = "/HomeAlertList.aspx"; //alert(msg);
                    //window.location.href = "/UserAccount.aspx"; //alert(msg);
                } 
            }else alert('Invalid Email and/or Password.'); $('#'+MsgID).html('');    
        }
        )
    }
}

function UpdateLoginTimeStamp(data)
{
    agentResult = JSON.parse(data);
    AjaxManagerContactUpdate = new DataFloat.Agora.AjaxManager("RecordType=4&ActionType=2&n_rk="+agentResult.ContactGuidKEY+"&n_ub="+agentResult.ContactOWNER+"&n_partial=1&n_k="+agentResult.ContactContactKEY+"&7320="+FullDate);
    AjaxManagerContactUpdate.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerSetContactData, 1, emptyFunction);
}

function emptyFunction(){}

var swipeFunction = null;    var swipeParam = null; var ContactGuid = null;
function CheckContactAgent(data){
    agentResult = JSON.parse(data);
    
    ContactEmail = agentResult.ContactEmail;
    ContactOWNER = agentResult.ContactOWNER;
    ContactGuid  = agentResult.ContactGuidKEY;

    RedirectPage = (DataFloat.Agora.Util.IsEmptyOrNull(DataFloat.Agora.Util.Request.QueryString['ref'])) ? "/HomeAlertList.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){
//Added by aneesh on Dec 10  2010 MyHOME logon

agentResult=agentResult.replace("[","");
agentResult=agentResult.replace("]","");


    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.
            window.location.href = 'http://' + agentResult[0].AgentWebsite + '/HomeAlertList.aspx?LoginID='+$("#7300_login_req").val()+'&GUID='+ContactGuid+'&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);
}



