var map;
var map2;
var zoom_level = 6;
var myOptions = {
		zoom: zoom_level,
		mapTypeId: google.maps.MapTypeId.ROADMAP
};
var state_code;
var email_lat;
var email_lng;
var bus_centerID;
var email_type = "default";
var country;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay;
var geoloc_timeout;
var gsvars = getVars();

function findalocation() {
	geoloc_timeout = setTimeout(handleNoGeolocation, 1000);
	
	if (geo_position_js.init()) {
		geo_position_js.getCurrentPosition(defaultMap, handleNoGeolocation);
	} else {
		handleNoGeolocation();
	}
}

function webregion() {
	geoloc_timeout = setTimeout(handleNoGeolocation, 1000);
	
	if (!state_code) {
		if (geo_position_js.init()) {
			geo_position_js.getCurrentPosition(webregionMap, handleNoGeolocation);
		} else {
			handleNoGeolocation();
		}
	} else {
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({'address': state_code}, function (results, status){
			if (status == google.maps.GeocoderStatus.OK) {
				var position = {
					coords: {
						latitude: results[0].geometry.location.lat(),
						longitude: results[0].geometry.location.lng()
					}
				}
				webregionMap(position);
			} else {
				findalocation();
			}
		});
	}
}

function webregionMap(position) {
	clearTimeout(geoloc_timeout);
	var state_name;
	email_type = "state";
	email_lat = position.coords.latitude;
	email_lng = position.coords.longitude;
	if (!state_code) {
		state_code = position.address.region;
		state_name = position.address.region;
	} else {
		state_name = state_code;
	}
	$.ajax({
		type: "POST",
		url: "/ajax/getcenterswebregion",
		data:"state_name="+state_name,
		dataType: 'json',
		complete: function(data){
			if (data) {
				//alert(data.responseText);
				var bus_centers = jQuery.parseJSON(data.responseText);
			}
			showWebRegionMap(position, bus_centers);
			$("#location_title2")[0].innerHTML = state_name;
			$("#state_list_container").children().css("color", "#fff");
			$("div[state_name='"+state_code+"']").css("color", "#F69F2E");
		}
	});
}

function defaultMap(position) {
	clearTimeout(geoloc_timeout);
	// These two global variables are used when an email is sent.
	email_lat = position.coords.latitude;
	email_lng = position.coords.longitude;
	$.ajax({
		type: "POST",
		url: "/ajax/getcenters",
		data:"search_miles=50&lat="+position.coords.latitude+"&lng="+position.coords.longitude,
		dataType: 'json',
		complete: function(data){
			if (data) {
				var bus_centers = jQuery.parseJSON(data.responseText);
			}
			showMap(position, bus_centers);
		}
	});
}

