/* MSN MapPoint / Virtual Earth JavaScript */

var centerPoint = null;
var map = null;
var dealers = null;
var dealersFound = new Array();
var pinid = 0;

 function GetMap()
 {
	if (map == null || typeof(map) == 'undefined') {
	    map = new VEMap('VEDealerMap');
		V6Dashboard();
	    map.LoadMap(centerPoint, 1);
		map._zoomLevel = 17;
		map.AttachEvent("onchangemapstyle",tagChangeMapStyle);
		// map.Resize(400,280);
		addCompassRose();
	} else {
		map.DeleteAllShapes();
		map.DeleteAllShapeLayers();
	}
	addDealers();
	map.ClearInfoBoxStyles();
 }

function V6Dashboard() {
	/*if (navigator.userAgent.indexOf("Safari") != -1 || document.location.search.indexOf("v6") != -1) {
		map.SetDashboardSize(VEDashboardSize.Small);
		map.version = 6;
	} else {
		map.SetDashboardSize(VEDashboardSize.Normal);
		map.version = 5;
	}*/
		map.SetDashboardSize(VEDashboardSize.Normal);
		map.version = 6.1;
}

 function fireClickEvent(elid) {
	
	var o = document.getElementById(elid);
	// Firefox, etc.
	if (document.createEvent) {
		var e = document.createEvent("MouseEvents");
		e.initEvent("click",true,false);
		o.dispatchEvent(e);
		alert("in if");
	} else if (document.createEventObject) {
		o.fireEvent("onclick");
		alert("in else");
	}
 }
