//
var map, dMap, centerPoint, zoomLevel, zoomLimit, mapMoveListener, northernMostIndex, thickboxInterval, infoWindowWidth;
var allowedBounds = new GLatLngBounds();
var maxZoom = 12;
// array to hold copies of the markers as well as additional dealer info
var dmaDealers = [];
var gDir;
var directionsMapSet = false;
var standardIconImageMap = [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0];
var invModel, invTrim, virModel, virTrim, searchParams;
// A flag that when true will cause the GAQ btns to not get displayed (can be set in dealer site)
var noGAQ = false;

// NOTE: use jQuery(window).load here instead of jQuery(document).ready
// - this seems to allow Safari enough time to apply CSS to the map div
jQuery(".mapBtn").livequery("click", function() {
	initTBMap();
});
							
function initMap() {
	if (lmaObjHolder.dealers == undefined) {
		alert("There are no dealers associated with this LMA.");
	} else if (GBrowserIsCompatible()) {
    	map = new GMap2(document.getElementById("mapCanvas"));
		centerPoint = new GLatLng(39.50,-98.35);
		zoomLevel = 3;
		map.setCenter(centerPoint,zoomLevel,G_NORMAL_MAP);  
		//
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());
		map.checkResize();
		//
		GEvent.addListener(map, "infowindowopen", onInfoWindowUpdate);
		//
		setInfoWindowWidth();
		map.clearOverlays();
		jQuery("#mapCanvas").ready(function () {
	  		handleDealerXml(lmaObjHolder);
		});
	}
}

function initTBMap(rModel, rTrim, vModel, vTrim, sParams) {
	// Set value for the model and trim name to be used for search and GAQ drop-down population
	(rModel == undefined) ? invModel = "" : invModel = rModel;
	(rTrim == undefined) ? invTrim = "": invTrim = rTrim;
	// Set value for the model and trim name to be used for display
	(vModel == undefined) ? virModel = "" : virModel = vModel;
	(vTrim == undefined) ? virTrim = "": virTrim = vTrim;
	// searchParams to be used instead of simply model name for inventory search (can use modelid and/or year, etc.)
	(sParams == undefined) ? searchParams = "": searchParams = sParams;
	//
	if (lmaObjHolder.dealers == undefined) {
		alert("There are no dealers associated with this LMA.");
	} else if (GBrowserIsCompatible()) {
		var tbGAQMap = tb_show("Select your nearest dealer", "#TB_inline?width=600&height=450&inlineId=mapWrapper", null);
    	map = new GMap2(document.getElementById("mapCanvas"));
		centerPoint = new GLatLng(39.50,-98.35);
		zoomLevel = 3;
		map.setCenter(centerPoint,zoomLevel,G_NORMAL_MAP);  
		//
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());
		map.checkResize();
		//
		GEvent.addListener(map, "infowindowopen", onInfoWindowUpdate);
		//
		setInfoWindowWidth();
		map.clearOverlays();
		jQuery(tbGAQMap).ready(function () {
			// tweak Thickbox CSS
			jQuery("#TB_title").css("height", "30px");
			jQuery("#TB_ajaxWindowTitle").css("padding-top", "8px");
			jQuery("#TB_ajaxWindowTitle").css("padding-left", "10px");
			jQuery("#TB_ajaxWindowTitle").css("font-weight", "bold");
			jQuery("#TB_ajaxContent").css("padding", "10px");
			jQuery("#TB_ajaxContent").css("overflow","hidden");
	  		handleDealerXml(lmaObjHolder);
		});
	}
}

// Safari hack.  Safari wants a set width for the generated infoWindow HTML.
// To find this, we'll create a temporary div to access the relevant layout CSS values.
// This is necessary since some LSLP layouts have narrow infoWindows (like GMC).
function setInfoWindowWidth() {
	jQuery("body").append("<div id='tempMapDiv' style='visibility:hidden'><div class='col1'></div><div class='col2'></div></div>");
	// if col2 is set to clear:left, then we know this is a narrow layout
	var isNarrow = (jQuery("#tempMapDiv .col2").css("clear") == "left")? true: false;
	var colWidth1 = jQuery("#tempMapDiv .col1").width();
	var colWidth2 = jQuery("#tempMapDiv .col2").width();
	infoWindowWidth = (isNarrow)? (colWidth1) : (colWidth1 + colWidth2);
	jQuery("#tempMapDiv").remove();
}