function showMap(position, bus_centers) {
	map = new google.maps.Map($("#map_canvas")[0], myOptions);
	var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	var markers = new Array();
	var infowindow;
	var infowindow_text;
	var letter_key = 0;
	var icon_path;
	var centers_all = "";
	var bounds = new google.maps.LatLngBounds();

	if ($("#all_centers_container")[0]) {
		$("#all_centers_container")[0].innerHTML = "";
	}
	
	for (var i in bus_centers) {
		marker_latlng = new google.maps.LatLng(bus_centers[i].latitude, bus_centers[i].longitude);
		markers[i] = new google.maps.Marker({
			position: marker_latlng,
			map: map,
			title: "AlphaGraphics "+bus_centers[i].centerWebName
		});
		bus_centers[i].latlng = marker_latlng;
		
		icon_path = getIconPath(letter_key);
		letter_key++;
		markers[i].setIcon(icon_path);
		markers[i].setMap(map);
		bounds.extend(marker_latlng);
		
		infowindow_text  = "<div class='bus_info_container'>";
		infowindow_text += "<div class='bus_center_title'><a href='/"+gsvars[110]+"/"+bus_centers[i].base+"'>AlphaGraphics "+bus_centers[i].centerWebName+"</a></div>";
		infowindow_text += "<div class='bus_center_text'>"+bus_centers[i].address1 + ", " + bus_centers[i].address2+"</div>";
		infowindow_text += "<div class='bus_center_text'>"+bus_centers[i].city + ", " + bus_centers[i].abbreviation + " " + bus_centers[i].zip+"</div>";
		infowindow_text += "<div class='bus_center_email'><a href='mailto:"+bus_centers[i].websiteEmail+"'>"+gsvars[73]+"</a></div>";
		infowindow_text += "<div class='bus_center_directions' onclick='startDirections("+bus_centers[i].centerID+");'>"+gsvars[72]+"</div>";
		infowindow_text += "</div>";
		
		markers[i].infowindow = infowindow_text;
		infowindow = new google.maps.InfoWindow();
		google.maps.event.addListener(markers[i], 'click', function() {
			infowindow.setContent(this.infowindow);
			infowindow.open(map,this);
		});
		
		bus_center_container = document.createElement("div");
		bus_center_container.className = "bus_center_container";

		bus_center_marker = document.createElement("div");
		bus_center_marker.className = "bus_center_marker";
		
		bus_info_container = document.createElement("div");
		bus_info_container.className = "bus_info_container";
		
		bus_center_title = document.createElement("div");
		bus_center_title_a = document.createElement("a");
		bus_center_title_a.href = "/"+gsvars[110]+"/"+bus_centers[i].base;
		bus_center_title.className = "bus_center_title";
		bus_center_title_a.innerHTML = "AlphaGraphics "+bus_centers[i].centerWebName;
		bus_center_title.appendChild(bus_center_title_a);
		
		bus_center_text1 = document.createElement("div");
		bus_center_text1.className = "bus_center_text";
		bus_center_text1.innerHTML = bus_centers[i].address1 + ", " + bus_centers[i].address2;
		
		bus_center_text2 = document.createElement("div");
		bus_center_text2.className = "bus_center_text";
		bus_center_text2.innerHTML = bus_centers[i].city + ", " + bus_centers[i].abbreviation + " " + bus_centers[i].zip;
		
		bus_center_text3 = document.createElement("div");
		bus_center_text3.className = "bus_center_text";
		bus_center_text3.innerHTML = bus_centers[i].websitePhoneNumber;

		bus_center_email = document.createElement("div");
		bus_center_email.className = "bus_center_email";
		
		bus_center_email_link = document.createElement("a");
		bus_center_email_link.href = "mailto:"+bus_centers[i].websiteEmail;
		bus_center_email_link.innerHTML = gsvars[73];
		
		bus_center_directions = document.createElement("div");
		bus_center_directions.className = "bus_center_directions";
		bus_center_directions.innerHTML = gsvars[72];
		bus_center_directions.latlng = bus_centers[i].latlng; 
		bus_center_directions.centerID = bus_centers[i].centerID;
		bus_center_directions.onclick = function(event) {
			startDirections(this.centerID);	
		}		
		
		bus_center_img = document.createElement("img");
		bus_center_img.src = icon_path;
		bus_center_img.infowindow = infowindow_text;
		bus_center_img.marker = markers[i];
		bus_center_img.latlng = bus_centers[i].latlng;
		bus_center_img.onclick = function() {
			infowindow.setContent(this.infowindow);
			infowindow.open(map,this.marker);
		}
		
		$("#all_centers_container")[0].appendChild(bus_center_container);
			bus_center_container.appendChild(bus_center_marker);
				bus_center_marker.appendChild(bus_center_img);
			bus_center_container.appendChild(bus_info_container);
				bus_info_container.appendChild(bus_center_title);
				bus_info_container.appendChild(bus_center_text1);
				bus_info_container.appendChild(bus_center_text2);
				bus_info_container.appendChild(bus_center_text3);
				bus_info_container.appendChild(bus_center_email);
					bus_center_email.appendChild(bus_center_email_link);
				bus_info_container.appendChild(bus_center_directions);
	}
	
	if (markers.length == 0) {
		map.setCenter(latlng);
	} else {
		map.fitBounds(bounds);
		var listener = google.maps.event.addListener(map, "idle", function() {
//			if (map.getZoom() > 6) {
//				map.setZoom(6);
//			}
			google.maps.event.removeListener(listener);
		});
	}
}