//fireClickEvent("VEDealerMap");
	function obliqueView(e) {
		document.getElementById("MSVE_navAction_styleGroup").className="";

			var tempobj;
			try { map.SetMapStyle("o"); } catch (e) {}
			document.getElementById('MSVE_navAction_rotatorContainer').style.display='none';
			document.getElementById('obliqueCompassDiv').style.position='relative';
			if(navigator.appName=="Microsoft Internet Explorer") {
				document.getElementById('obliqueCompassDiv').style.left='10px';
				document.getElementById('obliqueCompassDiv').style.top='-35px';
				document.getElementById('obliqueCompassDiv').style.width='78px';
				document.getElementById('obliqueCompassDiv').style.height='67px';
				jQuery("obliqueCompassDiv").css({"background-image": "url(/img/dealer_locator/birdseye/compassBackground.gif)"})
			} else {
				document.getElementById('obliqueCompassDiv').style.left='10px';
				document.getElementById('obliqueCompassDiv').style.top='-35px';
			}

			jQuery("#orthoZoomOuter").hide("fast");
			jQuery("#obliqueCompassDiv").show("fast");
			jQuery("#obliqueZoomOuter").show("fast");

			if(document.getElementById('MSVE_navAction_AerialMapStyle').style.display=='block') {
					document.getElementById('MSVE_dashboardContainer').style.height='178px';
					document.getElementById('MSVE_dashboardContainer').style.top='-40px';
				} else {
				//	document.getElementById('MSVE_dashboardContainer').style.height='178px';
				//	document.getElementById('MSVE_dashboardContainer').style.top='-40px';
				}

	}

	function orthoView() {
		if (map.GetMapStyle()=="o") {
//		fireClickEvent("MSVE_navAction_OrthoMapView");
		jQuery("#obliqueCompassDiv").hide("fast");
		jQuery("#obliqueZoomOuter").hide("fast");
		jQuery("#orthoZoomOuter").show("fast");
		}
	//	alert("in MSVE_obliqueNotification");
	//	fireClickEvent("MSVE_obliqueNotification");		
	}

	function roadView() {
		orthoView();
		//document.getElementById("MSVE_navAction_styleGroup").className="MSVE_RoadMapStyle";
		document.getElementById('MSVE_navAction_RoadMapStyle').style.backgroundColor='#696969';
		document.getElementById('MSVE_navAction_RoadMapStyle').style.color='#FFFFFF';
		document.getElementById('MSVE_navAction_HybridMapStyle').style.backgroundColor='#E7E6E2';
		document.getElementById('MSVE_navAction_HybridMapStyle').style.color='#696969';
		
		map.SetMapStyle("r");
	}

	function hybridView() {
		orthoView();
	//	document.getElementById("MSVE_navAction_styleGroup").className="MSVE_HybridMapStyle";
		document.getElementById('MSVE_navAction_HybridMapStyle').style.backgroundColor='#696969';
		document.getElementById('MSVE_navAction_HybridMapStyle').style.color='#FFFFFF';
		document.getElementById('MSVE_navAction_RoadMapStyle').style.backgroundColor='#E7E6E2';
		document.getElementById('MSVE_navAction_RoadMapStyle').style.color='#696969';
		map.SetMapStyle("h");			
	}
	
 function addZoomSlider() {
	jQuery("#MSVE_zoomDiv").css({height:"134px",width:"76px"}).empty();
	jQuery("#cdpageContent").append(
		jQuery(document.createElement("div")).attr("id","orthoZoomOuter").append(
			jQuery(document.createElement("div")).attr("id","orthoZoomPlus")
			).append(
			jQuery(document.createElement("div")).attr("id","orthoZoom").append(
				jQuery(document.createElement("div")).addClass("orthoZoomIndicator")
				)
			).append(
			jQuery(document.createElement("div")).attr("id","orthoZoomMinus")
			)
		);
	jQuery("#cdpageContent").append(
		jQuery(document.createElement("div")).attr("id","obliqueZoomOuter").append(
			jQuery(document.createElement("div")).attr("id","obliqueZoomPlus")
			).append(
			jQuery(document.createElement("div")).attr("id","obliqueZoom").append(
				jQuery(document.createElement("div")).addClass("obliqueZoomIndicator")
				)
			).append(
			jQuery(document.createElement("div")).attr("id","obliqueZoomMinus")
			)
		);
	setupZoomSlider();
 }

 function addObliqueRose() {
	jQuery("#MSVE_navAction_styleGroup").append(jQuery(document.createElement("div")).attr("id","obliqueCompassDiv").css({"background-image":"url(/img/dealer_locator/birdseye/compassBackground.gif)"}).append(jQuery(document.createElement("div")).addClass("obliqueRoseCenter")));
	var ocv = jQuery("#obliqueCompassDiv .obliqueRoseCenter");
	ocv.append(jQuery(document.createElement("div")).addClass("obliqueCompassArrowU").attr("id","obliqueCompassArrow"));
	ocv.append(jQuery(document.createElement("div")).addClass("obliqueRosePoint").attr("id","oRPN").html("N").css({left: "0px","top":"-24px"}));
	ocv.append(jQuery(document.createElement("div")).addClass("obliqueRosePoint").attr("id","oRPE").html("E").css({left: "24px","top":"0px"}));
	ocv.append(jQuery(document.createElement("div")).addClass("obliqueRosePoint").attr("id","oRPS").html("S").css({left: "0px","top":"24px"}));
	ocv.append(jQuery(document.createElement("div")).addClass("obliqueRosePoint").attr("id","oRPW").html("W").css({left: "-24px","top":"0px"}));
 	setupObliqueRosePoints();
 }
 function addCompassRose() {	
//		var becr = document.getElementById("MSVE_navAction_mapStyleCell");
		var becr = document.getElementById("MSVE_navAction_styleGroup");
		var roadstyle = document.createElement("div");
		var aerialstyle = document.createElement("div");
		var hybridstyle = document.createElement("div");
		for (var i = 0, l = becr.childNodes.length; i < l; i++) {
			becr.removeChild(becr.firstChild);
		}
		aerialstyle.className="MSVE_MapStyle";
		aerialstyle.id="MSVE_navAction_AerialMapStyle";
		hybridstyle.className="MSVE_MapStyle";
		hybridstyle.id="MSVE_navAction_HybridMapStyle";
		roadstyle.className="MSVE_MapStyle";
		roadstyle.id="MSVE_navAction_RoadMapStyle";
		jQuery(becr).attr("style","display: block !important");
		becr.parentNode.insertBefore(becr,becr.parentNode.firstChild);
		roadstyle.innerHTML="ROAD";
		hybridstyle.innerHTML="HYBRID";
		aerialstyle.innerHTML="BIRD'S EYE";
		aerialstyle.style.display="none";
		roadstyle.style.top='144px';
		roadstyle.style.left='12px';
		roadstyle.style.width='66px';
		roadstyle.style.height='20px';
		roadstyle.style.zIndex='150';
		roadstyle.style.backgroundColor='#E7E6E2';
		hybridstyle.style.top='140px';
		hybridstyle.style.left='12px';
		hybridstyle.style.width='66px';
		hybridstyle.style.height='20px';
		hybridstyle.style.zIndex='150';
		hybridstyle.style.backgroundColor='#E7E6E2';
		aerialstyle.style.top='136px';
		aerialstyle.style.left='12px';
		aerialstyle.style.width='66px';
		aerialstyle.style.height='20px';
		aerialstyle.style.zIndex='150';
		aerialstyle.style.backgroundColor='#E7E6E2';
		becr.appendChild(roadstyle);
		becr.appendChild(hybridstyle);
		becr.appendChild(aerialstyle);
		roadstyle.attachEvent("onclick",roadView);
		hybridstyle.attachEvent("onclick",hybridView);
		aerialstyle.attachEvent("onclick",obliqueView);
		
	//	document.getElementById('VEDealerMap').attachEvent("onclick",setupZoomSlider);
		document.getElementById('MSVE_navAction_toggleGlyphWrapper').style.display='none';
		document.getElementById('MSVE_navAction_topBackground').style.display='none';
		document.getElementById('MSVE_navAction_compassBackground').style.display='none';
		document.getElementById('MSVE_navAction_leftBackground').style.display='none';
		document.getElementById('MSVE_navAction_modeCell').style.display='none';
		document.getElementById('MSVE_navAction_showLabels').style.display='none';
		document.getElementById('MSVE_navAction_compassContainer').style.display='none';
		document.getElementById('MSVE_TinyZoomBar').style.display='none';
		document.getElementById('MSVE_navAction_separator0').style.display='none';
		document.getElementById('MSVE_navAction_separator3').style.display='none';
		document.getElementById('MSVE_navAction_separator2').style.display='none';
		
		
		var dashboardContainer=document.createElement("div");
		dashboardContainer.id="MSVE_dashboardContainer";
		var stylegroup=document.getElementById('MSVE_navAction_styleGroup');
		stylegroup.appendChild(dashboardContainer);


		document.getElementById('MSVE_navAction_RoadMapStyle').style.backgroundColor='#696969';
		document.getElementById('MSVE_navAction_RoadMapStyle').style.color='#FFFFFF';


		map.AttachEvent("onendzoom",zoomHandler)
		
		/*if (navigator.userAgent.indexOf("Safari") != -1 || document.location.search.indexOf("v6") != -1) {
			addZoomSlider();
			addObliqueRose();
		}*/
		
			addZoomSlider();
			addObliqueRose();

		// Add Compass Rose for Movement
		var cr = document.createElement("div");
		document.getElementById("cdpageContent").appendChild(cr);
		jQuery(cr).css({
			position: "absolute",
			top: "333px",
			right: "5px",
			backgroundImage: "url(/img/dealer_locator/compass_rose.png)",
			backgroundRepeat: "no-repeat",
			width: "57px",
			height: "56px",
			cursor: "pointer",
			border: "solid 1px #858585"
		}).ifixpng().click(function (e) {
			var t = jQuery(e.target);
			var pos=t.offset();
			pos.top=e.pageY-pos.top;
			pos.left=e.pageX-pos.left;
			var plane = { height: t.height(), width: t.width() };
			var d="", d2="";
		 	if (pos.top*100 / plane.height <= 33) d = "North";
		 	if (pos.top*100 / plane.height >= 66) d = "South";
			if (pos.left*100 / plane.width <= 33) d2 = "West";
			if (pos.left*100 / plane.width >= 66) d2 = "East";
			pan(d.length>0?d:d2,d.length>0?d2:null);
			e.preventDefault();
			e.stopPropagation();
		});	
	}

 function zoomIn() {
	zoomTo(map._zoomLevel - 1);
 }

 function zoomOut() {
	zoomTo(map._zoomLevel + 1);
 }

 function zoomTo (zoomLevel) {
	map._zoomLevel = zoomLevel;
	map.SetZoomLevel(18-zoomLevel);
	for (var z = 1; z <= 10; z++) {
		document.getElementById("zoom"+z).src="images/icon_map_zoom_" + (z == zoomLevel ? "on" : "off") + ".gif";
	}
 }

 function zoomToFit() {
	var minLat = 3000000;
	var minLng = 3000000;
	var maxLat = -300000;
	var maxLng = -300000;

	for (var d = 0; d < dealersFound.length; d++) {
		var ll = dealersFound[d].LatLong;
		if (ll.Latitude < minLat)
			minLat = ll.Latitude;
		if (ll.Latitude > maxLat)
			maxLat = ll.Latitude;
		if (ll.Longitude < minLng)
			minLng = ll.Longitude;
		if (ll.Longitude > maxLng)
			maxLng = ll.Longitude;
	}

	var centerLat = minLat + ((maxLat - minLat)/2);
	var centerLng = minLng + ((maxLng - minLng)/2);

	centerPoint = new VELatLong(centerLat,centerLng);

	map.SetCenter(centerPoint);

	var topleftLL = new VELatLong(minLat,minLng);
	var bottomrightLL = new VELatLong(maxLat,maxLng);

	var topleftPx = map.LatLongToPixel(topleftLL);
	var bottomrightPx = map.LatLongToPixel(bottomrightLL);
	var infinite_loop_catcher = 0;

	while (((topleftPx.y < 25 && topleftPx.x < 200) || topleftPx.x < 0 || topleftPx.y < 0 || bottomrightPx.x > 400 || bottomrightPx.y > 250) && infinite_loop_catcher < 21) {
		map.ZoomOut();
		topleftPx = map.LatLongToPixel(topleftLL);
		bottomrightPx = map.LatLongToPixel(bottomrightLL);
		infinite_loop_catcher++;
	}
 }

 function pan (direction,direction2) {
	var x = -1, y = -1;
	switch (direction) {
		case 'North':
			x = 313;
			y = 98;
			break;
		case 'South':
			x = 313;
			y = 299;
			break;
		case 'West':
			x = 149;
			y = 197;
			break;
		case 'East':
			x = 475;
			y = 197;
			break;
	}
	switch (direction2) {
		case 'West':
			x = 149;
			break;
		case 'East':
			x = 475;
			break;
	}
	if (x > 0 && y > 0) {
    	var ll = map.PixelToLatLong(new VEPixel(x,y));
	//	document.getElementById("panTail").style.display="none";
		map.AttachEvent("onendpan",rePanTail);
		map.PanToLatLong(ll);
	}
 }

 function addDealers() {
	var dealers = new Array();

	for (var d = 0; d < dealersFound.length; d++) {
		// Name, Description, LatLong
		dealers.push(
			AddPushPin(
				dealersFound[d].Index,
				dealersFound[d].Name,
				dealersFound[d].Description,
				dealersFound[d].LatLong
				)
		);
	}

	//zoomToFit();

	showAll();
 }

