var INITIAL_ZOOM_LEVEL = 2;
var map;
var mapDiv;
var mfgSelector;
var hoverMsg;
var loadingMsgText;
var request;
var infoRequest;

var infoWindowMarker;
var infoWindowMarkerPoint;
var allMarkers = new Array();

var count = 0;

window.onload = pc_init;

// All javascript body onload functions must be named pc_init
// to allow functionality when user is logged in
function pc_init() {
	if (GBrowserIsCompatible()) {
		request = GXmlHttp.create();
		infoRequest = GXmlHttp.create();
				
		mapDiv = document.getElementById('map');
		mapDiv.style.width = "800px";
		mapDiv.style.height = "575px";
		mapDiv.style.display = "block";
	
		loadingMsgText = document.createTextNode('Initializing...');
		var loadingMsgDiv = document.getElementById('loadingMsg');
		while (loadingMsgDiv.hasChildNodes()) {
			loadingMsgDiv.removeChild(loadingMsgDiv.firstChild);
		}
		loadingMsgDiv.appendChild(loadingMsgText);
		
		initMapState();

		hideHoverMessage();
		
		getDealerInfo();
	}
	else if (window.location.href.indexOf('noncompat') < 0) {
		window.location += "?noncompat=1";
	}
}

function initMapState() {
	map = new GMap(mapDiv);
	
	var initialCenter = new GLatLng(0, 0);
	var initialZoom   = INITIAL_ZOOM_LEVEL;
	
	var attLat = mapDiv.getAttribute('LAT');
	var attLng = mapDiv.getAttribute('LNG');
	var attArea= mapDiv.getAttribute('AREA');
	
	if (attLat != null && attLng != null && attArea != null && attArea > 0) {
		initialCenter = new  GLatLng(attLat, attLng);
		initialZoom = getZoomLevelForCountrySize(Number(attArea));
	}
	
	map.setCenter(initialCenter, initialZoom);
	
	GEvent.addListener(map, 'moveend', getDealerInfo);
	GEvent.addListener(map, 'infowindowclose', function() {
		infoWindowMarker = null;
		infoWindowMarkerPoint = null;
	});
	
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	
	markers = new Array();
}

function showNoVisibleDealersMessage(n) {
	if (n == null) {
		var html =  "<h1>No Dealer Locations found</h1>";
	}
	else {
		var html = "<h1>"+n+" Dealer Locations found</h1>";
	}
	html += "To see more move the map.";
	showHoverMessage(html);
}

function showHoverMessage(html) {
	hoverMsg = document.createElement('DIV');
	var msgPadding = 50;
	hoverMsg.id = "hoverMsg";
	hoverMsg.innerHTML = html;
	hoverMsg.style.position = "absolute";
	hoverMsg.style.zIndex = 10;
	
	mapDiv.appendChild(hoverMsg);
	
	hoverMsg.style.left = (mapDiv.offsetWidth/2 - hoverMsg.offsetWidth/2) + "px";
	
	hoverMsg.style.bottom = "30px"
	// Align in middle of screen - OLD
	//hoverMsg.style.top = (mapDiv.offsetHeight/2 - hoverMsg.offsetHeight/2) + "px";
	
	hoverMsg.onclick = hideHoverMessage;
}

function hideHoverMessage() {
	if (hoverMsg != null && hoverMsg.parentNode != null) {
		hoverMsg.parentNode.removeChild(hoverMsg);
	}
}

function getDealerInfo() {
	request.abort();
	infoRequest.abort();
		
	loadingMsgText.nodeValue = 'Loading Dealer locations...';
	hideHoverMessage();
	var mapBounds = map.getBounds();

	var url = '_dealer_xml_gen.cfm?'
		+ 'swLng='+mapBounds.getSouthWest().lng()
		+'&neLng='+mapBounds.getNorthEast().lng()
		+'&swLat='+mapBounds.getSouthWest().lat()
		+'&neLat='+mapBounds.getNorthEast().lat()
		+"&c="+(++count);
	request.open("GET",
		url,
		true);
	request.onreadystatechange = updateDealerIcons;
	request.send(null);
}

function updateDealerIcons() {
	if (request.readyState == 4) {
		var xmlDoc = request.responseXML;
		if (xmlDoc == null || typeof xmlDoc == 'undefined') {
			return;
		}
		var dealerNodes = xmlDoc.getElementsByTagName('dealer');
		var recordNode = xmlDoc.getElementsByTagName('records')[0];
		var totalDealers = recordNode.getAttribute("total");
		var shownDealers = dealerNodes.length;
		
		while (allMarkers.length > 0) {
			var m = allMarkers.pop();
			if (infoWindowMarker == null || m != infoWindowMarker) {
				map.removeOverlay(m);
			}
		}
		
		if (infoWindowMarker != null) allMarkers.push(infoWindowMarker);
		if (recordNode.getAttribute('error') == "FALSE") {
			for (i = 0; i < dealerNodes.length; i++) {
				var latitude = dealerNodes[i].getElementsByTagName('latitude')[0].firstChild.nodeValue;
				var longitude = dealerNodes[i].getElementsByTagName('longitude')[0].firstChild.nodeValue;
				if (typeof infoWindowMarkerPoint == "undefined" || infoWindowMarkerPoint == null ||
					(infoWindowMarkerPoint.x != longitude && infoWindowMarkerPoint.y != latitude))
				{
					var type = dealerNodes[i].getAttribute("type");
					var dlrMarker = createDealerMarker(latitude, longitude, xmlDoc, dealerNodes[i].getAttribute("id"), type);
					if (typeof dlrMarker != "null") {
						allMarkers.push(dlrMarker);
						map.addOverlay(dlrMarker);
					}
				}
			}
			if (shownDealers == totalDealers) {
				loadingMsgText.nodeValue = ((totalDealers==0) ? 'No' : totalDealers) + ' Dealer Location' + (totalDealers==1?'':'s');
				if (shownDealers == 0) {
					showNoVisibleDealersMessage();
				}
			}
			else {
				loadingMsgText.nodeValue = totalDealers + ' Dealer Location' + (totalDealers==1?"":"s");
				showNoVisibleDealersMessage(totalDealers);
			}
		}
		else {
			loadingMsgText.nodeValue = "Error: "+recordNode.getAttribute('message');
		}
	}
}

