var lastOpenInfoWnd = null;

$(function() {
	// Instantiate Google map.
	GoogleMap = new GoogleMapV3();
	GoogleMap.init($("#map").get(0), $("#map_dir_text").get(0));
	
	// Init display.
	$("#cust1st").hide();
});

// Google map V3 object.
var GoogleMapV3 = function() {
	// Vars.
	this.map;
	this.geocoder;
	this.dealerMarkers;
	this.locale = "en_US";
	this.icon = "http://static.dealertown.com/dashboard/dealerSites/defaultSuzukiDealer/_m/gmap_icon.png";
	this.directionDisplay;
	this.directionsService = new google.maps.DirectionsService();
	this.latlng;
	this.gmOptions;
	this.lastOpenInfoWnd;

	
	// Init map.
	this.init = function(mapdiv, mapDirDiv) {
		if (mapdiv) { // check for browser compatibility
			// Setup map
		    var latlng = new google.maps.LatLng(38.54816542304656, -92.63671875);
		    var gmOptions = {
		      zoom: 4,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP,
		      mapTypeControl: true,
		      navigationControl: true,
		      navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN}
		    };
		    //position: new ControlPosition(ControlPosition.ANCHOR_BOTTOM_LEFT, 10, 40)
			this.map = new google.maps.Map(mapdiv, gmOptions);
			this.directionsDisplay = new google.maps.DirectionsRenderer();
			this.directionsDisplay.setMap(this.map);
			this.directionsDisplay.setPanel(mapDirDiv);
			
			// Setup vars
			this.geocoder = new google.maps.Geocoder();
			this.dealerMarkers = new Array();
			this.lastOpenInfoWnd = new google.maps.InfoWindow();
		}
	}
	
	// Load driving directions.
	this.loadDrivingDirections = function(from, to, locale, callback) {
		var request = {
				origin: from,
				destination: to,
				provideRouteAlternatives: false,
				travelMode: google.maps.DirectionsTravelMode.DRIVING,
				unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
			};
			this.directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					GoogleMap.directionsDisplay.setDirections(response);
					GoogleMap.showSteps(response);
					if (callback) {
						callback();
					}
				}
			});
	}
	
	this.showSteps = function(directionResult) {
		  // For each step, place a marker, and add the text to the marker's
		  // info window. Also attach the marker to an array so we
		  // can keep track of it and remove it when calculating new
		  // routes.
		  var myRoute = directionResult.routes[0].legs[0];

		  for (var i = 0; i < myRoute.steps.length; i++) {
		      var marker = new google.maps.Marker({
		        position: myRoute.steps[i].start_point, 
		        map: GoogleMap.map
		      });
		      GoogleMap.attachInstructionText(marker, myRoute.steps[i].instructions);
		      GoogleMap.dealerMarkers[i] = marker;
		  }
	}
// this.lastOpenInfoWnd
	this.attachInstructionText = function(marker, text) {
		google.maps.event.addListener(marker, 'click', function() {
			GoogleMap.lastOpenInfoWnd.setContent('<div style="padding-top: 10px;">' + text + "</div>");
			GoogleMap.lastOpenInfoWnd.open(GoogleMap.map, marker);
		});
	}
	
	// Add a dealer marker.
	this.addDealerMarker = function(name, lat, lng, custinfo, icon) {

		// Collect customer info.
		custinfo = custinfo && custinfo != null ? custinfo : {};
		var srv = custinfo["srv"];
		var header = custinfo["header"];
		var title = custinfo["title"];
		var description = custinfo["description"];
		var street = custinfo["street"];
		var city = custinfo["city"];
		var state = custinfo["state"];
		var zip = custinfo["zip"];
		var phone = custinfo["phone"];
		var dist = custinfo["dist"];
		var homepage = custinfo["homepage"];
		var extra = custinfo["extra"] ? custinfo["extra"] : " target='_blank'";
		
		// use passed icon over defautl icon
		if(icon != null){
			this.icon = icon;
		}
		
		// Create marker.
		var inert = !(street && city && state && zip);
		var marker = new google.maps.Marker({
		      position: new google.maps.LatLng(lat, lng),
		      map: this.map,
		      icon: this.icon
		});

		if (!inert) {
			var markerText="<div class='map_dealer_info'>"
				+ "<b>" + (homepage ? "<a href='" + homepage + "' " + extra + ">" + name + "</a>" : name) + "</b>"
				+ "<br>" + srv
				+ "<br>" + street
				+ "<br>" + city + ", " + state + " " + zip
				+ "<br>" + phone 
				+ (dist ? "<br>Distance: <b>" + dist + "</b> miles" : "")
				+ "<br>"
				+ "<br><b>" + title + "</b>"
				+ "<br>" + description
				+ "<br>";
			markerText+="<b>For driving directions, please enter your zip or<br>street address, city, and state:</b>"
				+ "<form id='map_dir_marker_form' name='map_dir_form' action='map_directions.php' onsubmit='getDirections(this.from.value); return false;'>"
					+ "<input type='text' name='from' id='from'>"
					+ "<button class='button' type='submit'>GO</button>"
				+ "</form>"
				+ "</div>";

			google.maps.event.addListener(marker, 'click', function() {
				
				GoogleMap.lastOpenInfoWnd.setContent(markerText);
				GoogleMap.lastOpenInfoWnd.open(this.map,marker);
			});
		}
	    this.dealerMarkers[this.dealerMarkers.length] = marker;
	}
	
	// Locate and open dealer info.
	this.openDealerInfo = function(idx) {
		var marker = this.dealerMarkers[idx];
		google.maps.event.trigger(marker, "click");
	}
	
	// Adjust center and zoom level based on zip, distance, city, or state search.
	this.adjustCenterZoom = function(city, state, zip, dist) {
		var zoom = 10;
		if (zip && zip != null && zip != "" && zip != "null") { // zip
			if (dist) {
				if (dist > 50) zoom-=2;
				if (dist > 100) zoom--;
			}
			this.map.setCenter(this.dealerMarkers[0].getPosition());
			this.map.setZoom(zoom);
		}
		else { // city,state
			if (!city || city == null || city == "" || city == "null") {
				zoom = 6;
			} else {
				if (dist) {
					if (dist > 50) zoom-=2;
					if (dist > 100) zoom--;
				}
			}
		}
		this.map.setCenter(this.dealerMarkers[0].getPosition());
		this.map.setZoom(zoom);
		
	}
	
	// Display map with all markers.
	this.show = function(callback) {
		if(callback){
			setTimeout("window.print()", 300); // ie: wait til page is fully rendered before print
		}
	}
};