function addDealer ( index, name, description, lat, Long ) {
	dealersFound.push(new _VEDealer(index, name,description,lat,Long));
}

function _VEDealer ( index, name, description, Lat, Long) {
	this.Index = index;
	this.Name = name;
	this.Description = description;
	this.LatLong = new VELatLong(Lat,Long);
}

function AddPushPin(index, name, desc, position) {
	iconHtml = "<img src=\"/img/dealer_locator/icons/mapmarker"+index+".png\" class=\"MapPushPin\" alt=\""+index+"\">"
	var shape = new VEShape(VEShapeType.Pushpin, position);
	shape.SetCustomIcon(iconHtml);
	shape.SetTitle(name);
	shape.SetDescription(InfoBoxDesc(index-1));
	pinid++;
	map.AddShape(shape);
	// jQuery("#"+shape.GetId()+" div img").css({behavior: "url(/css/m/png.htc) !important"});

	return shape;
}

function InfoBoxDesc(index) {
	var d = document.createElement("div");
	var dd = document.createElement("p");
	var dda = document.createElement("a");
	var ddlink = location.href.substring(0,location.href.indexOf("#"))+"#dealer"+index;
	dd.appendChild(dda);
	dda.href="javascript:location.replace('"+ddlink+"');void(null)";
	dda.setAttribute("onclick","viewDealerDetails("+index+");crmEvent3({'Method':'Popup'})");
	if (/espanol/.test(location.pathname)) {
		dda.innerHTML = "Ver Detalles"; // modify with asset
	}else{
		dda.innerHTML = "View Dealer Details";
	}
	var dx = document.createElement("p");
	var dxa = document.createElement("a");
	dx.appendChild(dxa);
	dxa.href="javascript:void(null)";
	dxa.setAttribute("onclick","displayDrivingDirections('infoInputBox',"+index+");crmEvent4({'Method':'Popup'})");
	if (/espanol/.test(location.pathname)) {
		dxa.innerHTML = "Direcciones"; // modify with asset
	}else{
		dxa.innerHTML = "Get Driving Directions"; // modify with asset
	}
	d.appendChild(dd);
	d.appendChild(dx);
	// input box for mini directions
	var ii = document.createElement("div");
	ii.id="infoInputBox";
	ii.style.display = "none";
	d.appendChild(ii);
	var ij = document.createElement("div");
	ij.style.clear="left";
	d.appendChild(ij);
	return d.innerHTML;
}

function getInitialMap(){
	map = new VEMap('VEDealerMap');
	V6Dashboard();
	map.LoadMap();
	map.SetZoomLevel(4);
	map.AttachEvent("onchangemapstyle",tagChangeMapStyle);
	addCompassRose();
}

function tagChangeMapStyle(e) {
	var param = {};
	switch (e.mapStyle) {
		case "a": // Aerial
			// overloading map style to oblique/birdseye
			// map.SetMapStyle(VEMapStyle.Oblique);
			// return true;
			break;
		case "h": // Hybrid
			param["View"]="Hybrid";
			break;
		case "o": // Birds' Eye (oblique)
			param["View"]="BirdsEye";
			break;
		case "r": // Road
			param["View"]="Road";
			break;
	}
	crmEvent11(param);
	return false;
}
