var gmaps = {}


/*
    GENERAL LOCATION PLOTTING PRIMARILY FOR SEARCH RESULTS
*/
gmaps.locations = {
    container: null,
    map: null, //map instance on page is stored here

    createMap: function(element, center, zoom, onReady) {
        var I = this;
        if (center == null) center = new google.maps.LatLng(38.475895987802524, -97.82005029296873);
        if (zoom == null) zoom = 4;
        I.map = new google.maps.Map(
			element,
			{
			    center: center,

			    mapTypeId: google.maps.MapTypeId.ROADMAP,
			    mapTypeControl: true,
			    mapTypeControlOptions: {
			        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
			        //style:google.maps.MapTypeControlStyle.HORIZONTAL_BAR
			    },

			    navigationControl: true,
			    navigationControlOptions: {
			        //style: google.maps.NavigationControlStyle.SMALL
			        style:google.maps.NavigationControlStyle.ZOOM_PAN
			    },

			    scaleControl: false,
			    scaleControlOptions: {
			    //style:google.maps.ScaleControlStyle.
				},

				scrollWheel: false,
				zoom: zoom

		});

        new tbelt.gmaps.MarkerHandler(I.map);

        var evts = new gmaps.EventsGroup(gmaps.locations.map, {

            idle: function() {
                evts.releaseAll();
                if (typeof (onReady) == "function") onReady.call(this);
                delete evts;
            }

        });

    },

    jsonToMarkers: function(locations, infoWinTemplate) {
        var markers = [];
        for (var l = 0; l < locations.length; l++) {
            var location = locations[l];
            if (location.lat != "" && location.lng != "") {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng)),
                    title: location.name
                });
								
				var urlPrefix = location.Type.toLowerCase();
				if( window.location.pathname.indexOf("/pads/") > -1 )
				{
					urlPrefix = "pads";
				}
				else if( window.location.pathname.indexOf("/land/") > -1 )
				{
					urlPrefix = "land";
				}
								
                //clean up the location's data for map usage
                location.url = "/" + urlPrefix + "/property/" + location.ProjectID;
                location.sqft = parseInt(location.sqft);
                location.sqftStr = location.sqft.toString().replace(/(.+)([0-9]{3})$/, "$1,$2");
                location.address = location.location + ", " + location.City + ", " + location.ST;
				
				// create an encoded version of the location for the driving directions link
				location.locationEnc = location.location.replace("&", "%26");
				location.locationEnc = location.locationEnc.replace("?", "%3f");

                //create the info window with the cleaned location data
                var iwContent = $($tb.string.mesh(infoWinTemplate, location));
                iwContent.css({ visibility: "hidden" });
                $("div#gmap").append(iwContent);

                //console.log(iwContent.height());
                iwContent.remove();
                iwContent.css({ visibility: "visible" });

                marker.infoWindow = new google.maps.InfoWindow({
                    content: iwContent[0]
                });
                marker.infoWindow.data = location;

                google.maps.event.addListener(marker, "click", function() {
                    this.infoWindow.open(this.map, this);
                });

                google.maps.event.addListener(marker.infoWindow, "domready", function() {
                    this.isOpen = true;
                  
                    //close the other info windows
                    var markers = gmaps.locations.map.markerHandler.visibleMarkers;
                    for (var m = 0; m < markers.length; m++) {
                        var iw = markers[m].infoWindow;
                        if (iw != this && iw.isOpen) markers[m].infoWindow.close();
                    }
                });

                markers.push(marker);
            }
        }

        return markers;
    },


    getMarkerBounds: function(markers) {
        var bounds = new google.maps.LatLngBounds();
        for (var m = 0; m < markers.length; m++) {
            var pos = markers[m].getPosition();
            bounds.extend(pos);
        }
        return bounds;

    }
    /*,

    getLocations: function(query, callback) {
    var ajax = $.ajax({
    url: "/wri/locationJSON.aspx",
    data: query,
    success: function(data) {
    callback(data);
    },
    error: function() {
    alert("There was an error retrieving the locations.");
    }
    });


        return ajax;
    },
    
    cachedQueries: [],
    queryLocations: function(query) {

        function finish(markers) {
    gmaps.locations.map.fitBounds(gmaps.getMarkerBounds(markers));
    $("div.results-count > label").html(markers.length + " Properties found");
    }

        var cached = tbelt.array.searchObjects({ query: query }, gmaps.cachedQueries);

        if (cached.length == 0) {
    var cq = { query: query, markers: null };
    gmaps.cachedQueries.push(cq);
    gmaps.getLocations(query, function(json) {

                var markers = gmaps.locationsToMarkers(eval(json), unescape($("div#mapinfowindow").html()));
    cq.markers = markers;
    //create the marker handler and add all of the markers
    gmaps.locations.map.markerHandler.add(markers);

                finish(markers);

            });
    } else {
    finish(cached[0].markers);
    }

    },

    toggleFlashMap: function(isToggleOn) {
    var flash = flashMap.container = document.getElementById(flashMap.containerID);
    var gmap = gmaps.container;
    if (isToggleOn) {
    flash.style.display = "block";
    flash.style.visibility = "visible";
    gmap.style.display = "none";
    gmap.style.visibility = "hidden";
    } else {
    flash.style.display = "none";
    flash.style.visibility = "hidden";
    gmap.style.display = "block";
    gmap.style.visibility = "visible";
    }

    }*/

}




