﻿
var rgx_alt = /(.+?)(\/[\(\)\-a-z0-9\.]+?\-(?:loc|map))(.*)/i;
var rgx_location = /^\/([^\/]+?)\/([^\/]+?)\/(.*)$/i;
var rgx_radius = /(.+?)(\/[0-9\-\.]+\-radius)(.*)/i;
var MarkerCollection = new Array();

function SwitchRadiusOption(opt)
{
	var NewSEOQuery = CacheObject.SEOQuery;
		NewSEOQuery = NormalizeSEOQuery(NewSEOQuery.replace(rgx_radius, "$1$3"));
		NewSEOQuery = NewSEOQuery + "/" + opt + "/";
		isFirstLoad = true;
		ReloadListByMap(NewSEOQuery);
}

function SwitchSearchType(stype)
{
    var NewSEOQuery = CacheObject.SEOQuery;
	if (NewSEOQuery.indexOf("?") > -1)
	{
		NewSEOQuery = NewSEOQuery.split("?")[0];
	}
    switch(stype)
    {
        case "map":
                NewSEOQuery = NormalizeSEOQuery(NewSEOQuery.replace(rgx_alt, "$1$3"));
                NewSEOQuery = NormalizeSEOQuery(NewSEOQuery.replace(rgx_radius, "$1$3"));
            var Bounds = Map.getBounds();
            var MapQuery = String.format("/{0}-{1}-{2}-{3}-map", 
                    (Math.round(Bounds.getNorthEast().lat()*1000000)/1000000), 
                    (Math.round(Bounds.getNorthEast().lng()*1000000)/1000000),
                    (Math.round(Bounds.getSouthWest().lat()*1000000)/1000000), 
                    (Math.round(Bounds.getSouthWest().lng()*1000000)/1000000)); 
            NewSEOQuery = NewSEOQuery + MapQuery;
            //alert(stype + "::" + NormalizeSEOQuery(NewSEOQuery));
            //return;
            break;
        case "radius":
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			//	New logic for Radius search..
			//	1. Take the center point of the current map view
			//	2. Find nearest City
			//	3. Go to that location, with radius on
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            NewSEOQuery = NormalizeSEOQuery(NewSEOQuery.replace(rgx_alt, "$1$3"));
            NewSEOQuery = NormalizeSEOQuery(NewSEOQuery.replace(rgx_radius, "$1$3"));
            NewSEOQuery = NewSEOQuery + "/30.00-radius";
            var url = "/reno/Locations/GetRadiusSearch.aspx?SEOQuery={0}&Center={1}";
				url = String.Format(url, escape(NewSEOQuery), Map.getCenter().toString().replace(/[^0-9\.\-,]+/g,''));
				$.get(url, function(data)
				{
					if (data.indexOf("Error:") > -1)
					{
						alert(data);
					}
					else
					{
						//window.location.href = trim(data);
						window.location.href = trim(data).split('|')[0];
					}
				});
				return;
            break;
        case "location":
            NewSEOQuery = NewSEOQuery.replace(rgx_alt, "$1$3") + "/";
            NewSEOQuery = NewSEOQuery.replace(rgx_radius, "$1$3") + "/";
            NewSEOQuery = NewSEOQuery.replace(rgx_location, String.Format("/$1/{0}/$3", $("#LocSeo").val()));
            //alert(stype + "::" + NormalizeSEOQuery(NewSEOQuery));
            //return;
            break;
        case "custom":
            //TODO:
            break;
    }
    
    window.location.href = NormalizeSEOQuery(NewSEOQuery);
}

var CONST_RGX_MAP = /(.+?)\/(\-?[0-9\.]+)\-(\-?[0-9\.]+)\-(\-?[0-9\.]+)\-(\-?[0-9\.]+)\-map(\/?.*)/i;
var CONST_RGX_RADIUS = /(.+?)\/([0-9\-\.]+)\-radius(\/?.*)/i;
var CONST_RGX_LOCATION = /\/?([^\/]+)\/([^\/]+)(\/?.*)/i;
var CONST_RGX_RADIUS_CUSTOM = /(.+?)\/(\-?[0-9\.]+)\-(\-?[0-9\.]+)\-([0-9\.]+)\-radius(\/?.*)/i;

