var markerMap = new Array();
var gmarkers = [];
var htmls = [];
var labels = [];
var locationIndex = 0;

//=========================================================================
// This function picks up the click and opens the corresponding info window
function myclick(i) {
	GEvent.trigger(gmarkers[i], "click");
}

//=========================================================================
// A Test of styled info window overlay. Pulled from http://www.googlemapsbook.com/chapter9/CustomInfoWindow/map_functions.js.source#l9-5

//create the CCFInfoWindow overlay onject
function CCFInfoWindow(marker,html,width) {
	this.html_ = html;
	this.width_ = ( width ? width + 'px' : 'auto');
	this.marker_ = marker;
}

//add anew method to GMarker so you
//can use asimilar API to the existing info window.
GMarker.prototype.CCFInfoWindowInstance = null;
 
GMarker.prototype.openCCFInfoWindow = function(content,width) {
	if(this.CCFInfoWindowInstance == null) {
		this.CCFInfoWindowInstance = new CCFInfoWindow(
			this,
			content,
			width
		);
		map.addOverlay(this.CCFInfoWindowInstance);
	}
}
 
GMarker.prototype.closeCCFInfoWindow = function() {
	if(this.CCFInfoWindowInstance != null) {
		map.removeOverlay(this.CCFInfoWindowInstance);
		this.CCFInfoWindowInstance = null;
	}
}


//=========================================================================
// A function to create the marker and set up the event window
function wfCreateMarker(point, bizId, name, html, category, abbrv, type) {
    var iconfilename = gWayfindingImgBase + "/wayfinding/icons/locations/" + (locationIndex + 1) + ".png";
    var gicon = new GIcon(G_DEFAULT_ICON, iconfilename);
    //alert(iconfilename);
    //gicon.printImage = iconfilename;
    gicon.iconSize = new GSize(22, 30);
    gicon.iconAnchor = new GPoint(10, 29);
	gicon.shadow = gWayfindingImgBase + "/wayfinding/icons/shadow.png";
	gicon.shadowSize = new GSize(34, 30);

	var marker = new GMarker(point, gicon)

	GEvent.addListener(marker, "click", function() {
	    $(".map_pan_button").fadeOut(250); //.hide();
	    marker.openInfoWindowHtml(html, { maxWidth: 400 });
	    $(".map_pan_button").hide();
	});
	GEvent.addListener(marker, "infowindowbeforeclose", function() {
//	    if (isIE6()) {
	        $(".map_pan_button").show();
//	    } else {
//	        $(".map_pan_button").fadeIn(350); //.show();
//	    }
	});
//	GEvent.addListener(marker, "click", function() {
//		marker.openInfoWindowHtml(html, {maxWidth:400});
//		
//	});
	marker.category = category;

	// save the info we need to use later for the side_bar
	gmarkers[locationIndex] = marker;
	htmls[locationIndex] = html;
	locationIndex++;
	return marker;
}


function scrollToMap(duration) {
	//$('html, body').animate({
	//	scrollTop: $("#wayfinding_map").offset().top
	//}, duration);

	 $(window).scrollTop( $('#wayfinding_map').offset().top - 20 );
}


//open location bubble if deep linked URL has bizid
function initLocationClick(defaultLocation) {
	if(defaultLocation != '') {
   		GEvent.trigger(markerMap[defaultLocation.toUpperCase()], "click");
	}
}
	
//=========================================================================
function wfLoadLocationsMap(jsonDataPath, callback, jsonForcedCoordinates, defaultLocation) {
	if (GBrowserIsCompatible()) {
	    initGmap(jsonForcedCoordinates);
		var bounds = new GLatLngBounds();

//		if (jsonForcedCoordinates.IsForcedCoordinates) {
			// allow the override, forcing of lat, long and zoom
//			forceLatLongZoom(jsonForcedCoordinates);
//		} 
		
		//=========================================================================
		loadMarkers = function(jsonRaw) {
		    // bizId : marker

		    var jsonData = eval('(' + jsonRaw + ')');
		    jQuery.each(jsonData, function(locationIndex, markerArray) {
		        jQuery.each(markerArray, function(j, marker) {
		            if (marker.Lat == "" || marker.Lon == "") return;
		            var point = new GLatLng(marker.Lat, marker.Lon);
		            var gmarker = wfCreateMarker(
                                        point,
                                        marker.BizId,
                                        marker.Label,
                                        marker.Description,
                                        marker.Category,
                                        marker.Abbreviation,
                                        marker.Type);
		            map.addOverlay(gmarker);

		            if (!jsonForcedCoordinates.IsForcedCoordinates) {
		                // allow the override, forcing of lat, long and zoom
		                //forceLatLongZoom(jsonForcedCoordinates);
		                //} else {
		                bounds.extend(point);
		            }

		            // save a map of the markers based on bizId;
		            markerMap[marker.BizId] = gmarker;

		        })

		    });

		    if (jsonForcedCoordinates.IsForcedCoordinates) {
		        // allow the override, forcing of lat, long and zoom
		        forceLatLongZoom(jsonForcedCoordinates);
		    } else {
		        map.setZoom(map.getBoundsZoomLevel(bounds));
		        map.setCenter(bounds.getCenter());
		    }
		    //alert("zoom:" + map.getBoundsZoomLevel(bounds)  + " |~| center: " + bounds.getCenter());

		    if (jQuery.isFunction(callback)) {
		        callback(markerMap, gmarkers);
		    }

		    // optional paramater
		    if (defaultLocation) {
		        initLocationClick(defaultLocation);
		    }

		    if (jsonForcedCoordinates.IsForcedCoordinates) {
		        // allow the override, forcing of lat, long and zoom
		        forceLatLongZoom(jsonForcedCoordinates);
		    }
		}

		//=========================================================================
		// Get the JSON data file via Ajax
		GDownloadUrl(jsonDataPath, loadMarkers);
	}

}

function isIE6() {
    return window.external && typeof window.XMLHttpRequest == "undefined";
}


function calculateBounds(markers) {
	var bounds = new GLatLngBounds();
	var count = 0;
	jQuery.each(
        jQuery.grep(markers,
            function(marker, i) {
            	return !marker.isHidden();
            }
        )
        ,
        function(i, marker) {
        	bounds.extend(marker.getPoint());
        	count = i;
        }
    );
    if (count > 0) {
    	map.setZoom(map.getBoundsZoomLevel(bounds)-1);
    	map.setCenter(bounds.getCenter());
    }
}

function forceLatLongZoom(jsonForcedCoordinates) {
	var latLong = new GLatLng(jsonForcedCoordinates.Latitude, jsonForcedCoordinates.Longitude);
	map.setZoom(jsonForcedCoordinates.ZoomLevel);
	map.setCenter(latLong);
}



