﻿    //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"]) : 30.685596;
    var MapLongitude = (!DataFloat.Agora.Util.IsEmptyOrNull(DataFloat.Agora.Util.Request.QueryString["long"])) ? parseFloat(DataFloat.Agora.Util.Request.QueryString["long"]) : -88.146482;
    var dLast14days = DataFloat.Agora.Util.getSpecficDate(-100, 0, 0, 'YMD', "");
    tDefaultLatLong[200] = {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 = 200;
    var arrLoadedPops = new Array();    
    var mapAjax;
    var DrawAreas;
    var oComboManager;
    var arrProperties;
    var isOnDrive=false;
    
    //added by aneesh
    function ProcessNeighborhoodAreas() {
    
    arrAreas = JSON.parse(AreaJSon);  
    for (var i = 0; i < arrAreas.Polygons.length; i++) {
        $("#SaveNeighborhoodTitle").append("<div style='clear:both'><input type='checkbox' id='NeighborhoodAreas_" + i + "' name='NeighborhoodAreas' class='NeighborhoodAreas' onchange='OnChangeNeighborhood(this)' value='" + arrAreas.Polygons[i].Key + "'> " + unescape(arrAreas.Polygons[i].Name) + "<input type='hidden' id='NeighborhoodAreaID_"+i+"'/></div>");
    }
}
function OnChangeNeighborhood(Elem) {
    var tempPoints = [];
    var AreaName = "";
    var PolygonArrayNum = $(Elem).attr("id").split("_")[1];
    
    if ($(Elem).is(":checked")) {
        for (var i = 0; i < arrAreas.Polygons[PolygonArrayNum].Points.length; i++) {
            tempPoints.push(new VELatLong(parseFloat(arrAreas.Polygons[PolygonArrayNum].Points[i].lat), parseFloat(arrAreas.Polygons[PolygonArrayNum].Points[i].lng)));
        }
        oPowerMap_OnDrawFinishNeighborhood(oPowerMap.retrieveDrawAreaFromPoints(tempPoints, unescape(arrAreas.Polygons[PolygonArrayNum].Name)), unescape(arrAreas.Polygons[PolygonArrayNum].Name), "NeighborhoodAreaID_" + PolygonArrayNum);
    } else {
        oPowerMap.DeleteArea($("#NeighborhoodAreaID_" + PolygonArrayNum).val());
    }
    DoSearch();
}

function oPowerMap_OnDrawFinishNeighborhood(oDraw, AreaName, StoredDrawAreaID) {
    oCurrentDraw = oDraw;
    SubmitAreaNeighborhoodName(AreaName, StoredDrawAreaID);
    if (bAdvacendSearchStatus) {
        $('#SearchCriteria').show();
    }
}

function SubmitAreaNeighborhoodName(AreaName, StoredDrawAreaID) {
    var AreaName = (AreaName != undefined) ? AreaName : "New Neighborhood";

    AddNeighborhoodDrawRow(oCurrentDraw, StoredDrawAreaID);
    mapAjax.MapManager.VirtualMap.SetMapView(oCurrentDraw.GetPoints());

    $('#DrawingBoxContainer').hide();
    $('#InfoBoxContainer').show();
}
function AddNeighborhoodDrawRow(oDraw, StoredDrawAreaID) {
    var shapeID = oDraw.GetID();
    var shapeTitle = oDraw.Title;
    $("#" + StoredDrawAreaID).val(shapeID);
}
    //end aneesh

    $(document).ready(function() {
        //ProcessNeighborhoodAreas(); due to the ticket, we removed this features
        $(".wrap").corner("top");
        $(".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[200].Lat, tDefaultLatLong[200].Long), 10)
        mapAjax.MapManager.VirtualMap.AttachEvent("onmouseover", mapAjax.MapManager.OnMouseOverPin);
        mapAjax.MapManager.VirtualMap.AttachEvent("onendzoom", oPowerMap_OnEndZoom);
        mapAjax.MapManager.VirtualMap.AttachEvent("onendpan", CatchEventPOI);
        //New Map
           var RegionAl = $("#rgn").val();
           var Region=null;
           switch (RegionAl)
           {
                    case "bal": Region = "baldwin mls";          break;
                    case "vly": Region = "huntsville";           break;
                    case "bml": Region = "birmingham mls";       break;
                    case "lee": Region = "auburn/opelika mls";   break;
                    case "mnt": Region = "montgomery mls";       break;
                    case "tcn": Region = "tuscaloosa mls";       break;
                    case "pen": Region = "pensacola mls";        break;
                    case "cul": Region = "smithlake/cullman";    break;
                    case "lke": Region = "lake martin";          break;
                    default:    Region = "mobile mls";           break;
           }      
        if (Region != "" && Region !=null) { $("#string_Mlsboard").val(Region); ChangeLatLong(Region); }
        
            $("#frmAdvCriteria .flxCriteria").each(function() {
                var SectionName = $(this).attr("id").substring(3);
                if ($(this).find("input").size() == 0)
                    $("#a" + $(this).attr("id").substring(3)).hide();

                $(this).find("input").change(function() {
                    UpdateAdvancedCriteria(SectionName);
                })
                UpdateAdvancedCriteria(SectionName);
            })
        //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');
        $('#InfoBoxContainer').hide();
        $('#InfoBoxTooMany').hide();
        $('#DrawingBoxContainer').hide();
        accordionActions();
        //oMapSearch_OnLoad(OfficeJSon);
        //ChangeLatLong();
        DoSearch();
    })
    
    function HideAll() 
    {
        $("span.ShowTextField").each(
            function(i) {
                $("div#" + $(this).attr("title")).hide();
            }
        )
    }
    function ShowAdvancedSearch(){
    $("#divCriteriaDetail").show();
    $("#frmAdvCriteria .flxCriteria").each(function(e) { $(this).hide(); });
    $("#divExteriorFeature").show();
    $("#divAdvancedSearch").show();
    }
    
    function UpdateMap(){
        $("#divAdvancedSearch").hide();
        DoSearch();
    }
    
    function CloseCriteria(){
        $("#divAdvancedSearch").hide();
        return false;
    }
    
    function ShowCriteria(divFeature){
        $(".flxCriteria").hide();
        $("#" + divFeature).show();
    }
    
    function UpdateAdvancedCriteria(SectionID) {
        var CriteriaString = "";       
        $("#div" + SectionID + " input:checked").each(function() {
            if (CriteriaString != "") CriteriaString += ",";
            CriteriaString += $(this).val();
        })

        $("#div" + SectionID + " input[type=text]").each(function() {
            if (CriteriaString != "") CriteriaString += ",";
            CriteriaString += $(this).val();
        })

        if (CriteriaString == "") {
            $("#txt" + SectionID).html("No Criteria");
        }else $("#txt" + SectionID).html(CriteriaString);
    }
    
    
    function SetMapLocation(BoardId){
        iCurrentBoard = 200;
        mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(tDefaultLatLong[200].Lat, tDefaultLatLong[200].Long), 10)
    }
    
    function ViewPropertyDetails(MlsNumber) {
        window.open('/PropertyDetail.aspx?RecordType=200&searchType=Map&0110_exc=' + MlsNumber);
    }

    function AdvancedSearchTab_OnClick(){
	    if (bAdvacendSearchStatus)
	        $('#SearchCriteria').hide();
	    else
	        $('#SearchCriteria').show();
	    bAdvacendSearchStatus = !bAdvacendSearchStatus;
	}
	
	function DoSearch(pinObject){
	    if(isOnDrive){ return; }
	    $("#divDirection").hide();
	    $("#results_list").show();
	    $(".map_options").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 arrCheckArea = $('.cbxmyareas:checked, .NeighborhoodAreas:checked');
		    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 + "&" + $('#frmMapSearch').serialize() + '&' + $('#frmAdvCriteria').serialize();
		    
		    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();
	        
//	        if(ispostback=='1')
//	        {
//	              arrProperties = JSON.parse(result);    	        
//	            mapAjax.MapManager.ClearAll();
//	  	        var arrPin = new Array();
//	  	        var arrMls = new Array();
//                //PinClass = "DefaultPinOffice";	  	    
//	  	        for(var k = 0; k < arrProperties.length ; k++){
//                    iMLSNum = arrProperties[k]["mls"];
//                    //iName = arrProperties[i]["name"];
//                    iName =  "";
//                    iLatitude = arrProperties[k]["lat"];
//                    iLongitude = arrProperties[k]["long"];
//                    iKmls = arrProperties[k]["kmls"];
//                    iListDate = arrProperties[k]["listdate"];
//                    arrMls.push(arrProperties[k]["mls"]);
//                    if (iLatitude && iLongitude)
//                    {
//				        var Html = "<b><a href='OfficeDetail.aspx?RecordType=2&n_k="+ arrProperties[k]["OfficeKey"]+ "'>"+arrProperties[k]["name"]+"</a></b><br/>"+arrProperties[k]["OfficeAddress"]+"<br/>"+arrProperties[k]["OfficeCity"]+"&#160;"+arrProperties[k]["OfficeState"]+"&#160;"+arrProperties[k]["OfficeZip"]+"<br/>"+arrProperties[k]["OfficePhone"];				        
//					    arrPin[arrPin.length] = new mapAjax.MapManager.PinObject(k, iName, iLatitude, iLongitude, iMLSNum, PinClass, Html , iKmls);
//			        }
//                }
//                mapAjax.MapManager.NewItem(arrPin);
//                ispostback='0';
//	        }
//	        else
//	        {
	            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();
                $("#InfoBoxContainer").show();
                $("#InfoBox").show();
                
                
	  	        var ActiveListing = 0;
	  	        var NewListing = 0;
	  	        var OpenListing = 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"];
                    iOpenHouse=arrProperties[i]["openhouse"];
                    arrMls.push(arrProperties[i]["mls"]);
                    if (iLatitude && iLongitude)
                    {
                       if(parseInt(iOpenHouse)==1)
                       {
                            OpenListing++;
                            PinClass =  "OpenHousePin"; 
                       }
                       else
                       {
                            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());
                $("#OpenCount").html(OpenListing.toString());
                mapAjax.MapManager.NewItem(arrPin);
                StartListView();
           //}
	}
	
	function ChangeMLSBoard(Val) 
	{
            //$("#MapHeader").append("<img src='/img/loadingAnimation.gif'/>");
            /*queryString = ReplaceQueryString(location.href, "Region", Val.toLowerCase());
            location.replace(queryString.replace(".aspx&",".aspx?"));*/
            
            window.location.href = "/PropertySearchMap.aspx?" + $('#frmMapSearch').serialize() + '&' + $('#frmAdvCriteria').serialize() + "&Region=" + Val.toLowerCase();
    }
	
	function ChangeLatLong(Val) 
	{   
        strOptions = $("#prop_type").html();
        if (Val.toLowerCase().indexOf("montgomery") != -1)
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(32.378363, -86.292973), 13);
        }
        else if (Val.toLowerCase().indexOf("birmingham") != -1) 
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(33.513347, -86.803665), 11);
        }
        else if (Val.toLowerCase().indexOf("huntsville") != -1) 
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(34.730369, -86.586104), 11);
        }
         else if (Val.toLowerCase().indexOf("baldwin mls") != -1) 
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(30.358900, -87.663700), 11);
        }
        
        else if (Val.toLowerCase().indexOf("martin") != -1) 
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(32.723754, -85.934372), 12);
        }
        else if (Val.toLowerCase().indexOf("pensacola") != -1) 
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(30.425437, -87.211704), 13);
        }
        else if (Val.toLowerCase().indexOf("tuscaloosa") != -1) 
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(33.207239, -87.564983), 13);
        }
        else if (Val.toLowerCase().indexOf("cullman") != -1) 
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(34.17311, -86.845636), 14);
        }    
        else if (Val.toLowerCase().indexOf("auburn") != -1) // Lee County
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(32.6142652, -85.4476193), 11); 
        }
        else if (Val.toLowerCase().indexOf("mobile") != -1 || Val.toLowerCase().indexOf("baldwin") != -1) //) //// Mobile and Baldwin
        {
            mapAjax.MapManager.VirtualMap.SetCenterAndZoom(new VELatLong(30.685596, -88.046482), 11);       
        }
        //DoSearch();
        //UpdateAdvancedCriteria();  
    }
		
	function GetNumber(mls)
	{
	    var ListingClass = $(".Agora_Pin_"+mls).attr("class");
	    if(ListingClass != undefined)
        {
	        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', "");
	    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'); 
        $('.DefaultPin').show();	
        $('.compareLisitngCheckBox').removeAttr('checked');
	}
	
	function StartListView()
	{
	    PageNum = 1;
        $("#ListingBody").html("");
        GetMapResult();
	}
	
	function GetMapResult()
	{
	    if (arrProperties.length>=1)
	    {
	        $("#processing").html("...Loading&#160;<img src='/img/loadingAnimationbar.gif'/>");
	        LoadingResult = true;
	        var ResultMLS = "0250_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=200&"+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)) {
                ViewPropertyDetails(MlsNumber);
            }
        }
    }
    
    /* 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', '/img/ran_bt_draw_off.gif');
            else
                $("#imgMap").attr('src', '/img/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 ShowSpecificListings(Val)
        {
            if (Val=="new")
            {
                $(".DefaultPin").hide();
                $(".OpenHousePin").hide();
                $(".NewPin").show();
            }else if (Val=="act")
            {
                $(".DefaultPin").show();
                $(".OpenHousePin").hide();
                $(".NewPin").hide();            
            }
            else if (Val=="open")
            {
                $(".OpenHousePin").show();
                $(".DefaultPin").hide();
                $(".NewPin").hide();            
            }
            else if (Val=="")
            {
                $(".DefaultPin").show();
                $(".NewPin").show(); 
                $(".OpenHousePin").show();                       
            }
        }  
	    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><p><input type="checkbox" style="width:0px !important;" 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+'"></p></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(k == undefined) return;           
            pin.SetDescription("<div id='PropertyInfo_"+k+"' style='width:450px' ><img src='/img/loadingAnimation.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=200&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;
	        isOnDrive=false;
	    }	    
	    
	    var directionLoaded = true;
	    function ShowDirections(){
    	    
	        var AddressStart = $('#StreetAddress').val();
    	    
	        if (AddressStart != ''){
                $("#divDirection").show();
	            $("#results_list").hide();
	            $(".map_options").hide();	        
	            $('#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); 
	            isOnDrive=true;   	    
	        } else
	        {
	            alert ("Please input starting location.");
	        }
	    }
	    
	    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(){
	        alert('asd');
	        if ($("#StreetAddress").val()!='')
	        {
	            if(oComboManager.DestinationCombo.length > 0){
	                window.open("/Pop/MapDirection.aspx");
	                //ShowDirections();
	                //tb_show('Driving and Directions', '/POP/DrivingDirection.htm?height=200&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){
	        $('#helloAl').removeAttr('style');
	        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(arrProperties[iIndex].kmls, '(' + (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(!isOnDrive){DoSearch();}
	    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();
		window.setTimeout('Pop_AdvancedSearch()',500);
		if ($(this).html() == 'Advanced Criteria')
		{
            window.setTimeout('ShowAdvancedSearch()', 2000);
        }
        else 
        {
            CloseCriteria();
        }
		//alert($(this).parents('.accordion').children('.advanced').children('.content').size());
	});
}

function Pop_AdvancedSearch()
{
    if ($('#AdvancedFieldsetContent').css("display") == "block") ShowAdvancedSearch();
}



//***************************************************************************************************
// Compare Properties
//***************************************************************************************************
function addPropertyCompare(Elem)
{
        //var k =  Elem.value;
    var ctrl_comp_mls = $('.compareLisitngCheckBox');
    var str_comp_mls = '';

    for (i = 0; i < ctrl_comp_mls.length; i++) 
    {
        if (!ctrl_comp_mls[i].checked) continue;
        if (str_comp_mls != '') str_comp_mls += ',';
        str_comp_mls += ctrl_comp_mls[i].value;
    }

    if (str_comp_mls.split(',').length > 4)
    {
        alert('You can compare maximum 4 properties');
        $("#compare_" + Elem).attr("checked", "");
        return;
    }

}

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(isAgent)
    {
	    var ctrl_comp_mls = $('.compareLisitngCheckBox');
        var str_comp_mls = '';
            
        for(i=0; i<ctrl_comp_mls.length; i++)
        {
            if(!ctrl_comp_mls[i].checked) continue;        
            if(str_comp_mls != '') str_comp_mls += ',';        
            str_comp_mls += ctrl_comp_mls[i].value;
        }
        //alert(str_comp_mls);
        if(str_comp_mls.split(',').length < 2)
        {
            alert('Please select at least 2 properties for comparison');
            return;
        }
       
        if(isAgent=="True")
        {
                if(str_comp_mls.split(',').length > 3 )
                {
                    alert('You can compare maximum 3 properties');        
                    return;
                }
        }
        else
        {
                if(str_comp_mls.split(',').length > 4 )
                {
                    alert('You can compare maximum 4 properties');        
                    return;
                }
        }  
        window.open('/PropertyCompare.aspx?RecordType=200&0110_exc='+str_comp_mls);       
    }

    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 );
       
    }
    function ShowBuyerTours() {

    var AddressStart = $('#StreetAddress').val();
    var mlsBoard = $('#string_Mlsboard').val();
    if (AddressStart != '') {
        $("#divDirection").show();
        $("#results_list").hide();
        $(".map_options").hide();
        $('#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]);
        var mlslist = "";
        $("#IntineraryOrder option").each(function() {
            if (mlslist != "") mlslist += ",";
            mlslist += $(this).attr("value");
        })
       // alert(mlslist);
        directionLoaded = false;
        mapAjax.MapManager.VirtualMap.GetDirections(arrPoints, options);
        setTimeout("Directions_StillWorking()", 5000);
        setTimeout("Directions_CheckTimeout()", 10000);
        isOnDrive = true;

        window.open("/BuyerTour.aspx?mls=" + mlslist + "&AddressStart=" + AddressStart + "&mlsBoard=" + mlsBoard);
    } else {
        alert("Please input starting location.");
    }
}

   /* function ChangeLatLong() {
        CloseCriteria();
        if ($("#string_Mlsboard").val() == "Mobile MLS") {

            $("#liWaterfront").hide();
            $("#liWaterAccess").show();

            $("#string_WaterAccess").val("");
            $("#string_Waterfront").val("");
        } else {
            $("#liWaterfront").show();
            $("#liWaterAccess").hide();

            $("#string_WaterAccess").val("");
            $("#string_Waterfront").val("");
        }
        UpdateAdvancedCriteria();      
        
    }*/
//    $('.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();
//		window.setTimeout('Pop_AdvancedSearch()',1000);
//		
//		//alert($(this).parents('.accordion').children('.advanced').children('.content').size());
//	});
    function InitAdvancedSearchUpdater()
    {
        $("#divCriteriaDetail input:checkbox").click(
            function (e) {                
                ctrlId = $(this).attr("id");
                selectedValues = '';                
                $("input:checkbox[id=" + ctrlId + "]").each(                    
                    function (ex) {
                        i++;
                        if($(this).attr("checked") == true)
                        {
                            selectedValues += $(this).val() + ', ';
                            
                        }
                    }
                );
                
                UpdateAdvancedCriteria(ctrlId, selectedValues);
            }
        );
        
        $("#divCriteriaDetail input:text").change(
            function (e) {
                ctrlId = $(this).attr("id");                
                UpdateAdvancedCriteria(ctrlId, $(this).val());
            }
        );
        
        $("#divCriteriaDetail select").change(
            function (e) {
                ctrlId = $(this).attr("id");                
                UpdateAdvancedCriteria(ctrlId, $(this).val());
            }
        );
    }