function GetSearchType(url)
{
    var ReturnType = "location";
    
    if (url != undefined)
    {
		if (url.indexOf('#')>-1)
		{
			url = url.split('#')[1];
		}
	    
		if (CONST_RGX_MAP.test(url))
		{
			ReturnType = "map";
		}
		else if (CONST_RGX_RADIUS.test(url))
		{
			ReturnType = "radius";
		}
    }
    return ReturnType;
}

function isCustomRadius(url)
{
	if (CONST_RGX_RADIUS_CUSTOM.test(url))
    {
        return true;
    }
    return false;
}

function GetCustomRadiusCenter(url)
{
	var newLatLng = new google.maps.LatLng(0,0);
	if (isCustomRadius(url))
	{
		var sLat = url.replace(CONST_RGX_RADIUS_CUSTOM, "$2");
		var sLng = url.replace(CONST_RGX_RADIUS_CUSTOM, "$3");
			newLatLng = new google.maps.LatLng(parseFloat(sLat), parseFloat(sLng));
	}
	return newLatLng;
}

function GetViewType(url)
{
	var ReturnType = "list";
	
	if (url != undefined)
    {
		url = url.toLowerCase();
	    
		if (url.indexOf('#')>-1)
		{
			url = url.split('#')[1];
		}
	    
		if (url.indexOf("/map-view") > -1)
		{
			ReturnType = "map";
		}
		else if (url.indexOf("/gallery-view") > -1)
		{
			ReturnType = "gallery";
		}
		else if (url.toLowerCase().indexOf('/advanced-view') > -1)
		{
			ReturnType = "advanced";
		}
    }
    return ReturnType;
}