function showWebRegionMap(position, bus_centers) {
	map = new google.maps.Map($("#map_canvas")[0], myOptions);
	var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	var markers = new Array();
	var infowindow;
	var letter_key = 0;
	var icon_path;
	var centers_all = "";
	var bounds = new google.maps.LatLngBounds();
	var webregion_bus_centers = new Array();
	var sorted_array = new Array();

	if ($("#all_centers_container")[0]) {
		$("#all_centers_container")[0].innerHTML = "";
	}
	
	for (var i in bus_centers) {
		marker_latlng = new google.maps.LatLng(bus_centers[i].latitude, bus_centers[i].longitude);
		markers[i] = new google.maps.Marker({
			position: marker_latlng,
			map: map,
			title: "AlphaGraphics "+bus_centers[i].centerWebName
		});
		
		icon_path = getIconPath(letter_key);
		letter_key++;
		markers[i].setIcon(icon_path);
		markers[i].setMap(map);
		bounds.extend(marker_latlng);
		
		infowindow_text = "<div class='bus_info_container'>";
		infowindow_text += "<div class='bus_center_title'><a href='/"+gsvars[110]+"/"+bus_centers[i].base+"'>AlphaGraphics "+bus_centers[i].centerWebName+"</a></div>";
		infowindow_text += "<div class='bus_center_text'>"+bus_centers[i].address1 + ", " + bus_centers[i].address2+"</div>";
		infowindow_text += "<div class='bus_center_text'>"+bus_centers[i].city + ", " + bus_centers[i].abbreviation + " " + bus_centers[i].zip+"</div>";
		infowindow_text += "<div class='bus_center_email'><a href='mailto:"+bus_centers[i].websiteEmail+"'>Click here to email us</a></div>";
		infowindow_text += "<div class='bus_center_directions' onclick='startDirections("+bus_centers[i].centerID+");'>Directions</div>";
		infowindow_text += "</div>";

		markers[i].infowindow = infowindow_text;
		infowindow = new google.maps.InfoWindow();
		google.maps.event.addListener(markers[i], 'click', function() {
			infowindow.setContent(this.infowindow);
			infowindow.open(map,this);
		});
		bus_centers[i].icon_path = icon_path;
		bus_centers[i].marker = markers[i];
		bus_centers[i].latlng = marker_latlng;
		wrbc_key = bus_centers[i].webregion_name;
		if (!webregion_bus_centers[wrbc_key]) {
			webregion_bus_centers[wrbc_key] = new Array();
		}
		webregion_bus_centers[wrbc_key].push(bus_centers[i]);
	}
	
	var marker_count = 0;
	var webregion_counts = new Array();
	sorted_array = sortArray(webregion_bus_centers);
	
	for (var j in sorted_array) {
		webregion_container = document.createElement("div");
		webregion_container.className = "webregion_container";
		
		webregion_title = document.createElement("div");
		webregion_title_a = document.createElement("a");
		webregion_title.className = "webregion_title";
		webregion_title_a.name = j.toLowerCase(); 
		webregion_title_a.innerHTML = j;
		webregion_title.appendChild(webregion_title_a);
		
		$("#all_centers_container")[0].appendChild(webregion_container);
		webregion_container.appendChild(webregion_title);
		
		webregion_counts[j] = 0;

		for(var k in sorted_array[j]) {
			webregion_counts[j]++;
			marker_count++;
			bus_center_container = document.createElement("div");
			bus_center_container.className = "bus_center_container";
			
			bus_center_marker = document.createElement("div");
			bus_center_marker.className = "bus_center_marker";

			bus_info_container = document.createElement("div");
			bus_info_container.className = "bus_info_container";
		
			bus_center_title = document.createElement("div");
			bus_center_title.className = "bus_center_title";
			bus_center_title_a = document.createElement("a");
			bus_center_title_a.href = "/"+gsvars[110]+"/"+sorted_array[j][k].base;
			bus_center_title_a.innerHTML = "AlphaGraphics "+sorted_array[j][k].centerWebName
			bus_center_title.appendChild(bus_center_title_a);
			
			bus_center_text1 = document.createElement("div");
			bus_center_text1.className = "bus_center_text";
			bus_center_text1.innerHTML = sorted_array[j][k].address1 + ", " + sorted_array[j][k].address2;
			
			bus_center_text2 = document.createElement("div");
			bus_center_text2.className = "bus_center_text";
			bus_center_text2.innerHTML = sorted_array[j][k].city + ", " + sorted_array[j][k].abbreviation + " " + sorted_array[j][k].zip;
			
			bus_center_text3 = document.createElement("div");
			bus_center_text3.className = "bus_center_text";
			bus_center_text3.innerHTML = sorted_array[j][k].websitePhoneNumber;

			bus_center_email = document.createElement("div");
			bus_center_email.className = "bus_center_email";
			
			bus_center_email_link = document.createElement("a");
			bus_center_email_link.href = "mailto:"+sorted_array[j][k].websiteEmail;
			bus_center_email_link.innerHTML = "Click here to e-mail us";
			
			bus_center_directions = document.createElement("div");
			bus_center_directions.className = "bus_center_directions";
			bus_center_directions.innerHTML = "Directions";
			bus_center_directions.latlng = sorted_array[j][k].latlng;
			bus_center_directions.centerID = sorted_array[j][k].centerID;
			bus_center_directions.onclick = function(event) {
				startDirections(this.centerID);
			}
			
			bus_center_img = document.createElement("img");
			bus_center_img.src = sorted_array[j][k].icon_path;
			bus_center_img.infowindow = sorted_array[j][k].marker.infowindow;
			bus_center_img.marker = sorted_array[j][k].marker;
			bus_center_img.latlng = sorted_array[j][k].latlng;
			bus_center_img.onclick = function() {
				infowindow.setContent(this.infowindow);
				infowindow.open(map,this.marker);
			}
			
			webregion_container.appendChild(bus_center_container);			
			bus_center_container.appendChild(bus_center_marker);
			bus_center_marker.appendChild(bus_center_img);
			bus_center_container.appendChild(bus_info_container);
			bus_info_container.appendChild(bus_center_title);
			bus_info_container.appendChild(bus_center_text1);
			bus_info_container.appendChild(bus_center_text2);
			bus_info_container.appendChild(bus_center_text3);
			bus_info_container.appendChild(bus_center_email);
			bus_center_email.appendChild(bus_center_email_link);
			bus_info_container.appendChild(bus_center_directions);
		}
	}
	
	if (marker_count == 0) {
		map.setCenter(latlng);
	} else {
		map.fitBounds(bounds);
		var listener = google.maps.event.addListener(map, "idle", function() {
//			if (map.getZoom() > 6) {
//				map.setZoom(6);
//			}
			google.maps.event.removeListener(listener);
		});
	}
	
	var regionct = "";
	for (var z in webregion_counts) {
		if (regionct != "") {
			regionct += "<div class='region_sep'>|</div>";
		}
		regionct += "<div class='region_sep'><a href='#"+z.toLowerCase()+"'>"+ z + " ("+webregion_counts[z]+")</a></div>";
	}
	$("#regions_floater")[0].innerHTML = regionct;
}