function createDealerMarker(lat, lng, xmlDoc, id, type) {
	var coords = new GLatLng(lat, lng);
	
	var icon = getDealerIconForType(type);
	var html = getInfoWindowHtmlForDealer(xmlDoc, id);
	var marker = new GMarker(coords, icon);
	
	if (html == "") return null;
	
	GEvent.addListener(marker, 'click', function() {
		// If a user clicks another marker while an info window is already open,
		// Then GMaps will open the new window, then close the old one. This means
		// that the 'infowindowclose' event fires immediately after this one, which
		// has the effect of clearing the infoWindowMarker variables. By closing any
		// open window first, we avoid that problem
		map.closeInfoWindow();
		infoWindowMarker = marker;
		infoWindowMarkerPoint = coords;
		marker.openInfoWindowHtml(html);
	});
	
	return marker;
}

function getDealerIconForType(type) {
	if (type == "Distributor") {
		var icon = new GIcon(G_DEFAULT_ICON);
		icon.image = "images/maps/redmarker.png";
		//icon.iconSize = new GSize(25,45);
		//icon.shadow  = "images/maps/shadow50big.png";
		//icon.shadowSize = new GSize(45,45);
		//icon.transparent = "images/maps/bigredmarkertrans.png";
		//icon.iconAnchor = new GPoint(13,44);
		//icon.printImage = "images/maps/bigredmarkerprint.gif";
		//icon.mozPrintImage = icon.printImage;
		return icon;
	}
	else if (type == "Online") {
		var icon = new GIcon(G_DEFAULT_ICON);
		icon.image = "images/maps/greenmarker.png";
		//icon.iconSize = new GSize(23,37);
		//icon.shadow  = "images/maps/shadow50med.png";
		//icon.shadowSize = new GSize(42,37);
		//icon.transparent = "images/maps/medgreenmarkertrans.png";
		//icon.iconAnchor = new GPoint(12,36);
		//icon.printImage = "images/maps/medgreenmarkerprint.gif";
		//icon.mozPrintImage = icon.printImage;
		return icon;
	}
	else {
		var icon = new GIcon(G_DEFAULT_ICON);
		icon.image = "images/maps/yellowmarker.png";
		return icon;
	}
}

function getInfoWindowHtmlForDealer(doc, dealer_id) {
	var dealerNode = null;
	var allDealers = doc.getElementsByTagName('dealer');
	for (var i = 0; i < allDealers.length; i++) {
		if (allDealers[i].getAttribute('id') == dealer_id) {
			dealerNode = allDealers[i];
			break;
		}
	}
	
	if (dealerNode == null) {
		return "";
	}
	
	var html = "";
	var url = dealerNode.getAttribute('url');
	var logo_filename = dealerNode.getAttribute('logo');
	
	html += '<div style="color:black;">';
	
	html += '<div class="dealerName">';
	if (url.length > 0) {
		html += '<A HREF="'+url+'" TARGET="_blank" TITLE="Visit this seller&rsquo;s web site"><FONT COLOR="black">'+dealerNode.getAttribute("name").bold()+'</FONT></A>';
	}
	else {
		html += '<b>'+dealerNode.getAttribute("name")+'</b>';
	}
	html += "</div>"

	if (dealerNode.getAttribute("type") == 'Online') {
		html += "<div>Online Sales Only</div>";
	}
	else {
		html += '<div>'+dealerNode.getAttribute("address")+'</div>';
		
		//var phone = dealerNode.getAttribute("phone");
		//if (phone.length > 0) {
		//	html += "<div>"+phone+"</div>";
		//}
			
		//var email = dealerNode.getAttribute("email");
		//if (email.length > 0) {
		//	html += '<div><a href="mailto:'+email+'">'+email+'</a></div>';
		//}
		
		//html += '<DIV CLASS="profileLink"><A HREF="dealer_edit.cfm?dealer_id='+dealer_id+'" TITLE="View this seller&rsquo;s profile">Edit Dealer</a></div>';
	}
	if (logo_filename.length > 0) {
		html += '<BR><A HREF="'+url+'" TARGET="_blank" TITLE="Visit this seller&rsquo;s web site"><IMG SRC="/images/dealers/'+logo_filename+'" BORDER="0"></A>';
	}
	
	html += '</div>';
	
	return '<div style="white-space:nowrap;">'+html+'</div>';
}