function GetSearchRadius(url)
{
    var ReturnRadius = 30.0;
    
    if (GetSearchType(url) == "radius")
    {
		if (isCustomRadius(url))
		{
			ReturnRadius = parseFloat(url.replace(CONST_RGX_RADIUS_CUSTOM, "$4"));
		}
		else
		{
			ReturnRadius = parseFloat(url.replace(CONST_RGX_RADIUS, "$2"));
		}
        
    }
    
    return ReturnRadius;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Icon Objects cache
//  to speed up rendering, we reference these icons
//	instead of creating new ones as needed
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

var RegionIconObjects = new Array();
var RegionIconObjectsSelected = new Array();

$(function()
{
    for (var Level=0; Level < 5; Level++)
    {
		
		/* v.2
        var IconConstructor = new GIcon(G_DEFAULT_ICON);
            IconConstructor.iconSize = new GSize(15.0, 18.0);
            IconConstructor.iconAnchor = new GPoint(5.0, 8.0);
            IconConstructor.shadow = null;
            //IconConstructor.infoWindowAnchor = new GPoint(8.0, 1.0);
            
            IconConstructor.sprite = {};
            IconConstructor.sprite.image = Static + "/reno/custom/wrappers/gabriels/images/icons/icons_google_map.png";
            //IconConstructor.sprite.image = Static + "/reno/custom/wrappers/gabriels/images/icons/icons_google_map.png.ashx";
            IconConstructor.sprite.left = 0;
            switch(Level)
            {
                case 3:
                    IconConstructor.sprite.top = 20;
                    break;
                case 4:
                    IconConstructor.sprite.top = 0;
                    break;
                default:
                    IconConstructor.sprite.top = 40;
                    break;
            }
         */
         /* v.3 */
         switch(Level)
        {
            case 3:
				RegionIconObjects[Level] = new GIcon(Static + "/reno/custom/wrappers/gabriels/images/icons/icons_google_map.png"
					,new GSize(15, 18)	// This marker is 15 pixels wide by 18 pixels tall.
					,new GPoint(0, 20)	// The origin for this image Changes for each level
					,new GPoint(8, 10)	// The anchor for this image
				);
				RegionIconObjectsSelected[Level] = new GIcon(Static + "/reno/custom/wrappers/gabriels/images/icons/icons_google_map.png"
					,new GSize(15, 18)	// This marker is 15 pixels wide by 18 pixels tall.
					,new GPoint(20, 20)	// The origin for this image Changes for each level
					,new GPoint(8, 10)	// The anchor for this image
				);
                break;
            case 4:
				RegionIconObjects[Level] = new GIcon(Static + "/reno/custom/wrappers/gabriels/images/icons/icons_google_map.png"
					,new GSize(15, 18)	// This marker is 15 pixels wide by 18 pixels tall.
					,new GPoint(0, 0)	// The origin for this image Changes for each level
					,new GPoint(8, 10)	// The anchor for this image
				);
				RegionIconObjectsSelected[Level] = new GIcon(Static + "/reno/custom/wrappers/gabriels/images/icons/icons_google_map.png"
					,new GSize(15, 18)	// This marker is 15 pixels wide by 18 pixels tall.
					,new GPoint(20, 0)	// The origin for this image Changes for each level
					,new GPoint(8, 10)	// The anchor for this image
				);
                break;
            default:
				RegionIconObjects[Level] = new GIcon(Static + "/reno/custom/wrappers/gabriels/images/icons/icons_google_map.png"
					,new GSize(15, 18)	// This marker is 15 pixels wide by 18 pixels tall.
					,new GPoint(0, 40)	// The origin for this image Changes for each level
					,new GPoint(8, 10)	// The anchor for this image
				);
				RegionIconObjectsSelected[Level] = new GIcon(Static + "/reno/custom/wrappers/gabriels/images/icons/icons_google_map.png"
					,new GSize(15, 18)	// This marker is 15 pixels wide by 18 pixels tall.
					,new GPoint(20, 40)	// The origin for this image Changes for each level
					,new GPoint(8, 10)	// The anchor for this image
				);
                break;
        }

		// v.2
		//var shadow = null;
		//new google.maps.MarkerImage('images/beachflag_shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      //new google.maps.Size(37, 32),
      //new google.maps.Point(0,0),
      //new google.maps.Point(0, 32));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML <area> element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
//	  var shape = {
//		  coord: [1, 1, 1, 20, 18, 20, 18 , 1],
//		  type: 'poly'
//	  };

            //RegionIconObjects.push(IconConstructor);
    }

});

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	For version 3, you can pass the z-index order into the Marker constructor
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  CustomZIndexOrder
//  This is the delegate to pass to the zIndexProcess property of the 
//  Marker constructor. Don't know what the b value is or what it's used for.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//function CustomZIndexOrder(Marker, b) 
//{
//    return GOverlay.getZIndex(Marker.getPoint().lat()) + Marker.CustomZIndex * 1000000;
//}

var Icon = new Array();

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  GetRegionMarker()
//  Gets Region Icon Marker
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function GetRegionMarker(RegionName, ListingsCount, RegionId, Latitude, Longitude, Level)
{
    
    var LevelNum;
    switch(Level)
    {
        case "Country":     LevelNum=0;break;
        case "State":       LevelNum=1;break;
        case "County":      LevelNum=2;break;
        case "City":        LevelNum=3;break;
        case "Neighborhood":LevelNum=4;break;
    }
    //alert(Level + ":" + LevelNum);
        Icon[RegionId] = RegionIconObjects[LevelNum];

    if (isSelected(RegionId))
    {
        Icon[RegionId] = RegionIconObjectsSelected[LevelNum];
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //  Creation of the actual marker
    //  zIndexProcess controls the ZIndex of the marker itself
    //  The property requires a Function reference to be passed to it
    //  The Function evaluates when map.addOverlay is called.
    //  Note: You cannot pass a Delegate to this property, only a 
    //  Delegate/Function by name
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //  The higher the value passed to the Marker.CustomZIndex property,
    //  the highr to the top the marker will lay
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    var Marker = new GMarker({
					position: new GLatLng(Latitude, Longitude)
                    ,icon:Icon[RegionId] // by reference
                    //,id:RegionId			undocumented attributes Not suppoted in v.3
                    ,title:RegionName
                  });
    // v.2 var Marker = new GMarker(new GLatLng(Latitude, Longitude), {zIndexProcess:CustomZIndexOrder});
    /* v.2    Marker.CustomZIndex = LevelNum * -1; // states overlap city, cities overlap neighborhood */

    // v.2 var Marker = new GMarker(new GLatLng(Latitude, Longitude));

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //    Set the event listeners
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if (Level=="Neighborhood")
    {
        GEvent.addListener(Marker, "mouseover", function()
        {
             GP.PolyGet(slMap, RegionId, "006633", "006633");
             // v.2 SetToolTip(Marker);
        });
        GEvent.addListener(Marker, "mouseout", function()
        {
            if (CacheObject.SelectedLocations.length)
            {
                if (!($.inArray(RegionId, CacheObject.SelectedLocations) > -1))
                {
                    GP.PolyRem(slMap, RegionId);
                }
            }
        });
        GEvent.addListener(Marker, "click", function(recurse)
        {
            ChooserSelect('new-' + RegionId, function()
            {
                if (!isSelected(RegionId))
                {
                    GP.PolyRem(slMap, RegionId);
                }
                else
                {
                    GP.PolyGet(slMap, RegionId, "006633", "006633");
                }
                    // v.2 var qt = $('#mtgt_' + RegionId);
                    // v.2 if (qt.data("qtip")) qt.qtip("hide");
                    /* v.2 
                    slMap.removeOverlay(Marker);
                    Marker = GetRegionMarker(RegionName, ListingsCount, RegionId, Latitude, Longitude, Level);
                    slMap.addOverlay(Marker);
                    */
                    /* v.3 */
                    Marker.setMap(null);	// remove
                    Marker = GetRegionMarker(RegionName, ListingsCount, RegionId, Latitude, Longitude, Level);
                    Marker.setMap(slMap);	// add
            });
            
        });
    }
    else
    {
        GEvent.addListener(Marker, "mouseover", function()
        {
             // v.2 SetToolTip(Marker);
        });
        
        GEvent.addListener(Marker, "click", function()
        {
            ChooserSelect('new-' + RegionId, function()
            {
                    // v.2 var qt = $('#mtgt_' + RegionId);
                    // v.2 if (qt.data("qtip")) qt.qtip("hide");
                    /* v.2 
                    slMap.removeOverlay(Marker);
                    Marker = GetRegionMarker(RegionName, ListingsCount, RegionId, Latitude, Longitude, Level);
                    slMap.addOverlay(Marker);
                    */
                    /* v.3 */
                    Marker.setMap(null);	// remove
                    Marker = GetRegionMarker(RegionName, ListingsCount, RegionId, Latitude, Longitude, Level);
                    Marker.setMap(slMap);	// add
            });
        });
    }
    
    MarkerCollection[RegionId] = Marker;
    return Marker;
}

function isSelected(RegionId)
{
    var returnVal = false;
    if (CacheObject.SelectedLocations.length > 0)
    {
        returnVal = ( $.inArray(RegionId, CacheObject.SelectedLocations) > -1 );
    }
    return returnVal;
}




//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  GetRegionLocationMarker()
//  Gets Region Icon Marker for results and map view 
//	location searches
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function GetRegionLocationMarker(RegionName, ListingsCount, RegionId, Latitude, Longitude, Level, callback)
{
    
    var LevelNum;
    var isSel = isSelected(RegionId);
    
    switch(Level)
    {
        case "Country":     LevelNum=0;break;
        case "State":       LevelNum=1;break;
        case "County":      LevelNum=2;break;
        case "City":        LevelNum=3;break;
        case "Neighborhood":LevelNum=4;break;
    }

    if (isSel)
    {
        Icon[RegionId] = RegionIconObjectsSelected[LevelNum];
        isSel = true;
    }
    else
    {
		Icon[RegionId] = RegionIconObjects[LevelNum];
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //  Creation of the actual marker
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    var Marker = new GMarker({
					position: new GLatLng(Latitude, Longitude)
                    ,icon:Icon[RegionId] // by reference
                    ,id:RegionId	
                    ,level:LevelNum
                    ,title:RegionName
                    ,zIndex:1
                  });
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //    Set the event listeners
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    GEvent.addListener(Marker, "click", function()
    {
		var Action = (isSel) ? "rem" : "add";
		Marker.setMap(null);
		SelectedLocationsAct(RegionId, Action, function()
		{
			Marker = GetRegionLocationMarker(RegionName, ListingsCount, RegionId, Latitude, Longitude, Level, callback);
			Marker.setMap(Map);
			Exec(callback);
		})
    });
    
    MarkerCollection[RegionId] = Marker;
    return Marker;
}

var OverrideDontReloadMap = false;


function SelectedLocationsAct(RegionId, action, callback)
{
	CacheObject.doReloadMap = false;
	
	if (action == "rem")
	{
		for(var x=0;x<CacheObject.SelectedLocations.length;x++)
		{
			if (CacheObject.SelectedLocations[x] == RegionId)
			{
				CacheObject.SelectedLocations.splice(x,1);
				break;
			}
		}
	}
	else
	{
		CacheObject.SelectedLocations.push(RegionId);
	}
	
	var URLQuery = NormalizeSEOQuery(CacheObject.SEOQuery);
		URLQuery = URLQuery.replace(/[0-9]+\-pg/gi,''); // remove pagination
		URLQuery += "/manage-locations?" + action + "=" + RegionId;
		URLQuery = URLQuery.replace("//", "/");
		//alert(URLQuery);
		$.get(URLQuery, {}, function(data)
		{
			if (data=='err-none')
			{
				window.alert('At least one location required');
			}
			else
			{
				//alert(data);
				//note: data == new url
				var XMLDoc = ReloadList(data, false);
					ReloadLocationsWithXML(XMLDoc);
				$LocSuggest.HookupEvents();
			}
			
			if (callback != undefined && callback != null && $.isFunction(callback))
			{
				callback.apply();
			}
		});
}


var slMap = null; //Select Locations Map
var Mrkrs = new Array(); // markers for each map load
var MrkrMgr; // marker manager
var bounds = new GLatLngBounds(); //bounds for markers
var $dialog; // dialog housing select locations
// called after dialog opens
var $_dialogPostLoader = function(responseText, textStatus, XMLHttpRequest) 
    {
        window.setTimeout(function()
        {
            Mrkrs = new Array();
            bounds = new GLatLngBounds();
            
            //alert($('#dialog-post-load').html());
            eval($('#dialog-post-load').html()); // div contains javascript

			//	with eval, Mrkrs array now contains markers for map 
			//	with eval, bounds now defines the boundary of map
			
			var slMapOptions = {
				zoom: 8
				,center: new GLatLng(0, 0)
				,mapTypeId: google.maps.MapTypeId.ROADMAP
				,navigationControl: true
				,navigationControlOptions: 
				{
					style: google.maps.NavigationControlStyle.DEFAULT
					//ANDROID, DEFAULT, SMALL, ZOOM_PAN (biggest)
				}
				,mapTypeControl: false
				//,mapTypeControlOptions: 
				//{
				//	style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
				//	//DEFAULT, DROPDOWN_MENU, HORIZONTAL_BAR
				//}
				,scaleControl: false
			};
			
                if (slMap==null) 
                {
                    slMap = new GMap3(document.getElementById('select-locations-map'), slMapOptions);
                }
                
                //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                //	v.2
                //  changes the size of the copyright text 
                //  to make it smaller to fit
                //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                /* 
                window.setTimeout(function()
                {
                    var note = slMap.getContainer().childNodes; 
                    for(var i = 0; i < note.length; i++) 
                    { 
                        if(note[i].innerHTML.indexOf('©') !== -1)
                        { 
                            note[i].style.fontSize = "9px"; 
                            break; 
                        } 
                    } 
                }, 250);
                */
                
                /* v.2 slMap.setCenter(new GLatLng(0,0),0);

                /* v.2 slMap.addControl(new GSmallZoomControl3D()); */

//                GEvent.addListener(slMap, "zoomend", function()
//                {
//	                setTimeout(function(){SetTooltips();}, 500);
//                });
//                GEvent.addListener(slMap, "dragend", function()
//                {
//	                setTimeout(function(){SetTooltips();}, 500);
//                });
//                GEvent.addListener(slMap, "moveend", function()
//                {
//	                setTimeout(function(){SetTooltips();}, 500);
//                });

            /* v.2
            slMap.setCenter(bounds.getCenter());
            slMap.setZoom(slMap.getBoundsZoomLevel(bounds));
			*/
			/* v.3 */ slMap.fitBounds(bounds);
            // v.2 MrkrMgr = new MarkerManager(slMap);
            // v.2 MrkrMgr.addMarkers(Mrkrs, 0);
            // v.2 MrkrMgr.refresh();

			for(var x=0;x<Mrkrs.length;x++)
			{
				Mrkrs[x].setMap(slMap);
			}
			
            setTimeout(function()
            {
                // v.2 slMap.checkResize();
                $('input[name=new-location]').each(function(i)
                {
                    if (CacheObject.SelectedLocations)
                    {
                        if ($.inArray($(this).val(), CacheObject.SelectedLocations) > -1)
                        {
                            $(this).attr('checked', true);
                        }
                    }
                });
                for(var i=0;i<CacheObject.SelectedLocations.length;i++)
                {
                    if (CacheObject.SelectedLocations[i].length == 18)
                    {
                        GP.PolyGet(slMap, CacheObject.SelectedLocations[i], "006633", "006633");
                    }
                }
                OverlayCache.RenderOverlayType(slMap, "Neighborhood");
                //SetTooltips();
            }, 100);
            
        },100);

    };
    


function DebugSelect()
{
    //$('#newlocations').val(CacheObject.SelectedLocations.join(','));
}


function SelectLocations(sltype, primaryLocation) // initial opener
{

    //TODO: Joey Temp
    swap_flash('.has_flash');

    CacheObject.SelectedLocations = new Array();
    $('input[name=selected-location]').each(function(i)
    {
        CacheObject.SelectedLocations.push($(this).attr('id'));
    });
    DebugSelect();

    var url = CacheObject.SEOQueryRootPage + "/select-locations?sort=name&type=" + sltype + "&prid=" + primaryLocation;
    
//    if (window.confirm("Show XMLData?"))
//    {
//		window.location.href = url;
//		return;
//    }
	   //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	    //  IMPORTANT: the container '#dialog-wrap' must be in the DOM and not ever
	    //  unloaded from the DOM (usually with AJAX) or it will
	    //  break Google Maps
	    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	    $dialog = $('#dialog-wrap')
		.load(url, {}, $_dialogPostLoader)
		.dialog({
		    modal: false
            ,overlay: { 
                "opacity": "0.70", 
                "-moz-opacity": "0.70",
                "background-color": "black" 
            }
			,autoOpen: true
			,title: null
			,width: 853
			,height: 515
			,closeOnEscape: true
			,draggable: false
			,resizable: false
			,beforeclose: function(event, ui)
			{
			    //$dialog.load(Static + '/reno/utility/blank.html.ashx');
			    $dialog.load(Static + '/reno/utility/blank.html');
			}
		});
	$(".ui-dialog-titlebar").hide();

}

function ChooserSelectCheck(RegionId)
{
    // v.2 GEvent.trigger(MarkerCollection[RegionId], "click", MarkerCollection[RegionId].getPoint()); 
    GEvent.trigger(MarkerCollection[RegionId], "click");
}

function ChooserSelect(id, callback)
{
    id = "#"+id;
    var index = $.inArray($(id).val(), CacheObject.SelectedLocations);
    if (index > -1)
    {
        $(id).attr('checked', false);
        CacheObject.SelectedLocations.splice(index,1);
    }
    else
    {
        $(id).attr('checked', true);
        CacheObject.SelectedLocations.push($(id).val());
    }
    DebugSelect();
    id = id.replace("#","").replace("new-","");
    if (callback != undefined)
    {
        callback();
        //alert("callback!!");
    }
}

function SelectLocationsOpen(url) // called after dialog already opened
{
//    if (window.confirm("Show XMLData?"))
//    {
//		window.location.href = url;
//		return;
//    }
    slMap = null;
    OverlayCache = new OverlayCacheBase(); // refresh, rebuilt on load
    $dialog.load(url, {}, $_dialogPostLoader);
}

function CloseLocationsSearch()
{
    //TODO: Joey Temp
    swap_flash('.has_flash');

    slMap = null;
    OverlayCache = new OverlayCacheBase(); // refresh, rebuilt on load
    $dialog.dialog('destroy');
}

function NewLocationsSearch()
{
    CloseLocationsSearch();
    ActLocations("new", CacheObject.SEOQueryRootPage, CacheObject.SelectedLocations);
}

function ActLocations(action, CurrentSEO, RegionIdsArray, Callback)
{
	if (CurrentSEO==null)
	{
		CurrentSEO = CacheObject.SEOQuery;
	}
    $('#selected-locations :input').attr("disabled", true);
    //return;
    
    if (CurrentSEO.indexOf("?") > -1) // strip smart search or any query
    {
		CurrentSEO = CurrentSEO.split("?")[0];
    }
    var URL = CurrentSEO + '/manage-locations';
	URL = URL.replace("//", "/");
	
	//window.location.href = URL + "?" + action + "=" + RegionIdsArray.join(',');
    //document.body.innerHTML = URL + "?" + action + "=" + RegionIdsArray.join(',');
    //return;
    //alert(URL);
    //alert(RegionIdsArray);
    var phrase = "$.get(URL, { '"+action+"' : RegionIdsArray.join(',') }, function(data)\
    {\
        if (data=='err-none')\
        {\
            window.alert('At least one location required');\
            $('#" + RegionIdsArray[0] + "').attr('checked', true);\
        }\
        else\
        {\
            var XMLDoc = ReloadList(data);\
            ReloadLocationsWithXML(XMLDoc);\
            $LocSuggest.HookupEvents();\
        }\
        if (Callback != undefined) Callback();\
    });";
    //alert(phrase);
    eval(phrase);
    //ReloadList(data);
}

var LocationsXSL = null;

function ReloadLocations(SEOQuery)
{
    var XMLPath = NormalizeSEOQuery(SEOQuery, "/xml-out");
    var XSLPath = '/Reno/Listings/SalesRentals/Xsl/Result_Locations.xslt';
    if (LocationsXSL == null)
    {
		LocationsXSL = $.xsl.load(XSLPath);
    }
    
    $('#search_by_location_wrapper').getTransform(LocationsXSL, $.xsl.load(XMLPath));
}

function ReloadLocationsWithXML(XMLDoc)
{
    var XSLPath = '/Reno/Listings/SalesRentals/Xsl/Result_Locations.xslt';
    if (LocationsXSL == null)
    {
		LocationsXSL = $.xsl.load(XSLPath);
    }
    $('#search_by_location_wrapper').getTransform(LocationsXSL, XMLDoc);
}

function CloseToolTip(Marker, Callback)
{
	return;
	/* v.2
    $('#mtgt_' + Marker.id).qtip("hide");
    
    if (Callback != undefined)
    {
        Callback();
    }
    */
}
                
function SetTooltips()
{
	return;
	/* v.2 
    for(var x=0;x<Mrkrs.length;x++)
    {
        SetToolTip(Mrkrs[x]);
    }
    */
}

function SetToolTip(Marker)
{
	return;
	/* v.2 
         // Tool Tips
        //alert($('#mtgt_' + Mrkrs[x].id).attr('id'));
        $('#mtgt_' + Marker.id).qtip({
         style: { 
            name: 'blue',
            tip: 'bottomLeft'
         },
          content: Marker.name,
            position: {
              corner: {
                target: 'topRight',
                tooltip: 'bottomLeft'
              }
            },
            show: { 
                solo: true,
                delay: 0,
                ready: true
            },
            hide: { 
                delay: 0,
                when: { event: 'mouseout' } 
            }
        });
    */
}

