var default_center_latitude = 37.500298613775;
var default_center_longitude = -80.62371611595155;
var default_zoom_level = 6;
var middle_zoom_level = 12;
var full_zoom_level = 15
		
//zoomOutControl adapted from TextualZoomControl example at http://code.google.com/apis/maps/documentation/controls.html
function zoomOutControl() {
}

zoomOutControl.prototype = new GControl();

zoomOutControl.prototype.initialize = function(map) {
	var container = document.createElement("div");

	var zoomOutDiv = document.createElement("div");
	this.setButtonStyle_(zoomOutDiv);
	container.appendChild(zoomOutDiv);
	zoomOutDiv.appendChild(document.createTextNode("Zoom Out"));
	GEvent.addDomListener(zoomOutDiv, "click", function() {
		if (map.getZoom() == full_zoom_level)
			map.setZoom(middle_zoom_level);
		else
			map.setCenter(new GLatLng(default_center_latitude, default_center_longitude), default_zoom_level);
	});

	map.getContainer().appendChild(container);
	this.buttonDiv = zoomOutDiv;
	return container;
}

zoomOutControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10));
}

zoomOutControl.prototype.setButtonStyle_ = function(button) {
	button.style.textDecoration = "none";
	button.style.color = "#454545";
	button.style.backgroundColor = "white";
	button.style.font = "small Arial";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "6em";
	button.style.cursor = "pointer";
	button.style.display = "none";
}

zoomOutControl.prototype.setVisible = function(visible) {
	if (visible == true)
		this.buttonDiv.style.display = "block";
	else
		this.buttonDiv.style.display = "none";
}
		
//zoomInControl adapted from TextualZoomControl example at http://code.google.com/apis/maps/documentation/controls.html
function zoomInControl() {
}

zoomInControl.prototype = new GControl();

zoomInControl.prototype.initialize = function(map) {
	var container = document.createElement("div");

	var zoomInDiv = document.createElement("div");
	this.setButtonStyle_(zoomInDiv);
	container.appendChild(zoomInDiv);
	zoomInDiv.appendChild(document.createTextNode("Zoom In"));
	GEvent.addDomListener(zoomInDiv, "click", function() {
		if (map.getZoom() == middle_zoom_level)
			map.setZoom(full_zoom_level);
		else
			map.setCenter(new GLatLng(default_center_latitude, default_center_longitude), middle_zoom_level);
	});

	map.getContainer().appendChild(container);
	this.buttonDiv = zoomInDiv;
	return container;
}

zoomInControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10));
}

zoomInControl.prototype.setButtonStyle_ = function(button) {
	button.style.textDecoration = "none";
	button.style.color = "#454545";
	button.style.backgroundColor = "white";
	button.style.font = "small Arial";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "6em";
	button.style.cursor = "pointer";
	button.style.display = "none";
}

zoomInControl.prototype.setVisible = function(visible) {
	if (visible == true)
		this.buttonDiv.style.display = "block";
	else
		this.buttonDiv.style.display = "none";
}


//seObject class - stores collection of data about a store
function seLocation(storenumber, storename, latitude, longitude, showroom) {
	this.m_storenumber = storenumber;
	this.m_storename = storename;
	this.m_latitude = latitude;
	this.m_longitude = longitude;
	this.m_showroom = showroom;
}

seLocation.prototype.getLat = function() {
	return this.m_latitude;
}

seLocation.prototype.getLng = function() {
	return this.m_longitude;
}

seLocation.prototype.getName = function() {
	return this.m_storename;
}

seLocation.prototype.getNumber = function() {
	return this.m_storenumber;
}

seLocation.prototype.hasShowroom = function() {
	return this.m_showroom;
}


//locationMarker class - extends functionality of GMarker to include the ability to store a location ID number

//helper function - http://ajaxcookbook.org/javascript-inheritance/
function inherit(subclass, superclass) {
    var c = function() {};
    c.prototype = superclass.prototype;
    subclass.prototype = new c();
}

function LocationMarker(latlng, opts) {
    GMarker.call(this, latlng, opts);
}

inherit(LocationMarker, GMarker);

LocationMarker.prototype.getID = function() {
	return this.m_locationID;
}

LocationMarker.prototype.setID = function(id) {
	this.m_locationID = id;
}


//functions