function handleDealerXml(lmaInfo) {
	jQuery("#dmaSearchLoadImage").hide();
	if (typeof mapMoveListener != "undefined") { GEvent.removeListener(mapMoveListener); }
	map.clearOverlays();
	showDealers(lmaInfo);
}

function showDealers(lmaInfo) {
	var lat, lng, latLng, marker, dealerOb, curDealer;
	var northernMostLatitude = -90;
	var bounds = new GLatLngBounds();
	var zipCenter = false;
	for(var i=0; i < lmaInfo.dealers.length; i++) {
		curDealer = lmaInfo.dealers[i];
		lat = parseFloat(curDealer.latitude);
		lng = parseFloat(curDealer.longitude);
		latLng = new GLatLng(lat,lng);
		if (lat > northernMostLatitude) { northernMostLatitude = lat; northernMostIndex = i}
		if (i == 0 && !zipCenter) { // recenter map based on first marker
        	centerPoint = latLng;
        	map.setCenter(centerPoint, zoomLevel);
        }
		marker = createMarker(latLng, curDealer.dealerName, i);
		
		dealerOb = new Object();
		dealerOb = curDealer;
		dealerOb.gMarker = marker;
		dmaDealers.push(dealerOb);
		
		bounds.extend(latLng);
		map.addOverlay(marker);
	}
	// reset map bounds and zoom restraints
	zoomLimit = map.getBoundsZoomLevel(bounds);
	if (!zipCenter) { zoomLimit -= 1; }  // zoom out a bit more
	if (zoomLimit > maxZoom) { zoomLimit = maxZoom; }
	setZoomConstraint(zoomLimit);
	
	map.setZoom(zoomLimit);
	if (!zipCenter) { 
		map.setCenter(bounds.getCenter());
	}
	if (dmaDealers.length > 0) {
		allowedBounds = map.getBounds();
		extendAllowedBounds();
	    //
		mapMoveListener = GEvent.addListener(map, "move", function() {
	    	checkBounds();
	    });		
	}
	// If only one dealer, expand infoWindow
	if (dmaDealers.length == 1) {
		GEvent.trigger(dmaDealers[0].gMarker, "click");
	}
}
function createMarker(latLng, markerTitle, markerIndex) {
  var marker = new GMarker(latLng, {title:markerTitle});
  marker.index = markerIndex;
  GEvent.addListener(marker, "click", function() {
	var html = getMarkerHtml(this.index);
	this.openInfoWindowHtml(html);
	// This is for the admission inventory SWF.  Communicates the selected dealer to the SWF to show its inventory.
	if (window.changeDealer) {
		changeDealer(dmaDealers[this.index].webId);
	}
	// Callback provided by "infowindowopen" --> onInfoWindowUpdates
	//
	var thisDealerWebId = dmaDealers[this.index].webId;	
	sendPixelTag({
		pageLabel:"Map_Balloon",
		pageLayoutName: "Map_Balloon",
		pageName:"Map_Balloon",				
		webId:thisDealerWebId
	});	
	EventManager.publish({
		eventName:'com.cobaltgroup.ws.action.open.map.dealerBubble',
		publisherData:{
			pageLabel:"Map_Balloon",
			pageLayout: "Map_Balloon",
			pageName:"Map_Balloon",				
			webId:thisDealerWebId
		}
	});
  });
  return marker;
}

function getMarkerStandard() {
	var icon = new GIcon();
    icon.image = assetServerUrl + "/common/images/mapImages/marker_yellow.png";
    icon.iconSize = new GSize(20, 34);
    icon.shadow = "http://www.google.com/mapfiles/shadow50.png"; 
    icon.shadowSize = new GSize(37, 34);
    icon.iconAnchor = new GPoint(9, 34);
    icon.infoWindowAnchor = new GPoint(9, 2);
    icon.transparent = "http://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";
    icon.imageMap= standardIconImageMap; 
	return icon;
}

