﻿    //Main Objects
    var oGrid;
    var oPowerMap;
    var oPropertySearch;
    var oMapSlider;
    //Settings
    var iListPerPage = 100;
    var iLimitToShow;
    var PageNum = 1;
    var LPP = 10;
    var LoadingResult = false;
    var tDefaultLatLong = new Array();
    var MapLatitude = (!DataFloat.Agora.Util.IsEmptyOrNull(DataFloat.Agora.Util.Request.QueryString["lat"])) ? parseFloat(DataFloat.Agora.Util.Request.QueryString["lat"]) : 38.058905;
    var MapLongitude = (!DataFloat.Agora.Util.IsEmptyOrNull(DataFloat.Agora.Util.Request.QueryString["long"])) ? parseFloat(DataFloat.Agora.Util.Request.QueryString["long"]) : -85.68512;
    //var dLast14days = DataFloat.Agora.Util.getSpecficDate(-100, 0, 0, 'YMD', "");
    var dLast14days = DataFloat.Agora.Util.getSpecficDate(-2, 0, 0, 'YMD', "");
    tDefaultLatLong[320] = {Lat: MapLatitude, Long: MapLongitude};
    var fdlBoard = new Array();
    
    //Variables
    var bAdvacendSearchStatus = true;
    var iCurrentLoad = 0;
    var oCurrentDraw = null;
    var iCurrentImgPreview = 1;
    var oDataMapSource;
    var bDrawHasName = false;
    var allowToDraw = true;
    var iCurrentBoard = 320;
    var arrLoadedPops = new Array();    
    var mapAjax;
    var DrawAreas;
    var oComboManager;
    var arrProperties;