function initialize() {
	if (GBrowserIsCompatible()) {
		//create map object, set its center to approximately the center of the bounding box of our locations
		map = new GMap2(document.getElementById("map_canvas"));
		//map.disableDragging();
		map.setCenter(new GLatLng(default_center_latitude, default_center_longitude), default_zoom_level);
		
		
		//ADD ALL LOCATION MARKERS
		if (selected_location == null) {
			//make corporate location marker
			var corporateIcon = new GIcon();
			corporateIcon.iconSize = new GSize(18, 18);
			corporateIcon.shadowSize = new GSize(31, 22);
			corporateIcon.iconAnchor = new GPoint(9, 9);
			corporateIcon.image = "/images/mapping/redstar-big.png";
			corporateIcon.shadow = "/images/mapping/starshadow-big.png";
			
			addMarkerAt(map, 38.42711792714856, -82.42327451705933, corporateIcon, 1, locations[1].getName());
			
			//make markers for locations with showrooms
			var showroomIcon = new GIcon();
			showroomIcon.iconSize = new GSize(14, 14);
			showroomIcon.shadowSize = new GSize(24, 17);
			showroomIcon.iconAnchor = new GPoint(7, 7);
			showroomIcon.image = "/images/mapping/bluestar-med.png";
			showroomIcon.shadow = "/images/mapping/starshadow-med.png";
			
			for (i = 2; i < locations.length; i++) {
				if (locations[i].hasShowroom())
					addMarkerAt(map, locations[i].getLat(), locations[i].getLng(), showroomIcon, i, locations[i].getName());
			}
			
			//make non-showroom location markers
			var nsIcon = new GIcon();
			nsIcon.iconSize = new GSize(14, 14);
			nsIcon.shadowSize = new GSize(24, 17);
			nsIcon.iconAnchor = new GPoint(7, 7);
			nsIcon.image = "/images/mapping/greenstar-med.png";
			nsIcon.shadow = "/images/mapping/starshadow-med.png";
			
			for (i = 2; i < locations.length; i++) {
				if (! locations[i].hasShowroom())
					addMarkerAt(map, locations[i].getLat(), locations[i].getLng(), nsIcon, i, locations[i].getName());
			}
		}
		//SELECTED LOCATION MARKER
		else {
			if (selected_location == 1) {
				var corporateIcon = new GIcon();
				corporateIcon.iconSize = new GSize(18, 18);
				corporateIcon.shadowSize = new GSize(31, 22);
				corporateIcon.iconAnchor = new GPoint(9, 9);
				corporateIcon.image = "/images/mapping/star-corporate.png";
				corporateIcon.shadow = "/images/mapping/starshadow-big.png";
				
				addMarkerAt(map, 38.42711792714856, -82.42327451705933, corporateIcon, 1, locations[1].getName());
			}
			else {
				//make markers for locations with showrooms
				var locationIcon = new GIcon();
				locationIcon.iconSize = new GSize(14, 14);
				locationIcon.shadowSize = new GSize(24, 17);
				locationIcon.iconAnchor = new GPoint(7, 7);
				if (locations[selected_location].hasShowroom())
					locationIcon.image = "/images/mapping/star-store.png";
				else
					locationIcon.image = "/images/mapping/star-store.png";
				locationIcon.shadow = "/images/mapping/starshadow-med.png";
				
				addMarkerAt(map, locations[selected_location].getLat(), locations[selected_location].getLng(), locationIcon, selected_location, locations[selected_location].getName());
			}
		}
		
		//add listener to make map zoom in on any marker that gets clicked
		/*GEvent.addListener(map, "click", function(overlay, point) {
			if (location_loaded != overlay.getID()) {
				loadLocationInfo(overlay.getID());
				location_loaded = overlay.getID();
			}
			
			if (map.getZoom() == default_zoom_level)
				map.setCenter(overlay.getLatLng(), middle_zoom_level);
			else
				map.setCenter(overlay.getLatLng(), full_zoom_level);
		});*/
		
		//zoom in button is only visible when zoomed out
		var zoomIn = new zoomInControl();
		map.addControl(zoomIn);
		
		GEvent.addListener(map, "zoomend", function() {
			if (map.getZoom() == full_zoom_level)
				zoomIn.setVisible(false);
			else
				zoomIn.setVisible(true);
		});

		var zoomOut = new zoomOutControl();
		map.addControl(zoomOut);

		//zoom out button is only visible when zoomed in
		GEvent.addListener(map, "zoomend", function() {
			if (map.getZoom() == default_zoom_level || map.getZoom() == middle_zoom_level)
				zoomOut.setVisible(false);
			else
				zoomOut.setVisible(true);
		});
		
		if (selected_location != null) {
			map.setCenter(new GLatLng(locations[selected_location].getLat(), locations[selected_location].getLng()), full_zoom_level);
			zoomIn.setVisible(true);
		}
	}
	else {
		document.getElementById("map_canvas").style.backgroundImage = "url('/images/mapping/static_map.gif')";
	}
}