function setZoomConstraint(val) {
	var mt = map.getMapTypes();
	for (var i=0; i<mt.length; i++) {
    	mt[i].getMinimumResolution = function() {return val;}
    }
}
function removeZoomConstraint() {
	var mt = map.getMapTypes();
	for (var i=0; i<mt.length; i++) {
    	mt[i].getMinimumResolution = function() {return 0;}
    }
}

// If the map position is out of range, move it back
function checkBounds() {
  	if (allowedBounds.contains(map.getCenter())) {
   		return;
  	}
  	// not OK, so find the nearest allowed point and move there
  	var C = map.getCenter();
  	var X = C.lng();
  	var Y = C.lat();
  	var AmaxX = allowedBounds.getNorthEast().lng();
  	var AmaxY = allowedBounds.getNorthEast().lat();
  	var AminX = allowedBounds.getSouthWest().lng();
  	var AminY = allowedBounds.getSouthWest().lat();
  	if (X < AminX) {X = AminX;}
  	if (X > AmaxX) {X = AmaxX;}
  	if (Y < AminY) {Y = AminY;}
  	if (Y > AmaxY) {Y = AmaxY;}
  	//
  	map.setCenter(new GLatLng(Y,X));
}
/*
	Make sure map bounds will allow the northernmost infoWindow to fully display
*/
function extendAllowedBounds() {
	var infoWindowHeight = 320;  // pixels needed to show entire infoWindow
	var canvasHeight = parseInt(jQuery("#mapCanvas").css("height"));
	//
	var topLeftLatLng = map.fromContainerPixelToLatLng(new GPoint(0,0),true); 
	var topLeftDivPixel = map.fromLatLngToDivPixel(topLeftLatLng);  // divPixel of top left corner
	var northDivPixel = map.fromLatLngToDivPixel(dmaDealers[northernMostIndex].gMarker.getLatLng());  // divPixel of northernmost marker
	var pixToTop = northDivPixel.y - topLeftDivPixel.y;
	//
	var pixelsNeeded = infoWindowHeight - (pixToTop + (canvasHeight/2));
	if (pixelsNeeded > 0) {
		var latRange = allowedBounds.getNorthEast().lat() - allowedBounds.getSouthWest().lat();
		var latPerPixel = latRange / canvasHeight;
		var extraLatNeeded = pixelsNeeded * latPerPixel;
		//
		var newNorthEastLat = allowedBounds.getNorthEast().lat() + extraLatNeeded;
		allowedBounds.extend(new GLatLng(newNorthEastLat, allowedBounds.getNorthEast().lng()));
	}
}

// ********************************************************************************************

function onInfoWindowUpdate() {
	var dIndex = jQuery("#infoWindowIndex").val();
	if (dmaDealers[dIndex].pixelTags.showAddress) {
		// user has already seen address
		jQuery("#showAddressText").hide();
		jQuery("#showAddressIcon").hide();
	} else {
		jQuery("#infoWindowDealerAddress").hide();
		jQuery('#showAddress').click(function () { 
			showAddress();
		});
	}
}