$(document).ready(function() {


    $(".flxCriteria").hide();
    $("#divAdvancedSearch").hide();
    $("#divDirection").hide();
    
    iLimitToShow = 200;
    oPowerMap = new DataFloat.Agora.RealMap("divMapMs");
    oPowerMap.onElementClickUp = DoSearch;

    oComboManager = new DataFloat.Agora.CustomDropBox(document.getElementById('IntineraryOrder'), true);
    
   //New Map
    mapAjax = new DataFloat.Agora.AjaxManager();
    mapAjax.MapManager = oPowerMap;
    mapAjax.MapManager.OnMapChangeCenter = false;
    mapAjax.MapManager.LoadMap();
    mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(tDefaultLatLong[320].Lat, tDefaultLatLong[320].Long), 9)
    mapAjax.MapManager.VirtualMap.AttachEvent("onmouseover", mapAjax.MapManager.OnMouseOverPin);
    mapAjax.MapManager.VirtualMap.AttachEvent("onendzoom", oPowerMap_OnEndZoom);
    mapAjax.MapManager.VirtualMap.AttachEvent("onendpan", CatchEventPOI);
    //New Map
    
    //Map Layout [Layers] Components

    mapAjax.MapManager.AddMessage('InfoBoxContainer', mapAjax.MapManager.NewFixedBox('InfoBox', '', DataFloat.Agora.IU.BoxStyle.Alert) , 'InfoBox');
    
    mapAjax.MapManager.AddMessage('InfoBoxTooMany', mapAjax.MapManager.NewFixedBox('InfoBoxContent', 'More than 100 properties<br/>found. Please Zoom in or narrow Search Criteria<br/>Showing the first 100 properties.', DataFloat.Agora.IU.BoxStyle.Alert) , 'InfoBox');
    
    mapAjax.MapManager.AddMessage('DrawingBoxContainer',mapAjax.MapManager.NewFixedBox('DrawingBox', '<br/><u>To draw square box over interested area:</u><br/><br/>1.	Place hand near area of interest<br/><br/>2.	Left click on mouse and hold button<br/><br/>3.	Drag square box to cover interested area', DataFloat.Agora.IU.BoxStyle.Neutral) , 'DrawingBox');
        
	accordionActions();    
	
	DoSearch();
})


    function ShowSpecificListings(Val)
    {
        if (Val=="new")
        {
            $(".DefaultPin").hide();
            $(".NewPin").show();
        }else if (Val=="act")
        {
            $(".DefaultPin").show();
            $(".NewPin").hide();            
        }else if (Val=="")
        {
            $(".DefaultPin").show();
            $(".NewPin").show();                        
        }
    }   

    function ShowAdvancedSearch(){
        $("#divAdvancedSearch").show();
        $(".flxCriteria").hide();
        $("#divExteriorFeature").show();
    }
    
    function UpdateMap(){
        $("#divAdvancedSearch").hide();
        DoSearch();
    }
    
    function CloseCriteria(){
        $("#divAdvancedSearch").hide();
        return false;
    }
    
    function ShowCriteria(divFeature){
        $(".flxCriteria").hide();
        $("#" + divFeature).show();
    }
    
    function UpdateAdvancedCriteria(){
        $("#txtExtFeature").html(($("#string_Exterior").val() == '' ? 'No Criteria' : $("#string_Exterior").val()));
        $("#txtIntFeature").html(($("#string_Interior").val() == '' ? 'No Criteria' : $("#string_Interior").val()));
        $("#txtPropStyle").html(($("#string_PropertyStyle").val() == '' ? 'No Criteria' : $("#string_PropertyStyle").val()));
        $("#txtGarage").html(($("#string_Garage").val() == '' ? 'No Criteria' : $("#string_Garage").val()));
        $("#txtLotDetails").html(($("#string_LotDetails").val() == '' ? 'No Criteria' : $("#string_LotDetails").val()));
        $("#txtStories").html(($("#string_Stories").val() == '' ? 'No Criteria' : $("#string_Stories").val()));
        $("#txtAcreage").html(($("#int_AcresMin").val() == '' ? 'No Criteria' : $("#int_AcresMin").val()));
        
    }
    
    function SetMapLocation(BoardId){
        iCurrentBoard = 320;
        mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(tDefaultLatLong[320].Lat, tDefaultLatLong[320].Long), 10)
    }
    
    function ViewPropertyDetails(MlsNumber){
		    window.open('/PropertyDetail.aspx?RecordType=180&searchType=Map&get=1&Agora__Item__Detail=1&0110_exc=' + MlsNumber);
		}

    function AdvancedSearchTab_OnClick(){
	    if (bAdvacendSearchStatus)
	        $('#SearchCriteria').hide();
	    else
	        $('#SearchCriteria').show();
	    bAdvacendSearchStatus = !bAdvacendSearchStatus;
	}
	
	function DoSearch(pinObject){
	    $("#divDirection").hide();
	    $("#results_list").show();
        var oPinClick = null; 
	    if (pinObject != undefined)
	        oPinClick = oPowerMap.VirtualMap.GetShapeByID(pinObject.elementID);
   
   	    if (oPinClick == null){
	        mapAjax.StopAllRequest();
            var VELatLongRectangle = oPowerMap.VirtualMap.GetMapView();
	    
		    //New Map Search
		    
		    var drawParam;
		    var arrCheckArea = $('.cbxmyareas');
		    var arrCheckAreaToSearch = new Array();
		    var arrAllDraw = oPowerMap.GetAllDraw();
		    if (arrCheckArea.length > 0){
		        var arrDrawAreasToSearch = new Array();
		        for (iCkA=0;iCkA<arrCheckArea.length;iCkA++){
		            if (arrCheckArea[iCkA].checked)
		                arrCheckAreaToSearch.push(arrAllDraw[iCkA]);
		        }
		    }
		    drawParam = (arrCheckAreaToSearch.toAgoraAreaSearch());
	        
		    var searchLatMin, searchLatMax, searchLongMin, searchLongMax;
		    if (drawParam == ''){
		        searchLatMin = VELatLongRectangle.BottomRightLatLong.Latitude;
		        searchLatMax = VELatLongRectangle.TopLeftLatLong.Latitude;
		        searchLongMin = VELatLongRectangle.TopLeftLatLong.Longitude;
		        searchLongMax = VELatLongRectangle.BottomRightLatLong.Longitude;
            }else{
                var arrSplitLat = drawParam.split('|');
                var pointA = arrSplitLat[0].split(',');
                var pointB = arrSplitLat[1].split(',');
                var pointC = arrSplitLat[2].split(',');
                                
                searchLatMin = pointB[0];
		        searchLatMax = pointA[0];
		        searchLongMin = pointA[1];
		        searchLongMax = pointC[1];
                if (searchLatMin > searchLatMax)
                {
                    var searchLatTemp = searchLatMin;
                    searchLatMin = searchLatMax;
                    searchLatMax = searchLatTemp;
                }
                if (searchLongMin < searchLongMax)
                {
                    var searchLongTemp = searchLongMin;
                    searchLongMin = searchLongMax;
                    searchLongMax = searchLongTemp;            
                }
            }		    
		    var mapParam = "Agora__ItemPerPage=101&dec_LatMin=" + searchLatMin + "&dec_LatMax=" + searchLatMax + "&dec_LongMin=" + searchLongMin + "&dec_LongMax=" + searchLongMax + "&" + serializeForm('frmMapSearch') + '&' + serializeForm('frmAdvCriteria');
		    mapAjax.ItemPerPage = 101;
		    mapAjax.FormParams = mapParam;
            mapAjax.NewSystemRequest(DataFloat.Agora.Services.ServiceMapSearch, null, oMapSearch_OnLoad);
            return false;
        }else{
            MlsNumber = oPinClick.MlsNumber; 
            oPowerMap_PinClick(null, MlsNumber);
        }
	}
	
	function oMapSearch_OnLoad(result){
	        //AdvancedSearchTab_OnClick();
	        arrProperties = JSON.parse(result);
	        mapAjax.MapManager.ClearAll();
	  	    var arrPin = new Array();
	  	    var arrMls = new Array();
	  	    $("#divSearchResults").html('');
	  	    if (arrProperties[0] != null)
	  	        $("#InfoBox").html('<span>' + arrProperties[0].Total + '</span><br/>Properties Found');
	  	    else
	  	        $("#InfoBox").html('<span>No Properties</span><br/>Found');
	  	        
	  	    $("#InfoBoxTooMany").hide();
	  	    if (arrProperties.length > (mapAjax.ItemPerPage - 1))
	  	        $("#InfoBoxTooMany").show();
            
            $("#InfoBox").show();
            
            
	  	    var ActiveListing = 0;
	  	    var NewListing = 0;
	  	    var showResult = (arrProperties.length > (mapAjax.ItemPerPage-1)) ? (mapAjax.ItemPerPage-1) : arrProperties.length;
	  	    for(var i = 0; i < showResult; i++){
                iMLSNum = arrProperties[i]["mls"];
                iLatitude = arrProperties[i]["lat"];
                iLongitude = arrProperties[i]["long"];
                iKmls = arrProperties[i]["kmls"];
                iListDate = arrProperties[i]["listdate"];
                arrMls.push(arrProperties[i]["mls"]);
                if (iLatitude && iLongitude)
                {
                    if (parseInt(iListDate) >= dLast14days)
                    {
                        NewListing++;
                        PinClass =  "NewPin"; 
                    }else 
                    {
                        ActiveListing++;
                        PinClass =  null; 
                    }
					arrPin[arrPin.length] = new mapAjax.MapManager.PinObject(i, null, iLatitude, iLongitude, iMLSNum, PinClass, null, iKmls);
			    }
            }
            $("#NewCount").html(NewListing.toString());
            $("#ActiveCount").html(ActiveListing.toString());
            mapAjax.MapManager.NewItem(arrPin);
            StartListView();
	}
		
	function GetNumber(mls)
	{
	    var ListingClass = $(".Agora_Pin_"+mls).attr("class");
	    if (ListingClass.indexOf("NewPin")!=-1)
	    {
	        $("#Status_"+mls).removeClass("active");
	        $("#Status_"+mls).addClass("new");
	    }
	    var CurrentPosition = $(".Agora_Pin_"+mls).attr("id").replace("Agora_Pin_","");
	    $("#Number_"+mls).html(CurrentPosition);
	}
	
	function CheckStatus(HolderID, Date)
	{  
	    //var dLast14days = DataFloat.Agora.Util.getSpecficDate(-14, 0, 0, 'YMD', "");
	    var dLast14days = DataFloat.Agora.Util.getSpecficDate(-2, 0, 0, 'YMD', "");
	    if (Date >= dLast14days)
	    {
	        $("#"+HolderID).removeClass("active");
	        $("#"+HolderID).addClass("new");
	    }
	}
	
	function ShowOnlySelected()
	{
	    var CheckedListings = $("input:checked[name=ShowOnMap]").get();
	    if (CheckedListings.length>=1)
	    {
	        $("div.DefaultPin").hide();
	        $("div.NewPin").hide();
	        for (var i=0; i<CheckedListings.length; i++)
	        {
	            $('.Agora_Pin_'+CheckedListings[i].value).show();
	        }
	    }else alert("Please check at least 1 listing to show");
	}
	
	function ClearSelected()
	{
        $('input:checked[name=ShowOnMap]').removeAttr('checked'); 
        $("div.DefaultPin").show();
	    $("div.NewPin").show();	
        
	}
	
	function StartListView()
	{
	    PageNum = 1;
        $("#ListingBody").html("");
        GetMapResult();
	}
	
	function GetMapResult()
	{
	    if (arrProperties.length>=1)
	    {
	        $("#processing").html("...Loading&#160;<img src='/images/bg_loading.gif'/>");
	        LoadingResult = true;
	        var ResultMLS = "0110_exc=";
	        for (var i=0; i<arrProperties.length; i++)
	        {
	            FirstList = ((PageNum - 1) * LPP) + 1;
	            LastList = (PageNum * LPP);
	            if (i+1>=FirstList && i+1<=LastList)
	            {
	                if (i+1!=FirstList) ResultMLS += ",";
	                ResultMLS += arrProperties[i]["kmls"];
	            }
	        }
    	    
	        var HtmlView = "MapResult"+$("#results_view").val();
            var AspNet_formParams = "HtmlInterface="+HtmlView+"&RecordType=180&5020_order=descending&"+ResultMLS;
            var ajaxResult = new DataFloat.Agora.AjaxManager(AspNet_formParams);
            ajaxResult.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerMultipleHtml, 1, function(data){
                $("#ListingBody").append(data);
                $("#ListingBody tr:odd").addClass("alt");
                $("#processing").empty();
            });            
        }
	}
	
	/* GRID */
	function OnListViewOver(e)
	{
	    var oPinToFind = oPowerMap.GetPinByMlsNumber(this.id);
	    if (oPinToFind!=null)
	        ShowMapPopup(oPinToFind);

        $('.Agora_Pin_'+this.id).parent().mouseover();
	}	
	
    function OnListViewOut(e)
	{
        $('.Agora_Pin_'+this.id).parent().mouseout();
	}		
	
	//Grid Behavior
	function Grid_OnRowClick(index){
	    ViewPropertyDetails(arrProperties[index].kmls);
	    //ViewPropertyDetails($("#Agora_Grid_Tr_"+index+" .Agora_Grid_mls").html());
	    //oPowerMap_PinClick(null, arrProperties[index].mls, parseInt(index)+1);
	}
	
	function Grid_OnRowMouseOver(index){
	    var oPinToFind = oPowerMap.GetPinByMlsNumber(arrProperties[index].kmls)
        $("#Agora_Pin_"+(parseInt(index)+1)).parent().mouseover();
	    oPowerMap.HigligthPin(parseInt(index)+1);
	    
	}
	
	function Grid_OnRowMouseOut(index){
	    oPowerMap.RemoveHigligth(parseInt(index)+1);
	}
	//Grid Behavior
	
	function NavGrid(direction, page){
	    page = String.IsEmptyOrNull(direction) ? page : oGrid.CurrentPage + direction;
	    oGrid.LoadContent(page);oGrid.CreateNavigation('NavGrid');
	}
	
	
	/* GRID */

	/* MAP */
	function oPowerMap_PinClick(e, MlsNumber, index){
	    if (!oPowerMap.DrawMode){
	        oPowerMap.RemoveAllHigligth();
	        if (e != null && e != undefined){ oPinClick = oPowerMap.VirtualMap.GetShapeByID(e.elementID); if (oPinClick!=null) { MlsNumber = oPinClick.MlsNumber; index = oPinClick.Position+1;}}
	        if ((MlsNumber != null && MlsNumber != undefined)){
	            oPowerMap.HigligthPin(index);
	            iCurrentImgPreview = 1;
	            var oPropertySearchPreview = new DataFloat.Agora.AjaxManager();    
	            oPropertySearchPreview.FormParams = "RecordType=" + iCurrentBoard + "&0110_exc=" + MlsNumber + "&HtmlInterface=NewMapPreview";
	            oPropertySearchPreview.NewRequest(DataFloat.Agora.Services.ServiceGetHtmlContent, 1, null, "PropertyPreview", true);
	        }else{
	            //DoSearch();
	        }
        }
    }
    
    /* MAP */
        //Draw feature
        DrawArea = oPowerMap_DrawArea; //Alias, just for HTML call propose {It means, just for HTML call propose]
        function oPowerMap_DrawArea(){
            if (allowToDraw){
                bDrawHasName = false;
                oPowerMap.StartDraw(oPowerMap_OnDrawFinish, DataFloat.Agora.RealMap.DrawType.Square);
                $('#DrawingBoxContainer').show();
                $('#SearchCriteria').hide();
                $('#InfoBoxContainer').hide();
            }else{
                alert('You may draw one area only');
            }    
        }
        
        function oPowerMap_CheckDrawName(){
            if (!bDrawHasName){
                oPowerMap.DeleteArea(oCurrentDraw.GetID());
                oPowerMap_OnCheckDrawPermission();
            }
            
        }
        
        function oPowerMap_OnCheckDrawPermission(){
            if (oPowerMap.DrawAreas.length >=1)
                $("#imgMap").attr('src', 'Images/ran_bt_draw_off.gif');
            else
                $("#imgMap").attr('src', 'Images/ran_bt_draw.gif');
            allowToDraw = (oPowerMap.DrawAreas.length >=1) ? false : true;
        }
        
        function oPowerMap_OnDrawFinish(oDraw){
            oCurrentDraw = oDraw;
            //$('#DrawingBoxContainer').hide();
            
            //tb_show('Map Search', '/POP/AreaNamePopup.aspx?height=175&width=325');
            SubmitAreaname();
            $("#TB_window").bind("unload", oPowerMap_CheckDrawName);
            if (bAdvacendSearchStatus)
                $('#SearchCriteria').show();

            oPowerMap_OnCheckDrawPermission();
        }
    	
    	
	    function SubmitAreaname(){
	        var AreaName = "New Area";//$.trim($('#shapeTitle').val()); //The name of the field [textbox] into the Pop box
	        if (AreaName != '')
	            bDrawHasName = true;
	        var arrAreas = oPowerMap.GetAllDraw();
    	    
	        for (iArea=0;iArea<arrAreas.length;iArea++){
	            if (AreaName.toUpperCase() ==  arrAreas[iArea].Title.toUpperCase() || AreaName == ''){
	                $('#MsgDisplay').html('Please name this search'); //Name into the pop box
			        $('#MsgDisplay').css('color','red'); //Name into the pop box
			        return;
	            }
	        }
	        //tb_remove();
	        oPowerMap.SetDraw(oCurrentDraw, AreaName);
	        AddDrawRow(oCurrentDraw);
	        DoSearch();
	        oCurrentDraw = null;
	        
	        $('#DrawingBoxContainer').hide();
	        $('#InfoBoxContainer').show();
	    }
    	
    	
	    function DeleteDrawRow(IdDraw, Title){
	        $('#tr_'+IdDraw).remove();
	        oPowerMap.DeleteArea(IdDraw);
	        oPowerMap_OnCheckDrawPermission();
	    }
    	
	    function AddDrawRow(oDraw){
	        
	        //Hard code for now
	        var shapeID = oDraw.GetID();
            var shapeTitle = oDraw.Title;
            var theLat = oDraw.Latitude;
            var theLng = oDraw.Longitude;
                strMyMapInfo = '<tr id="tr_'+shapeID+'"><td><input type="checkbox" class="cbxmyareas" value="' 
                    + shapeID + '" name="cbxmyareas" checked="true"/>&#160;&#160;' + unescape(shapeTitle) + '&#160;&#160;<a href="javascript:DeleteDrawRow(\'' + shapeID + '\', \'' + shapeTitle 
                    + '\')">Remove</a>&#160;&#160;</td><td id="Msg_'+shapeID+'"></td></tr>';
            $('.SaveAreaTitle').append(strMyMapInfo);
            //<a class="LinkArea" href="javascript:checkLogin(\'Msg_'+shapeID+'\',\'' + shapeID + '\',\'3\')">Save</a>

	    }
	    //Draw feature
	/* MAP */
	
	function GoPhoto(Direction, ImgName, IndexName, Count, ImgSrc){
	        iCurrentImgPreview = $("#" + IndexName).html();
		    iCurrentImgPreview =  parseInt(iCurrentImgPreview) + (1*Direction);
		    if (iCurrentImgPreview <= 1)
		    {
		        $('.Previous').hide();
		        iCurrentImgPreview=1;
		    }else $('.Previous').show();
		    if (iCurrentImgPreview >= Count)
		    {
		        $('.Next').hide();
		        iCurrentImgPreview=Count;
		    }else $('.Next').show();
		    	    		    
		    $('#' + IndexName).html(iCurrentImgPreview);
		    $("#" + ImgName).attr('src', $('#ImageIndex_' + iCurrentImgPreview).val());
		    
		}   
		
		DataFloat.Agora.RealMap.prototype.drawSquare = function(OldDrewAreas)
		{
		    try
		    {
		        this.g_shapePoints = new Array();
		        this.g_tempShape = null;
		        this.g_tempPoints = null;
				DataFloat.Agora.Global.MapObjectCurrentInstance = this;		    
		    
                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempPoints = new Array();
                
                var P1 = new VELatLong(DrawAreas[0].LatLong[0].Lat, DrawAreas[0].LatLong[0].Long);
                var P2 = new VELatLong(DrawAreas[0].LatLong[1].Lat, DrawAreas[0].LatLong[1].Long);
                var P3 = new VELatLong(DrawAreas[0].LatLong[2].Lat, DrawAreas[0].LatLong[2].Long);
                var P4 = new VELatLong(DrawAreas[0].LatLong[3].Lat, DrawAreas[0].LatLong[3].Long);
                var P5 = new VELatLong(DrawAreas[0].LatLong[0].Lat, DrawAreas[0].LatLong[0].Long);              

                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempPoints.push(P1);
                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempPoints.push(P2);
                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempPoints.push(P3);
                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempPoints.push(P4);
                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempPoints.push(P5);
                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempShape = new VEShape(VEShapeType.Polygon,DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempPoints );
                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempShape.SetFillColor(new VEColor(0,128,0,0.1));
                DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempShape.HideIcon();                              
                try{
                    DataFloat.Agora.Global.MapObjectCurrentInstance.DrawAreaLayer.AddShape(DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempShape);
                    oPowerMap_OnDrawFinish(DataFloat.Agora.Global.MapObjectCurrentInstance.g_tempShape);
                }catch(err)
                {
                    alert(err.description);
                }

                DataFloat.Agora.Global.MapObjectCurrentInstance.DrawAreaLayer.Show();
		    }
			catch(err)
			{
			    //alert('_virtualMapsearch.js::drawPolygonMouseMove: ' + err.description); 
				$AgoraLog.WriteLog('[DataFloat.Agora.RealMap.drawSquareMouseMove] - ERROR - ' + err.description);
			}
		}
		
        DataFloat.Agora.RealMap.prototype.OnMouseOverPin = function(e){
        
	        if(e.elementID)
	        {
		        var pin = mapAjax.MapManager.VirtualMap.GetShapeByID(e.elementID);
        		ShowMapPopup(pin);
	        }
        }	
		
        function ShowMapPopup(pin){
            var k = pin.MlsNumber;
            
            
        		if (arrLoadedPops[k] == undefined){
		            arrLoadedPops[k] = true;
                    
		            //if (!IsNumeric(k)) return;
		            
 		            pin.SetDescription("<div id='PropertyInfo_"+k+"' style='width:450px' ><img src='/images/ran_bg_loading.gif'/> Loading...</div>"); 
            		
		            mapAjax.MapManager.getPopInfo(k,"PropertyInfo_"+k, pin);
		            
                }
        }		
	
        DataFloat.Agora.RealMap.prototype.getPopInfo = function(k, divID, pinObejct){
            var VEPopUpRequest = new DataFloat.Agora.AjaxManager("RecordType=180&HtmlInterface=MapPopUpInfo&0110_exc="+k);
            VEPopUpRequest.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerMultipleHtml, 1, function(data){
                $("#"+divID).html(data);
                pinObejct.SetDescription(data);
            });
        }			
		
		
		function GetMapPOI(CodeNum, Type)
		{
		    var POIRequest = "20";

		    if ($("#POI"+Type).attr("class")=="POIUnselected")
		    {
		        $("#POI"+Type).removeClass("POIUnselected");
		        $("#POI"+Type).addClass("POISelected");
		        $("#POI"+Type).parent("span").addClass("POISelected");
		        $("#POI"+Type).parent("span").removeClass("POIUnselected");
                mapAjax.MapManager.ShowPOI(DataFloat.Agora.Services.ServicePOI, CodeNum, Type,POIRequest);
            }else
            {
                mapAjax.MapManager.RemovePOI(Type);
		        $("#POI"+Type).removeClass("POISelected");
		        $("#POI"+Type).addClass("POIUnselected");
                $("#POI"+Type).parent("span").removeClass("POISelected");
		        $("#POI"+Type).parent("span").addClass("POIUnselected");		        
            }
	        
		}
		
		var PropertyLatitude = null;
		var PropertyLongitude = null;
		var PropertyAddress = null;
		
        function GetPropertyDirection(Latitude, Longitude, PFullAddress)
        {
            PropertyLatitude = Latitude;
            PropertyLongitude = Longitude;
            PropertyAddress = escape(PFullAddress);
            $("#StartingLocation").focus();
        }
        
        function GetMapDirection(StartLocationID)
        {
            var FromLocation = $("#"+StartLocationID).val();
            if (FromLocation=="") return;
            
            DataFloat.Agora.Util.NewPop('/POP/PropertyDetailMapDirections.aspx?Latitude=' + PropertyLatitude + '&Longitude=' + PropertyLongitude + '&AddressTo=' + PropertyAddress + "&AddressFrom=" + FromLocation, 1000, 500);
        }
        
        var dataSourceDirections;
	    function Directions_OnLoad(route){
	        // Unroll route
               var legs     = route.RouteLegs;
               var iRouteTime = (route.Time/60/60);


               $("#totalMiles").html(route.Distance.toFixed(1));
               $("#routeHour").html(parseInt(iRouteTime));
               $("#routeMinutes").html(parseInt((route.Time/60) % 60));
               
               var numTurns = 0;
               var leg      = null;
               directionLoaded = true;
               dataSourceDirections = new Array();

                for(var i = 0; i < legs.length; i++)
                {

                   leg = legs[i];
                   var turn = null;
                   var currentColor = "odd";
                   for(var j = 0; j < leg.Itinerary.Items.length; j ++)
                   {
                      
                      turn = leg.Itinerary.Items[j];
                      $('#tblDirection tr:last').after('<tr id="' + currentColor + '"><td><p class="first">» ' + turn.Text + '</p></td><td><p>' + turn.Distance.toFixed(1) + ' mi</p></td></tr>');
                      currentColor = (currentColor == "odd") ? "even" : "odd";
                      dataSourceDirections.push({Step: turn.Text, Distance: turn.Distance.toFixed(1)});
                      numTurns++;
                   }
                }
                $("#divDirection").show();
                $("#results_list").hide();
                
                $('#DrawingBoxContainer').hide();
	    }        
    	    
	    function Directions_StillWorking(){
	        $('#DrawingBox').html('<img src="/Css/MapSearch/agora_map_box_ico_alert.gif"/>We are working on your request.<br/>Please wait...');
	    }
	    
	    function Directions_CheckTimeout(){
	        if (!directionLoaded){
	            $('#DrawingBox').html("We didn't get to process your request.<br/><br/><a href='javascript:StartDrivingDirections()'>Try Again</a> &nbsp;&nbsp;&nbsp;<a href='javascript:$(\"#DrawingBoxContainer\").hide();'>Cancel</a>");
                directionLoaded = true;
	        }
	    }
	    
	    function ClearDirection(){
	        mapAjax.MapManager.VirtualMap.DeleteRoute();
	        document.getElementById("IntineraryOrder").length=0;
	    }	    
	    
	    var directionLoaded = true;
	    function ShowDirections(){
    	    
	        var AddressStart = $('#StreetAddress').val();
    	    
	        if (AddressStart != ''){
	            $('#DrawingBoxContainer').show();
	            $('#DrawingBox').html("Processing your request.<br/>Please wait...");
	            var options = new VERouteOptions();
                options.RouteCallback = Directions_OnLoad;
                
	            var arrPoints = new Array();
	            var arrAddress = oComboManager.TextToArray();
                arrPoints.push(AddressStart);
	            for (iA=0;iA<arrAddress.length;iA++)
	                arrPoints.push(arrAddress[iA]);
    	            
	            directionLoaded = false;
	            mapAjax.MapManager.VirtualMap.GetDirections(arrPoints, options);
	            setTimeout("Directions_StillWorking()", 5000);
	            setTimeout("Directions_CheckTimeout()", 10000);
    	    
	        }
	    }
	    
	    function GetIndex(MlsNumber){
	        for (iDs = 0; iDs < arrProperties.length; iDs++){
	            if (arrProperties[iDs].kmls == MlsNumber)
	                return iDs;
	        }
	    }
    	
	    function MoveupItinerary(){
	        oComboManager.MoveUp();
	    }
    	
	    function MovedownItinerary(){
	        oComboManager.MoveDown();
	    }
    	
	    function StartDrivingDirections(){

	        if ($("#StreetAddress").val()!='')
	        {
	            if(oComboManager.DestinationCombo.length > 0){
	                window.open("/Pop/MapDirection.aspx");
	                //ShowDirections();
	                //tb_show('Driving and Directions', '/POP/DrivingDirection.htm?height=180&width=300');
	            }else{
	                alert('Please add one or more properties into your intinerary to start your driving and directions.');
	            }
	        }else alert("Please enter the starting address");
	    }
	    
	    function AddItinerary(MlsNumber){
	        if ($(".directions .content").css("display")!="block")
	        {
		        $(".accordion .section").children(".content").slideUp();
		        $(".accordion .directions").children(".content").slideDown();
		    }
	        var iIndex = GetIndex(MlsNumber);
	        if (!oComboManager.ValueExists(iIndex)){
	            oComboManager.AddItem(iIndex, '(' + (iIndex+1) + ') - ' + arrProperties[iIndex].address) ;
            }
	    }

	
	var MapX;
	var MapY;
	function OnEventCatchPosition(e)
	{
	    MapX = e.mapX;
	    MapY = e.mapY;
	}
	function OnEventMouseForPOI(e)
	{
        if (MapX != e.mapX && MapY != e.mapY)
        {
            CatchEventPOI();
	    }
	}
	
	function CatchEventPOI()
	{
        var POIArr = $(".POISelected").get();
        for (var i=0; i<POIArr.length; i++)
        {
            var FuncName = $('#'+POIArr[i].id).attr("onclick");
            eval(FuncName)();
            eval(FuncName)();
        }
        //return false;
	}
	var ignoreZoomEvent = false;
	function oPowerMap_OnEndZoom(){
	    if (oMapSlider != undefined && !ignoreZoomEvent){
	        var zoomLevel = mapAjax.MapManager.VirtualMap.GetZoomLevel();
	        zoomLevel = parseInt((100 * zoomLevel) / 19);
	        oMapSlider.unsubscribe("change", Slider_OnChange);
	        oMapSlider.setValue(zoomLevel/scaleFactor);
	        oMapSlider.subscribe("change", Slider_OnChange);
	        CatchEventPOI();
        }
	}   
	
	function Slider_SrollOut(){
	    ignoreZoomEvent = true;
	    oMapSlider.setValue(oMapSlider.getValue()-5);
	    setTimeout("ignoreZoomEvent = false;", 2000);
	}
	
	function Slider_SrollIn(){
	    ignoreZoomEvent = true;
	    oMapSlider.setValue(oMapSlider.getValue()+5);
	    setTimeout("ignoreZoomEvent = false;", 2000);
	}
	
	    
	function SliderToMapZoom(SliderLevel){
	    var iSliderLevel = (SliderLevel>100) ? 100 : SliderLevel;
	    var iNew = 6+((19-6)/100) * iSliderLevel;
	    
	    return parseInt(iNew);
	}
	
	
	function Slider_OnChange(offsetFromStart){
	    var iSliderLevel = SliderToMapZoom(oMapSlider.getRealValue()); 
	    
	    mapAjax.MapManager.VirtualMap.SetZoomLevel(iSliderLevel)
	}