function addMarkerAt(map, latitude, longitude, markerIcon, id, name) {
	var options = { icon:markerIcon , title:name };
	var marker = new LocationMarker(new GLatLng(latitude, longitude), options);
	marker.setID(id);
	map.addOverlay(marker);
}

function loadLocationInfo(id) {
	ajaxObjZoom = getAjaxObject();
	
	ajaxObjZoom.onreadystatechange = function() {
		if (ajaxObjZoom.readyState < 4)
			document.getElementById("locationinfo").innerHTML = '<div class="loadingmessage">Loading location data...</div>';
		if (ajaxObjZoom.readyState == 4) {
			document.getElementById("locationinfo").innerHTML = ajaxObjZoom.responseText;
		}
	}
	
	var scripturl = "/scripts/ajax/mapping_locationdetails.asp";

	//send request
	ajaxObjZoom.open("GET", scripturl + "?ms=" + new Date().getTime() + "&locid=" + id);
	ajaxObjZoom.send(null);
}

function zoomToLocation(lat, lng, id) {
	loadLocationInfo(id);
	location_loaded = id;
	map.setCenter(new GLatLng(lat, lng), full_zoom_level);
}

function find_location() {
	document.getElementById("locationsubmitinput").disabled = true;
	document.getElementById("locationsubmitinput").value = "Searching...";
	
	showroom_only = document.geocodingform["showroomonly"].checked;
	
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(document.geocodingform["address"].value + ", " + document.geocodingform["city"].value + ", " +
		document.geocodingform["state"].value + " " + document.geocodingform["zip"].value, select_locations);
}

function select_locations(response) {
	document.getElementById("locationsubmitinput").disabled = false;
	document.getElementById("locationsubmitinput").value = "Find Location";
	
	if ((response) == null) {
		alert("The address you entered cannot be located by the Google Maps service. \nPlease check the address for " +
			"accuracy.");
		return false;
	}
	
	var closestLocs = [];
	closestLocs[0] = new Array(-1, 9999999999);
	closestLocs[1] = new Array(-1, 9999999999);
	closestLocs[2] = new Array(-1, 9999999999);

	for (i = 1; i < locations.length; i++) {
		var dist = getDistanceBetween(response.lat(), response.lng(), locations[i].getLat(), locations[i].getLng());
		if (!showroom_only || locations[i].hasShowroom()) {
			if (closestLocs[0] == null || dist < closestLocs[0][1])
				closestLocs[0] = [i, dist];
			else if (closestLocs[1] == null || dist < closestLocs[1][1])
				closestLocs[1] = [i, dist];
			else if (closestLocs[2] == null || dist < closestLocs[2][1])
				closestLocs[2] = [i, dist];
		}
	}
	
	ajaxObjSelectLoc = getAjaxObject();
	
	ajaxObjSelectLoc.onreadystatechange = function() {
		if (ajaxObjSelectLoc.readyState < 4)
			document.getElementById("locationinfo").innerHTML = '<div class="loadingmessage">Loading closest locations...</div>';
		if (ajaxObjSelectLoc.readyState == 4) {
			document.getElementById("locationinfo").innerHTML = ajaxObjSelectLoc.responseText;
		}
	}
	
	var scripturl = "/scripts/ajax/mapping_closestlocs.asp";

	var post_string = build_loc_post(closestLocs[0], closestLocs[1], closestLocs[2]);
	
	current_address = document.geocodingform["address"].value;
	current_city = document.geocodingform["city"].value;
	current_state = document.geocodingform["state"].value;
	current_zip = document.geocodingform["zip"].value;

	//send request
	ajaxObjSelectLoc.open("POST", scripturl + "?ms=" + new Date().getTime());
	ajaxObjSelectLoc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajaxObjSelectLoc.send(post_string);
}