function sortArray(array_to_sort) {
	var array_keys = [];
	for (var x in array_to_sort) {
		array_keys.push(x);
	}
	array_keys.sort();
	
	var return_array = [];
	for (var i=0; i<array_keys.length; i++) {
		return_array[array_keys[i]] = array_to_sort[array_keys[i]];
	}
	return return_array;
}

function handleNoGeolocation() {
	clearTimeout(geoloc_timeout);
	//No coordinates DEFAULT
	var position = {
		coords: {
			latitude: 0,
			longitude: 0
		}
	}
	$.ajax({
		type: "POST",
		url: "/ajax/getcenters",
		data:"search_miles=50&lat="+position.coords.latitude+"&lng="+position.coords.longitude,
		dataType: 'json',
		complete: function(data){
			if (data) {
				var bus_centers = jQuery.parseJSON(data.responseText);
			}
			showMap(position, bus_centers);
		}
	});	
}

function searchByZipCode() {
	email_type = "zip";
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({'address': $("#zip_code")[0].value}, function (results, status){
		if (status == google.maps.GeocoderStatus.OK) {
			var position = {
				coords: {
					latitude: results[0].geometry.location.lat(),
					longitude: results[0].geometry.location.lng()
				}
			}
			var search_miles = $("#search_miles")[0].value;
			email_lat = results[0].geometry.location.lat();
			email_lng = results[0].geometry.location.lng();
			$.ajax({
				type: "POST",
				url: "/ajax/getcenters",
				data:"search_miles="+search_miles+"&lat="+results[0].geometry.location.lat()+"&lng="+results[0].geometry.location.lng(),
				dataType: 'json',
				complete: function(data){
					var bus_centers = jQuery.parseJSON(data.responseText);
					showMap(position, bus_centers);
				}
			});
		}
	});
}

function searchByCityState() {
	if($("#city")[0].value == "" || $("#state")[0].value == 0)
		return;
	email_type = "city";
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({'address': $("#city")[0].value + "," + $("#state")[0].value+" US"}, function (results, status){
		if (status == google.maps.GeocoderStatus.OK) {
			var position = {
				coords: {
					latitude: results[0].geometry.location.lat(),
					longitude: results[0].geometry.location.lng()
				}
			}
			email_lat = results[0].geometry.location.lat();
			email_lng = results[0].geometry.location.lng();
			$.ajax({
				type: "POST",
				url: "/ajax/getcenters",
				data:"search_miles=50&lat="+results[0].geometry.location.lat()+"&lng="+results[0].geometry.location.lng(),
				dataType: 'json',
				complete: function(data){
					var bus_centers = jQuery.parseJSON(data.responseText);
					showMap(position, bus_centers);
				}
			});
		}
	});
}