//Handles the slide movement of accordion elements
function accordionActions() {
	$('.accordion .content').not('.first').hide();
	$('.accordion .title').click(function() {
		$(this).siblings('.content').slideDown();
		$(this).parents('.accordion').children('.section').children('.content').not($(this).siblings('.content')).slideUp();
	});
}





//***************************************************************************************************
// Compare Properties
//***************************************************************************************************
function addPropertyCompare(Elem)
{
    var iQtyProperty = 0;
    $('.compareLisitngCheckBox').each(function () { 
        if ($(this).attr('checked')){
            iQtyProperty++;
        }
    });
    if (iQtyProperty > 4){
        alert('You cannot compare more than 4 properties');
        return false;
    }
}

function toggleCompare(id)
{
	if ($("#compare_"+id).attr("checked"))
	{
		$("#compare_"+id).removeAttr("checked")
	}else{
		$("#compare_"+id).attr("checked","checked");
	}
}

function checkCompare(){

	var propertyList = DataFloat.Agora.Util.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(DataFloat.Agora.Util.ReadCookie('CompareProperties'));
    }

    function cleanPropertyList()
    {
	    DataFloat.Agora.Util.DeleteCookie('CompareProperties');
    }
    function removeChecked(){
	    $("input").removeAttr("checked");
    }
    function compareProperties()
    {
        var iQtyProperty = 0;
        var sMls = new Array();
        $('.compareLisitngCheckBox').each(function () { 
            if ($(this).attr('checked')){
                iQtyProperty++;
                sMls.push($(this).val());
            }
        });
        if (iQtyProperty > 4){
            alert('You cannot compare more than 4 properties');
            return false;
        }
        

        window.open("PropertyCompare.aspx?RecordType=180&sch=map&0110_exc=" + sMls.join(",")) ;
        
        
    }

    var config = {    
         sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
         interval: 50, // number = milliseconds for onMouseOver polling interval    
         over: OnListViewOver, // function = onMouseOver callback (REQUIRED)    
         timeout: 300, // number = milliseconds delay before onMouseOut    
         out: OnListViewOut // function = onMouseOut callback (REQUIRED)    
    };

    function MapReady()
    {
        LoadingResult = false;
        $("div.overflow").scroll(function(){
            var elem = $('div.overflow');
            if (elem[0].scrollHeight - elem.scrollTop() / elem.outerHeight() > 0.8) {
              if ((PageNum * LPP) < arrProperties.length && !LoadingResult)
              {
                PageNum++;
                GetMapResult();
              }
            }
        });	
        
        $(".Agora_Map_Tr").hoverIntent( config );
       
    }