function getMarkerHtml(dealerIndex) {
	var i;
	var numLinks = dmaDealers[dealerIndex].links.length;
	var urlAppend = (lmaObjHolder.urlAppend == "null") ? "" : lmaObjHolder.urlAppend;
	var html = "";
	if ((invModel == "") || (invModel == undefined)) {
		var dealerName = dmaDealers[dealerIndex].gMarker.getTitle();
		// NOTE: Safari needs to have the width of the containing element defined inline
		html += "<div id='infoWindowContainer' style='width:" + infoWindowWidth + "px'><input type='hidden' id='infoWindowIndex' value='" + dealerIndex + "'><div id='infoWindowDealerName'>";
		html += dealerName;
		html += "</div><div class='col1 floatLeft'>";
		html += "<div id='infoWindowDealerAddress'>";
		html += dmaDealers[dealerIndex].street1;
		if (dmaDealers[dealerIndex].street2 != "null") { html += ", " + dmaDealers[dealerIndex].street2; }
		html += "<br />" + dmaDealers[dealerIndex].city + ", " + dmaDealers[dealerIndex].state + " " + dmaDealers[dealerIndex].zip;
		html += "</div><br /><br /><div class='infoTitle'>CONTACT US</div>";
		//
		var numPhone = dmaDealers[dealerIndex].phone.length;
		for (i=0; i<numPhone; i++) {
			html += "<div class='phone" + (i+1) + "'>";
			if (dmaDealers[dealerIndex].phone[i].value!=null && dmaDealers[dealerIndex].phone[i].value!="undefined") {
				html += dmaDealers[dealerIndex].phone[i].label + ": " + dmaDealers[dealerIndex].phone[i].value;
			}
			html += "</div>";
		}
		html += "<div class='url'>";
		for (i=0; i<numLinks; i++) {
			if (dmaDealers[dealerIndex].links[i].label == "Home Page") {
				var thisURL = dmaDealers[dealerIndex].links[i].url;
				if (urlAppend != "") {
					thisURL += (thisURL.indexOf("?") > -1) ? "&" + urlAppend : "?" + urlAppend;
				}
				html += "Website: <a href='" + thisURL + "' target='_new'>" + dealerName + "</a></div>"
				break;
			}
		}
		html += "<br /><div class='infoTitle'>MORE ACTIONS</div>";
		var linkCounter = 1;
		for (i=0; i<numLinks; i++) {
			if (dmaDealers[dealerIndex].links[i].label != "Home Page") {
				html += "<div class='link' id='link" + linkCounter + "'>";
				var thisURL = dmaDealers[dealerIndex].links[i].url;
				if (dmaDealers[dealerIndex].links[i].label == "Browse Inventory") {
					html += "<a href='" + thisURL + "?search=new&make=" + make + "&" + urlAppend + "' target='_new'>" + dmaDealers[dealerIndex].links[i].label + "</a>";
				} else {
					if (urlAppend != "") {
						thisURL += (thisURL.indexOf("?") > -1) ? "&" + urlAppend : "?" + urlAppend;
					}
					html += "<a href='" + thisURL + "' target='_new'>" + dmaDealers[dealerIndex].links[i].label + "</a>";
				}
				html += "</div>";
				linkCounter++;
			}
		}
		//
		html += "<br /><br /><br /></div><div class='col2 floatLeft'><div>";
		html += "<img class='infoWindowDealerLogo' width='100' height='100' src='" + makeLogoPath + ".gif'>";
		html += "</div><div>";
		if (!noGAQ) {
			html += "<a href='#GAQ' onclick='initGetAQuote(" + dealerIndex + ", true); return false' class='thickbox'><img src='"+designColorPath+"/images/btn_GAQ.png' alt='Get a Quote' class='infoWindowGAQ_btn' /></a>";
		}
		html += "</div></div></div>";
	} else {
		var dealerName = dmaDealers[dealerIndex].gMarker.getTitle();
		// NOTE: Safari needs to have the width of the containing element defined inline
		html += "<div id='infoWindowContainer' style='width:" + infoWindowWidth + "px'><input type='hidden' id='infoWindowIndex' value='" + dealerIndex + "'>";
		var modelName = (virModel == "") ? invModel : virModel;
		html += "<div id='modelDescription'>View new<span class='modelName'> " + modelName + " </span>inventory at</div>";
		html += "<div id='infoWindowDealerName' style='float: left; padding-top: 25px; width: 210px;'>" + dealerName + "</div>";
		html += "<div style='float: right; width: 100px; height: 115px'><img class='infoWindowDealerLogo' width='100' height='100' src='" + makeLogoPath + ".gif' style='margin: 5px 0 10px 0;' /></div>";
		html += "<div style='clear: both'></div>";
		for (i=0; i<numLinks; i++) {
			if (dmaDealers[dealerIndex].links[i].label == "Browse Inventory") {
				var tempURLsuffix = (searchParams == "") ? ("&model=" + invModel) : searchParams; 
				html += "<div id='mapInvLink' style='float: left; width: 150px;'><a href='" + dmaDealers[dealerIndex].links[i].url + "?search=new&make=" + make + tempURLsuffix + "&" + urlAppend + "' target='_new'><img src='" + designColorPath + "/images/btn_INV.png' alt='View Inventory' /></a></div>";
				if (!noGAQ) {
					html += "<div id='mapGaqLink' style='float: left; width: 88px;'><a href='#GAQ' onclick='initGetAQuote(" + dealerIndex + ", true); return false' class='thickbox'><img src='"+designColorPath+"/images/btn_GAQ.png' alt='Get a Quote' class='infoWindowGAQ_btn' /></a></div>";
				}
				break;
			}
		}
		html += "</div>";		
	}
	return html;
}