function searchByCountry(country_code) {
	email_type = "country";
	country = country_code;
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({'address': country_code}, function (results, status){
		if (status == google.maps.GeocoderStatus.OK) {
			var position = {
				coords: {
					latitude: results[0].geometry.location.lat(),
					longitude: results[0].geometry.location.lng()
				}
			}
			email_lat = results[0].geometry.location.lat();
			email_lng = results[0].geometry.location.lng();
			$.ajax({
				type: "POST",
				url: "/ajax/getcentersbycountry",
				data:"country_code="+country_code,
				dataType: 'json',
				complete: function(data){
					var bus_centers = jQuery.parseJSON(data.responseText);
					showMap(position, bus_centers);
				}
			});
		}
	});
}

function searchByState(state_name) {
	state_code = state_name;
	email_type = "state";
	webregion();
}

function startDirections(centerID) {
	$.ajax({
		type: "POST",
		url: "/ajax/getonebuscenter",
		data:"bus_center_id="+centerID,
		dataType: 'json',
		async: false,
		complete: function(data){
			var map_width = 400;
			var map_height = 300;
			//set global variable to pick up when sending an email.
			bus_centerID = centerID;
			var	bus_centers = jQuery.parseJSON(data.responseText);
			var latlng = new google.maps.LatLng(bus_centers[0].latitude, bus_centers[0].longitude);

			var inner_width = $(window).width() + $(window).scrollLeft();
			var inner_height = $(window).height() + $(window).scrollTop();


			if ($("#directions_input_container")[0]) {
				$(document.body)[0].removeChild($("#directions_input_container")[0]);
			}
			var directions_input_container = document.createElement("div");
			directions_input_container.id = "directions_input_container";
			directions_input_container.style.left = (inner_width/2) - (map_width/2)+"px";
			directions_input_container.style.top = ($(window).scrollTop()+100)+"px";
			directions_input_container.style.display = "none";
			
			var directions_input_title = document.createElement("div");
			directions_input_title.id = "directions_input_title";
			directions_input_title.innerHTML = gsvars[74];
			
			var directions_print_img = document.createElement("div");
			directions_print_img.id = "directions_print_img";
			directions_print_img.onclick = function() {
				printDirections();
			}
			
			var directions_email_img = document.createElement("div");
			directions_email_img.id = "directions_email_img";
			directions_email_img.onclick = function() {
				emailMap("directions");
			}
			
			var directions_input_middle_text = document.createElement("div");
			directions_input_middle_text.id = "directions_getd";
			directions_input_middle_text.innerHTML = gsvars[75]+":";
			
			var directions_input_input = document.createElement("input");
			directions_input_input.id = "directions_input";
			directions_input_input.type = "text";
			
			var directions_input_submit = document.createElement("div");
			directions_input_submit.id = "directions_input_submit";
			directions_input_submit.innerHTML = gsvars[70];
			directions_input_submit.onclick = function() {
				getDirections(latlng);
			}
			
			var directions_input_close = document.createElement("div");
			directions_input_close.id = "directions_input_close";
			directions_input_close.innerHTML =  gsvars[59];
			directions_input_close.onclick = function() {
				$("#directions_input_container").fadeOut(1000, function() {
					$(document.body)[0].removeChild($("#directions_input_container")[0]);	
				});
				$("#full_shadow").fadeOut(1000);
			}

			var directions_input_map2_canvas = document.createElement("div");
			directions_input_map2_canvas.id = "map2_canvas";
			directions_input_map2_canvas.style.width = map_width+"px";
			directions_input_map2_canvas.style.height = map_height+"px";

			var directions_panel = document.createElement("div");
			directions_panel.id = "directions_panel";
			
			
			var clear = document.createElement("div");
			clear.className = "clear";
			
			$(document.body)[0].appendChild(directions_input_container);
			directions_input_container.appendChild(directions_print_img);
			directions_input_container.appendChild(directions_email_img);
			directions_input_container.appendChild(directions_input_title);
			directions_input_container.appendChild(directions_input_middle_text);
			directions_input_container.appendChild(directions_input_input);
			directions_input_container.appendChild(directions_input_submit);
			directions_input_container.appendChild(directions_input_close);
			directions_input_container.appendChild(clear);
			directions_input_container.appendChild(directions_input_map2_canvas);
			directions_input_container.appendChild(directions_panel);

			displayShadow();
			$("#directions_input_container").fadeIn(1000);
			
			var infowindow_text = "<div class='bus_info_container'>";
			infowindow_text += "<div class='bus_center_title'>AlphaGraphics "+bus_centers[0].centerWebName+"</div>";
			infowindow_text += "<div class='bus_center_text'>"+bus_centers[0].address1 + ", " + bus_centers[0].address2+"</div>";
			infowindow_text += "<div class='bus_center_text'>"+bus_centers[0].city + ", " + bus_centers[0].abbreviation + " " + bus_centers[0].zip+"</div>";
			infowindow_text += "<div class='bus_center_email'><a href='mailto:"+bus_centers[0].websiteEmail+"'>"+gsvars[73]+"</a></div>";
			infowindow_text += "<div class='bus_center_directions' onclick='startDirections("+bus_centers[0].centerID+");'>"+gsvars[72]+"</div>";
			infowindow_text += "</div>";
			
			myOptions.zoom = 13;
			map2 = new google.maps.Map($("#map2_canvas")[0], myOptions);
			map2.setCenter(latlng);
			
			marker = new google.maps.Marker({
				position: latlng,
				map: map2
			});
			marker.setMap(map2);

			marker.infowindow = infowindow_text;
			var infowindow = new google.maps.InfoWindow();
			google.maps.event.addListener(marker, 'click', function() {
				infowindow.setContent(this.infowindow);
				infowindow.open(map2,this);
			});

			directionsDisplay = new google.maps.DirectionsRenderer();
			directionsDisplay.setMap(map2);
			directionsDisplay.setPanel($("#directions_panel")[0]);
		}
	});
}