function build_loc_post(location1, location2, location3) {
	var post_string =  'loc1id=' + escape(locations[location1[0]].getNumber()) + '&';
        post_string += 'loc1name=' + escape(locations[location1[0]].getName()) + '&';
        post_string += 'loc1lat=' + escape(locations[location1[0]].getLat()) + '&';
	   post_string += 'loc1lng=' + escape(locations[location1[0]].getLng()) + '&';
	   post_string += 'loc1showroom=' + escape(locations[location1[0]].hasShowroom() ? 'y' : 'n') + '&';
	   post_string += 'loc1dist=' + escape(location1[1]) + '&';
	   post_string += 'loc2id=' + escape(locations[location2[0]].getNumber()) + '&';
        post_string += 'loc2name=' + escape(locations[location2[0]].getName()) + '&';
        post_string += 'loc2lat=' + escape(locations[location2[0]].getLat()) + '&';
	   post_string += 'loc2lng=' + escape(locations[location2[0]].getLng()) + '&';
	   post_string += 'loc2showroom=' + escape(locations[location2[0]].hasShowroom() ? 'y' : 'n') + '&';
	   post_string += 'loc2dist=' + escape(location2[1]) + '&';
	   post_string += 'loc3id=' + escape(locations[location3[0]].getNumber()) + '&';
        post_string += 'loc3name=' + escape(locations[location3[0]].getName()) + '&';
        post_string += 'loc3lat=' + escape(locations[location3[0]].getLat()) + '&';
	   post_string += 'loc3lng=' + escape(locations[location3[0]].getLng()) + '&';
	   post_string += 'loc3showroom=' + escape(locations[location3[0]].hasShowroom() ? 'y' : 'n') + '&';
	   post_string += 'loc3dist=' + escape(location3[1]) + '&';
	   post_string += 'address=' + escape(document.geocodingform["address"].value + ", " +
		document.geocodingform["city"].value + ", " + document.geocodingform["state"].value + " " +
		document.geocodingform["zip"].value);
	
	return post_string;
}