/*
    HELPS WITH THE METRO AREA DEFINITIONS
*/

gmaps.metroDef = {
    container: null,
    map: null,
    txtCenter: null,
    txtZoom: null,
    createMap: function(element, center, zoom, onReady) {
        var I = this;
        if (center == null) center = new google.maps.LatLng(38.475895987802524, -97.82005029296873);
        if (zoom == null) zoom = 4;
        I.map = new google.maps.Map(
			element,
			{
			    center: center,

			    mapTypeId: google.maps.MapTypeId.ROADMAP,
			    mapTypeControl: true,
			    mapTypeControlOptions: {
			        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
			        //style:google.maps.MapTypeControlStyle.HORIZONTAL_BAR
			    },

			    navigationControl: true,
			    navigationControlOptions: {
			        //style: google.maps.NavigationControlStyle.SMALL
			        style:google.maps.NavigationControlStyle.ZOOM_PAN
			    },

			    scaleControl: false,
			    scaleControlOptions: {
			    //style:google.maps.ScaleControlStyle.
			},

			scrollWheel: false,
			zoom: zoom

});
        I.map.isReady = false;
        var evts = new gmaps.EventsGroup(I.map, {

            idle: function() {
                if (!this.isReady) {
                    if (typeof (onReady) == "function") onReady.call(this);
                    this.isReady = true;
                }
                var center = this.getCenter();
                I.txtCenter.value = center.lat() + "," + center.lng();
                //I.txtCenter.value = this.getCenter().toString().replace(/(^\()|(\)$)/g, "");
                I.txtZoom.value = this.getZoom().toString();

            }

        });

    }


}



/*
Manages a group of MapsEventListeners
http://code.google.com/apis/maps/documentation/v3/reference.html#MapsEventListener
*/
gmaps.EventsGroup = (function(){
	
	function EventsGroup(target, eventsObj){
		
		if(target!=null) {
			this.target = target;			
			if(eventsObj!=null){
				this.bindMulti(eventsObj);
			}			
		}
		
	}
	
	EventsGroup.prototype = {
		target:null,
		
		bind:function(evtName, func){
			this[evtName] = google.maps.event.addListener(this.target, evtName, func);
			this["_"+evtName]=func;
			return this[evtName];
		},
		bindMulti:function(evtsObj){
			for(var eventName in evtsObj){
				this.bind(eventName, evtsObj[eventName]);					
			}
		},
		release:function(evtName){
			//console.log(evtName);
			//console.dir(this[evtName]);
			if(this.hasOwnProperty(evtName) && typeof(this["_"+evtName])=="function" && this[evtName].remove){
				google.maps.event.removeListener(this[evtName]);	
				delete this[evtName];
				delete this["_"+evtName];
			}				
		},
		releaseAll:function(){
			for(var eventName in this){
				this.release(eventName);
			}
		}
		
	}
	
	
	return EventsGroup;
})();