function getDirections(latlng) {
	var origin = $("#directions_input")[0].value;
	if (origin == "") {
		return;
	}
	
	var map_loc = findPos($("#directions_input_container")[0]);
	var mheight = getStyle($("#directions_input_container")[0], "height");
	mheight = Number(mheight.substr(0, mheight.length - 2));
	var dp_top = map_loc.top + mheight + 35;
	var dp_width = $("#directions_input_container")[0].width;
	
	
	var request = {
		origin:origin,
		destination:latlng,
		travelMode: google.maps.TravelMode.DRIVING
	}
	directionsService.route(request, function(result, status){
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(result);
			$("#directions_panel").fadeIn(1000);
		}
	});
}

function findPos(obj) {
	var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft;
			curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return {left:curleft,top:curtop};
} 

function getStyle(el, cssprop) {
    if (el.currentStyle) {
            return el.currentStyle[cssprop];
    } else if (document.defaultView && document.defaultView.getComputedStyle) {
            return document.defaultView.getComputedStyle(el, "")[cssprop];
    } else {
            return el.style[cssprop];
    }
}   

function printLocations() {
	window.print();
}

function printDirections() {
	$("#directions_input_container").printElement();
}

function redirectForCountrySearch(country) {
	email_type = "country";
	window.location.href = "/location/find_a_location#country="+country;
}

function redirectForZipCodeSearch() {
	email_type = "zip";
	var zip_code = $("#zip_code")[0].value;
	if (zip_code == "") {
		return;
	}
	var mile_radius = $("#search_miles")[0].value;
	window.location.href = "/location/find_a_location#zip="+zip_code+"|"+mile_radius;
}

function redirectForCitySearch() {
	email_type = "city";
	var city = $("#city")[0].value;
	var state = $("#state")[0].value;
	if (city == "" || state == 0) {
		return;
	}
	window.location.href = "/location/find_a_location#city="+city+"|"+state;
}