//Validate state. 
function validateState(frm) 
{
	var errorMsg = "";    
	if (!frm.state.value) {
		errorMsg += "Please select your state.\n";
	}
	if (errorMsg) { 
		dispErrorMsg(errorMsg); 
		return false;
	}
	return true;
}

//Validate state and zip. 
function validateZipAndState(frm)
{
	if (!frm.state.value && !frm.zip.value) {
		alert("Please enter a Zip Code or City/State.");
		return false;
	}
	else if (frm.zip.value) {
		return validateZip(frm);
	}
	return validateState(frm);
}

//Validate address.
function validateAddress(frm) 
{
	if (frm.from.value == "") {
		alert("Please enter an address.");
		return false;
	}
	return true;
}

//Display formatted error message.
function dispErrorMsg(errorMsg) {
	var line = "________________________________________________________\n\n";
	var head = "We're sorry.  We could not send your data as it was submitted.\n";
	alert(line + head + line + errorMsg);
	return false;
}

//Popup.
function popUp(url) {
	window.open(url, "_blank", "width=620, height=440, scrollbars=yes", false);
}

//Open non-Matrix dealer website.
function linkaway() {
var msg = "";
msg += "You are now leaving American Suzuki Motor Corporation's Auto Website, and entering an independent dealer site.\n";
msg += "\n";   
msg += "American Suzuki is not responsible for the content presented by any independent Suzuki dealer, including advertising claims, special offers, illustrations, names or endorsements.\n";
msg += "\n";   
msg += "Thank you for visiting our website. Please visit again soon.\n";
return confirm(msg);
}

//Display Customer 1st help.
function popupCust1stHelp(event, enable) {
	var box = $("#cust1st");
	if (enable) {
		// Fill box.
		if (box.html() == '') {
			var msg = "<div id='cust_1st_popup_close'><a onclick='popupCust1stHelp(null, false); return false;'>x</a></div>"
				+ "<div class='cust_1st_sales'><a></a></div>"
				+ "Dealers providing exceptional Sales Satisfaction"
				+ "<div class='cust_1st_service'><a></a></div>"
				+ "Dealers providing exceptional Service Satisfaction<br><br>"
				+ "Customers First dealers are those that have been recognized by Suzuki"
					+ " for providing exceptional customer satisfaction."
					+ " A dealer can be recognized for providing exceptional customer service with either"
					+ " their sales experience, service experience, or both.";
			box.append(msg);
		}

		// Vertically position and show.
		var yoffset;
		if ($.browser.msie) {
			yoffset = document.documentElement.scrollTop;
		}
		else {
			yoffset = window.pageYOffset;
		}
		var y = yoffset+event.clientY-440;
		//box.append("Y="+y+",yoffset="+yoffset+",screen.height="+screen.height+",event.clientY="+event.clientY);
		box.css("top", y);
		box.show();
	}
	else {
		box.hide();
	}
}