function getDistanceBetween(lat1, lng1, lat2, lng2) {
	//haversine formula obtained from http://www.movable-type.co.uk/scripts/latlong.html
	var R = 6371; // km
	var dLat = convert_degrees_to_rad(lat2-lat1);
	var dLng = convert_degrees_to_rad(lng2-lng1); 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	        Math.cos(convert_degrees_to_rad(lat1)) * Math.cos(convert_degrees_to_rad(lat2)) * 
	        Math.sin(dLng/2) * Math.sin(dLng/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;
	
	return convert_km_to_mi(d);
}

function convert_degrees_to_rad(deg) {
	return (deg / 360) * 2 * Math.PI;
}

function convert_km_to_mi(distance) {
	return distance * 0.621369949495;
}

function load_default_info() {
	ajaxObjLoadDefault = getAjaxObject();
	
	ajaxObjLoadDefault.onreadystatechange = function() {
		if (ajaxObjLoadDefault.readyState < 4)
			document.getElementById("locationinfo").innerHTML = '<div class="loadingmessage">Loading...</div>';
		if (ajaxObjLoadDefault.readyState == 4) {
			document.getElementById("locationinfo").innerHTML = ajaxObjLoadDefault.responseText;
			
			if (current_address != "")
				document.geocodingform["address"].value = current_address;
			if (current_city != "")
				document.geocodingform["city"].value = current_city;
			if (current_state != "")
				document.geocodingform["state"].value = current_state;
			if (current_zip != "")
				document.geocodingform["zip"].value = current_zip;
			
			location_loaded = 0;
		}
	}
	
	var scripturl = "/scripts/ajax/mapping_defaultinfo.asp";

	//send request
	ajaxObjLoadDefault.open("GET", scripturl + "?ms=" + new Date().getTime());
	ajaxObjLoadDefault.send(null);
}

var locations = [];
locations[1] = new seLocation('01', "Huntington", 38.42711792714856, -82.42327451705933, true);
locations[2] = new seLocation('02', "Dunbar", 38.3616640618729, -81.7395257949829, true);
locations[3] = new seLocation('03', "Parkersburg", 39.2358597773385, -81.5236830711365, true);
locations[4] = new seLocation('04', "Beckley", 37.8134456327011, -81.1721634864807, true);
locations[5] = new seLocation('05', "Turkey Creek", 37.6685353842871, -82.2929191589355, false);
locations[6] = new seLocation('06', "Logan", 37.8272600573291, -81.9678139686584, false);
locations[7] = new seLocation('07', "Ashland", 38.4741031872005, -82.6273584365845, false);
locations[8] = new seLocation('08', "Pikeville", 37.4432110486493, -82.5243830680847, true);
locations[9] = new seLocation('09', "Lancaster", 39.7169420792301, -82.6061797142029, true);
locations[10] = new seLocation(10, "Middlesboro", 36.6083108037111, -83.7059497833252, false);
locations[11] = new seLocation(11, "Bluefield", 37.2659247207462, -81.2341547012329, true);
locations[12] = new seLocation(12, "Dunbar - SESCO", 38.3610583538901, -81.7396545410156, false);
locations[13] = new seLocation(13, "Clarksburg", 39.2780286904744, -80.3424382209778, true);
locations[14] = new seLocation(14, "New Boston", 38.7504018002288, -82.9391598701477, false);
locations[15] = new seLocation(15, "Chillicothe", 39.361776, -83.001366, false);
locations[16] = new seLocation(16, "Christiansburg", 37.1649335836855, -80.4181623458862, true);
locations[17] = new seLocation(17, "Morgantown", 39.653474, -79.969037, false);
locations[18] = new seLocation(18, "Winston-Salem", 36.0736957228909, -80.2565860748291, false);
locations[19] = new seLocation(19, "Mt. Airy", 36.5011157938982, -80.6297564506531, false);
locations[20] = new seLocation(20, "Greensboro", 36.0590391977098, -79.8338055610657, false);
locations[21] = new seLocation(21, "Lewisburg", 37.8355771277735, -80.41410148143768, false);
locations[22] = new seLocation(22, "Covington", 37.7941519636351, -79.9951028823853, false);
locations[23] = new seLocation(23, "Maysville", 38.6352935659889, -83.8116502761841, false);
locations[24] = new seLocation(24, "Richmond", 37.5163808738478, -77.435781955719, true);
locations[25] = new seLocation(25, "Athens", 39.3313929520601, -82.1203136444092, false);
locations[26] = new seLocation(26, "Roanoke", 37.2827605032766, -79.9866485595703, false);
locations[27] = new seLocation(27, "Princeton", 37.3669852451697, -81.0997653007507, false);
locations[28] = new seLocation(28, "Salisbury", 35.657714680993, -80.4864621162415, false);
locations[29] = new seLocation(29, "Concord", 35.4304105840201, -80.6078267097473, true);
locations[30] = new seLocation(30, "Statesville", 35.7803777160538, -80.9034061431885, true);
locations[31] = new seLocation(31, "Troutman", 35.680393949982, -80.8569931983948, false);
locations[32] = new seLocation(32, "Portsmouth - CIS", 38.7390717048119, -82.9781270027161, false);
locations[33] = new seLocation(33, "Chillicothe - CIS", 39.3380813683882, -82.9523134231567, false);
locations[34] = new seLocation(34, "Wytheville", 36.9550017628925, -81.0793375968933, false);
locations[35] = new seLocation(35, "Goldsboro", 35.3734620908988, -78.0051183700562, false);
locations[36] = new seLocation(36, "Raleigh", 35.8332625339134, -78.6082291603088, false);
locations[37] = new seLocation(37, "Kinston", 35.2836551483198, -77.5559663772583, false);
locations[38] = new seLocation(38, "Roanoke Rapids", 36.4410154493229, -77.6499080657959, false);
locations[39] = new seLocation(39, "Cary", 35.793780622146, -78.7700200080872, false);
locations[40] = new seLocation(40, "Durham", 35.9698791944502, -78.8768792152405, false);
locations[41] = new seLocation(41, "Marion", 37.738956, -88.942909, false);
locations[42] = new seLocation(42, "Asheville", 35.451441, -82.523117, false);

var map;
var current_address = "";
var current_city = "";
var current_state = "";
var current_zip = "";

var showroom_only = false;

var location_loaded = 0;

window.onload = initialize;
window.onunload = GUnload;