function emailMap(which) {
	var container_width = 500;
	var container_height = 300
	var inner_width = $(window).width() + $(window).scrollLeft();
	var inner_height = $(window).height() + $(window).scrollTop();

	var email_container = document.createElement("div");
	email_container.id = "email_container";
	email_container.style.left = (inner_width/2) - (container_width/2)+"px";
	email_container.style.top = "120px";
	email_container.style.width = container_width+"px";
	email_container.style.height = container_height+"px";
	
	var email_title = document.createElement("div");
	email_title.id = "email_title";
	email_title.innerHTML = gsvars[63];

	var email_content = document.createElement("div");
	email_content.innerHTML = gsvars[64];
	email_content.style.marginBottom = "15px";
	
	var email_to_text = document.createElement("div");
	email_to_text.id = "email_to_text";
	email_to_text.innerHTML = gsvars[65]+":";
	
	var email_to_input = document.createElement("input");
	email_to_input.type = "text";
	email_to_input.id = "to_addresses";
	
	var email_subject_text = document.createElement("div");
	email_subject_text.innerHTML = gsvars[66]+":";
	email_subject_text.id = "email_subject_text";
	
	var email_subject_input = document.createElement("input");
	email_subject_input.id = "subject_line";
	email_subject_input.value =gsvars[71];
	
	var email_from_text = document.createElement("div");
	email_from_text.innerHTML = gsvars[67]+":";
	email_from_text.id = "email_from_text";
	
	var email_from_input = document.createElement("input");
	email_from_input.id = "from_address";
	
	var email_message_text = document.createElement("div");
	email_message_text.id = "email_message_text";
	email_message_text.innerHTML = gsvars[68]+":";
	
	var email_message_input = document.createElement("textarea");
	email_message_input.id = "message";

	var cancel_button = document.createElement("input");
	cancel_button.id = "cancel_button";
	cancel_button.type = "button";
	cancel_button.value = gsvars[69];
	cancel_button.onclick = function() {
		$("#email_container").fadeOut(1000, function() {
			$(document.body)[0].removeChild($("#email_container")[0]);
		});
		if ($("#directions_input_container")[0]) {
			$("#directions_input_container").fadeOut(1000, function() {
				$(document.body)[0].removeChild($("#directions_input_container")[0]);
			});	
		}
		$("#full_shadow").fadeOut(1000);
	}
	
	var submit_button = document.createElement("input");
	submit_button.id = "submit_button";
	submit_button.type = "button";
	submit_button.value = gsvars[70];
	submit_button.onclick = function() {
		if (validateForm()) {
			sendMapEmail(which);	
			$("#email_container").fadeOut(1000, function() {
				$(document.body)[0].removeChild($("#email_container")[0]);
			});
			if ($("#directions_input_container")[0]) {
				$("#directions_input_container").fadeOut(1000, function() {
					$(document.body)[0].removeChild($("#directions_input_container")[0]);
				});
			}
			$("#full_shadow").fadeOut(1000);
		}
	}

	email_container.appendChild(email_title);
	email_container.appendChild(email_content);
	email_container.appendChild(email_to_text);
	email_container.appendChild(email_to_input);
	email_container.appendChild(email_subject_text);
	email_container.appendChild(email_subject_input);
	email_container.appendChild(email_from_text);
	email_container.appendChild(email_from_input);
	email_container.appendChild(email_message_text);
	email_container.appendChild(email_message_input);
	email_container.appendChild(cancel_button);
	email_container.appendChild(submit_button);
	$(document.body)[0].appendChild(email_container);
	
	displayShadow();
	$("#email_container").fadeIn(1000);
}

function validateForm() {
	var emailRegEx = new RegExp("^[\\w\\.-]+@(?:[\\w-]+\\.)*[\\w-]+\\.\\w+$");
	
	if ($("#to_addresses")[0].value == "") {
		alert("Please enter the recipient's email address.");
		return false;
	}

	var to_addresses = $("#to_addresses")[0].value.split(",");
	for (var i in to_addresses) {
		to_addresses[i] = $.trim(to_addresses[i]);
		
		if (emailRegEx.test(to_addresses[i]) === false) {
			alert("You have entered an invalid recipient email address");
			return false;
		}
	}
	
	if ($("#from_address")[0].value == "") {
		alert("Please enter your email address.");
		return false;
	}
	
	if (emailRegEx.test($("#from_address")[0].value) === false) {
		alert("You have entered an invalid From address");
		return false;
	}
	
	return true;
}

function sendMapEmail(which) {
	var to_addresses = $("#to_addresses")[0].value.split(",");
	var tos = "";
	for (var i in to_addresses){
		if (tos != "") {
			tos += ",";
		}
		tos += $.trim(to_addresses[i]);
	}
	var email_subject = $("#subject_line")[0].value;
	var from_address = $("#from_address")[0].value
	var data;
	var message = $("#message")[0].value;
	if (which == "webregion") {
		data = state_code;
	} else if (which == "find") {
		if (email_type == "zip") {
			data = $("#zip_code")[0].value + "|" + $("#search_miles")[0].value;
		} else if (email_type == "city") {
			data = $("#city")[0].value + "|" + $("#state")[0].value;
		} else if (email_type == "country") {
			data = country;
		} else {
			data = email_lat+"|"+email_lng;
		}
	} else if (which == "directions") {
		if (email_type == "zip") {
			data = "zip|"+email_lat+"|"+email_lng+"|"+bus_centerID+"|"+$("#zip_code")[0].value + "|" + $("#search_miles")[0].value;
		} else if (email_type == "city") {
			data = "city|"+email_lat+"|"+email_lng+"|"+bus_centerID+"|"+$("#city")[0].value + "|" + $("#state")[0].value;
		} else if (email_type == "country") {
			data = "country|"+email_lat+"|"+email_lng+"|"+bus_centerID+"|"+country;
		} else if (email_type == "state") {
			data = "state|"+email_lat+"|"+email_lng+"|"+bus_centerID+"|"+state_code;
		} else {
			data = "latlng|"+email_lat+"|"+email_lng+"|"+bus_centerID;
		}
	}
	$.ajax({
		type: "POST",
		url: "/ajax/sendmapemail",
		data:"to_addresses="+tos+"&email_subject="+email_subject+"&from_address="+from_address+"&message="+message+"&which="+which+"&email_type="+email_type+"&data="+data,
		dataType: 'json',
		complete: function(data){
			if (data) {
				//alert(data.responseText);
			}
		}
	});
}