function showAddress() {
	jQuery("#showAddress").unbind('click');
	jQuery("#infoWindowDealerAddress").show();
	jQuery("#showAddressText").hide();
	jQuery("#showAddressIcon").hide();
	// pixel tag
	var dIndex = jQuery("#infoWindowIndex").val();
	dmaDealers[dIndex].pixelTags.showAddress = true;
	//
	var thisDealerWebId = dmaDealers[dIndex].webId;
	sendPixelTag({
		pageLabel:"Map_Address",
		webId:thisDealerWebId
	});
}

// ********************************************************************************************

function showDirections(dealerIndex) {
	var dName = dmaDealers[dealerIndex].gMarker.getTitle();
	// thickbox
	tb_show("", "#TB_inline?width=785&height=500&inlineId=hiddenMapDirections", null);
	//
	jQuery("#TB_window").ready(function () {
		initDirections(dealerIndex);
	});
	// event when Thickbox is closed
	jQuery("#TB_window").unload(function () {
		gDir.clear();
		dMap.clearOverlays();
		setZoomConstraint(zoomLimit);
	});
	// pixel tag
	var thisDealerWebId = dmaDealers[dealerIndex].webId;
	sendPixelTag({
		pageLabel:"Map_Print_Directions",
		webId:thisDealerWebId
	});
}

function initGetAQuote (dealerIndex, thickboxOpen) {
	if (thickboxOpen) {
		tb_remove();
		// jQuery.timers plugin
		jQuery(document).everyTime(10, 'checkThickbox', function() {
			waitForThickboxUnload(dealerIndex);
		});
	} else {
		showGetAQuote(dealerIndex);
	}
}

function waitForThickboxUnload(dealerIndex) {
	if (jQuery("#TB_window").length == 0) {
		jQuery(document).stopTime('checkThickbox');
		showGetAQuote(dealerIndex);
	}
}

function showGetAQuote(dealerIndex) {
	FormUtility.resetErrors();
	resetGAQ();
	var tbGAQMap = tb_show("Get a quote", "#TB_inline?width=593&height=213&inlineId=gaqFormWrapper", null);
	jQuery(tbGAQMap).ready(function () {
		jQuery("#lslp_gaq_vehImgCont").empty();
		// tweak Thickbox CSS
		jQuery("#TB_title").css("height", "30px");
		jQuery("#TB_ajaxWindowTitle").css("padding-top", "8px");
		jQuery("#TB_ajaxWindowTitle").css("padding-left", "10px");
		jQuery("#TB_ajaxWindowTitle").css("font-weight", "bold");
		jQuery("#TB_ajaxContent").css("overflow","hidden");
		if (invModel != "") {
			jQuery("#gaq_model").val(invModel).triggerHandler("change");
			jQuery("#gaq_trim").val(invTrim).triggerHandler("change");
		} else {
			jQuery("#gaq_model").val(taxonomySearch.getModel()).triggerHandler("change");
			jQuery("#gaq_trim").val(taxonomySearch.getTrim()).triggerHandler("change");
		}
		jQuery("#gaq_fromMapField").val("true");
		var dealerIndex = jQuery("#infoWindowIndex").val();
		var thisDealerWebId = dmaDealers[dealerIndex].webId;
		jQuery("#dealerSelect").val(thisDealerWebId);
		sendPixelTag({
			pageLabel:"GAQ_Map",
			pageLayoutName: "GAQ",
			pageName:"GAQ",
			webId:thisDealerWebId
		});
		EventManager.publish({
			eventName:'com.cobaltgroup.ws.view.leadForm.getAQuote',
			publisherData:{
				pageLabel:"GAQ_Map",
				pageLayout: "GAQ",
				pageName:"GAQ",
				webId:thisDealerWebId
			}
		});
	});
}