function hashHandler() {
	var hash_pieces = window.location.hash.split("=");
	if (hash_pieces[0] == "#country") {
		var country = hash_pieces[1];
		searchByCountry(country);
	} else if (hash_pieces[0] == "#zip") {
		var zip_pieces = hash_pieces[1].split("|");
		$("#zip_code")[0].value = zip_pieces[0];
		$("#search_miles")[0].value = zip_pieces[1];
		searchByZipCode();
	} else if (hash_pieces[0] == "#city") {
		var city_pieces = hash_pieces[1].split("|");
		$("#city")[0].value = city_pieces[0];
		$("#state")[0].value = city_pieces[1];
		searchByCityState();
	} else if (hash_pieces[0] == "#state") {
		state_code = hash_pieces[1];
		webregion();
	} else if (hash_pieces[0] == "#latlng") {
		var latlng_pieces = hash_pieces[1].split("|");
		var position = {
			coords: {
				latitude: latlng_pieces[0],
				longitude: latlng_pieces[1]
			}
		}
		defaultMap(position);
	} else if (hash_pieces[0] == "#directions") {
		var dir_pieces = hash_pieces[1].split("|");

		if (dir_pieces[0] == "country") {
			searchByCountry(dir_pieces[4]);
		} else if (dir_pieces[0] == "zip") {
			$("#zip_code")[0].value = dir_pieces[4];
			$("#search_miles")[0].value = dir_pieces[5];
			searchByZipCode();
		} else if (dir_pieces[0] == "city") {
			$("#city")[0].value = dir_pieces[4];
			$("#state")[0].value = dir_pieces[5];
			searchByCityState();
		} else if (dir_pieces[0] == "state") {
			state_code = dir_pieces[4];
			webregion();
		} else {
			var position = {
				coords: {
					latitude: dir_pieces[1],
					longitude: dir_pieces[2]
				}
			}
			defaultMap(position);
		}
		
		startDirections(dir_pieces[3]);
		var t=setTimeout("displayShadow()",500);
	} else {
		findalocation();
	}
	window.location.hash = "";
}

function displayShadow(){
	$("#full_shadow")[0].style.height = $(document.body)[0].scrollHeight + "px";
	$("#full_shadow").fadeIn(1000);
}

function getIconPath(lkey) {
	return "/images/1600/globals/map_marker.png";
//	var icon_letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
//	var icon_path;
//	if (lkey <= 25) {
//		icon_path = "http://maps.google.com/mapfiles/marker"+icon_letters[lkey]+".png";
//	} else if ((lkey > 25) && (lkey <= 51)) {
//		new_lkey = lkey - 26;
//		icon_path = "http://maps.google.com/mapfiles/marker_yellow"+icon_letters[new_lkey]+".png";
//	} else if ((lkey > 51) && (lkey <= 77)) {
//		new_lkey = lkey - 52;
//		icon_path = "http://maps.google.com/mapfiles/marker_green"+icon_letters[new_lkey]+".png";
//	} else if ((lkey > 77) && (lkey <= 103)) {
//		new_lkey = lkey - 78;
//		icon_path = "http://maps.google.com/mapfiles/marker_orange"+icon_letters[new_lkey]+".png";
//	} else if ((lkey > 103) && (lkey <= 129)) {
//		new_lkey = lkey - 104;
//		icon_path = "http://maps.google.com/mapfiles/marker_purple"+icon_letters[new_lkey]+".png";
//	} else {
//		icon_path = "http://maps.google.com/mapfiles/marker.png";
//	}
//	
//	return icon_path;
}

function checkForEnterPress(e, fn) {
	var keycode;
	if (e) {
		if (window.event) {
			keycode = window.event.keyCode;
		} else if (e) {
			keycode = e.which;
		} else {
			keycode = null;
		}
		
		if (keycode != 13) {
			return false;
		} else {
			fn();
			return true;
		}
	}	
}

var temp = window.onload;
window.onload = function() {
	temp();
	if (window.location.hash) {
		hashHandler();
	} else if (window.location.href.indexOf("find_a_location") != -1) {
		findalocation();
	} else {
//		webregion();
	}
	
}



