// JavaScript Document
var p = 0;
var position = "";
var geocoder = null;
var addressMarker;
var gdir = "";

var area_Geocodes = { 
	"allentown_area" : "40.602229,-75.471537",
	"bath_area" : "40.727212,-75.392987",
	"bethlehem_area" : "40.626164,-75.360561",
	"center_valley_area" : "40.529275,-75.393747",
	"easton_area" : "40.682722, -75.218692",
	"emmaus_area" : "40.534442,-75.493397",
	"lehigh_valley" : "40.621198,-75.400825",
	"lehighton_area" : "40.830695,-75.721609",
	"pennsylvania" : "40.912559,-77.768741",
	"philadelphia_area" : "39.951639,-75.163808",
	"pocono_area" : "41.055539,-75.308332",
	"schnecksville_area" : "40.675421,-75.621197",
	"slate_belt_area" : "40.875389,-75.225905",
	"whitehall_area" : "40.623271,-75.466026",
	"berks_county" : "40.407462,-75.984907",
	"bucks_county" : "40.328646,-75.102778",
	"montgomery_county" : "40.212065,-75.355912",
	"schuylkill_county" : "40.722587,-76.229632",
	"nyc" : "40.606679,-74.162418",
	"nyc_bronx" : "40.826878,-73.922742",
	"nyc_brooklyn" : "40.675234,-73.971043",
	"nyc_manhattan" : "40.749863,40.749863",
	"nyc_queens" : "40.651384,-73.871609",
	"nyc_staten_island" : "40.606679,-74.162418",
	"phillipsburg_area" : "40.691209,-75.184105"	
};	

var city_Geocodes = {
	"pa_albrightsville" : "41.017204,-75.600902",
	"pa_alburtis" : "40.509068,-75.599820",
	"pa_allentown" : "40.602229,-75.471537",
	"pa_aquashicola" : "40.811042,-75.590394",
	"pa_ashfield" : "40.784519,-75.714017",
	"pa_bangor" : "40.866932,-75.206292",
	"pa_bartonsville" : "41.004912,-75.279663",
	"pa_bath" : "40.716940,-75.394602",
	"pa_bethlehem" : "40.626164,-75.360561",
	"pa_blakeslee" : "41.092719,-75.592651",
	"pa_bowmanstown" : "40.799035,-75.663141",
	"pa_breinigsville" : "40.539790,-75.630716",
	"pa_brodheadsville" : "40.923428,-75.397489",
	"pa_catasauqua" : "40.649687,-75.466915",
	"pa_center valley" : "40.529275,-75.393747",
	"pa_cherryville" : "40.754145,-75.538616",
	"pa_coopersburg" : "40.510283,-75.391537",
	"pa_coplay" : "40.671566,-75.496974",
	"pa_danielsville" : "40.794846,-75.532949",
	"pa_dingmans ferry" : "41.223049,-74.870857",
	"pa_east stroudsburg" : "41.002827,-75.183229",
	"pa_east texas" : "40.547318,-75.561553",
	"pa_easton" : "40.682722, -75.218692",	
	"pa_effort" : "40.939045,-75.435864",
	"pa_emmaus" : "40.534442,-75.493397",
	"pa_fogelsville" : "40.579050,-75.629475",
	"pa_gilbert" : "40.915718,-75.440055",
	"pa_greentown" : "41.321388,-75.307597",	
	"pa_hawley" : "41.479121,-75.175161",
	"pa_hellertown" : "40.582039,-75.338970",	
	"pa_honesdale" : "41.577058,-75.258028",
	"pa_jim thorpe" : "40.887457,-75.743326",
	"pa_kresgeville" : "40.896962,-75.503277",	
	"pa_kunkletown" : "40.965498,-75.256722",
	"pa_lake harmony" : "41.060436,-75.591274",
	"pa_lakeville" : "41.438086,-75.276877",
	"pa_lansford" : "40.831987,-75.882484",
	"pa_laurys station" : "40.723307,-75.530229",
	"pa_lehighton" : "40.830695,-75.721609", 
	"pa_limeport" : "40.508884,-75.447235", 
	"pa_macungie" : "40.515715,-75.555604",
	"pa_marshalls creek" : "41.042833,-75.127432", 
	"pa_martins creek" : "40.783713,-75.186532",
	"pa_mount bethel" : "40.904034,-75.112572", 
	"pa_mount pocono" : "41.126405,-75.359841", 
	"pa_mountainhome" : "41.180286,-75.268996", 
	"pa_nazareth" : "40.740631,-75.311936", 
	"pa_neffs" : "40.694790,-75.609655", 
	"pa_nesquehoning" : "40.861567,-75.830462", 
	"pa_new tripoli" : "40.681042,-75.752000", 
	"pa_northampton" : "40.686439,-75.491853", 
	"pa_old zionsville" : "40.485306,-75.523413",
	"pa_orefield" : "40.633365,-75.583635",
	"pa_palmerton" : "40.799101,-75.616530", 
	"pa_parryville" : "40.821998,-75.678323", 
	"pa_pen argyl" : "40.868641,-75.254970",
	"pa_pocono pines" : "41.107791,-75.457387", 
	"pa_pocono summit" : "41.110995,-75.386231", 
	"pa_portland" : "40.919962,-75.094123",
	"pa_reeders" : "41.018921,-75.335936", 
	"pa_saylorsburg" : "40.896456,-75.324705", 
	"pa_schnecksville" : "40.675421,-75.621197", 
	"pa_sciota" : "40.927939,-75.316540", 
	"pa_slatedale" : "40.744543,-75.656573", 
	"pa_slatington" : "40.752534,-75.606187", 
	"pa_stockertown" : "40.755220,-75.262137", 
	"pa_stroudsburg" : "40.984371,-75.197890", 
	"pa_summit hill" : "40.825091,-75.850084", 
	"pa_tafton" : "41.404805,-75.183190", 
	"pa_tannersville" : "41.044188,-75.308617", 	
	"pa_tatamy" : "40.740698,-75.259408",
	"pa_tobyhanna" : "41.174780,-75.421609", 
	"pa_trexlertown" : "40.547883,-75.605869",
	"pa_weatherly" : "40.943400, -75.822651",
	"pa_whitehall" : "40.623271,-75.466026",
	"pa_wind gap" : "40.849976,-75.291502",
	"pa_zionsville" : "40.481801,-75.507160",
	"nj_phillipsburg" : "40.691209,-75.184105",
	"nj_belvidere" : "40.827447,-75.073691",
	"nj_bloomsburg" : "40.694041,-75.111097",
	"nj_stewartsville" : "40.694041,-75.111097",
	"nj_washington" : "40.757858,-74.982368"	
};

$(document).ready(function() {			   					   

	$("a[class^='gas']").livequery('click', function(event) {
		$("#show_gas").replaceWith('<div id="show_gas"></div>');
		$("#show_gas").hide();
		var temp = $(this).attr("class");
		temp = temp.split("%");
		id_select = temp[1];
		if (id_select == 1) {
			window.location.href = "/gas_pa/";
		}
		if (id_select == 2) {
			window.location.href = "/gas_ny/";
		}
		if (id_select == 3) {
			window.location.href = "/gas_nj/";
		}
	});	

	$("a[href='#gotomap']").livequery('click', function(event) {
		return false;
	});
	
	$("a[id^='mapit']").livequery('click', function(event) {
		var temp = $(this).attr("id");
		temp = temp.split("%");
		id = temp[1];
		//lat = temp[2];
		//lng = temp[3];
		gasMap(id);
		window.scrollTo(0, 200);
	});	

	$(".gas_pa, .gas_nj, .gas_ny, .city_search_pa, .city_search_nj").livequery('change', function(event) {
		closeGasWindow();
	});	
	
	$(".city_search_pa").livequery('change', function(event) {										  
		var location = $("#location").val();
		var city = $("#city").val();
		var string = "&location=" + location + "&city=" + city + '&p=' + p;
		$.ajax({
			type: "POST",
			url: "models/ajax-gas-pa.php",
			data: string,
			success: function(html){
				$("#show_gas_pa").show().html(html);
				showCityPA(city.toLowerCase(), p);
				$("select[id='city'] option[value='" + city + "']").attr("selected","selected");
			}
		});
	});
	
	$(".city_search_nj").livequery('change', function(event) {				  
		var location = $("#location").val();
		var city = $("#city").val();
		var string = "&location=" + location + "&city=" + city + '&p=' + p;
		$.ajax({
			type: "POST",
			url: "models/ajax-gas-nj.php",
			data: string,
			success: function(html){
				$("#show_gas_nj").show().html(html);
				showCityNJ(city.toLowerCase(), p);
				$("select[id='city'] option[value='" + city + "']").attr("selected","selected");
			}
		});
	});

	$(".directions").livequery('click', function(event) {
		$("#directions").replaceWith('<div id="directions"></div>');										 
		getNewDirections();
	});
	
	$(".gas_pa").livequery('change', function(event) {	
		$("select[id='city'] option[value='']").attr("selected","selected");									  
		loadPA();	
	});
	
	$(".gas_ny").livequery('change', function(event) {
		$("select[id='city'] option[value='']").attr("selected","selected");
		loadNY();	
	});

	$(".gas_nj").livequery('change', function(event) {
		$("select[id='city'] option[value='']").attr("selected","selected");											  
		loadNJ();	
	});
});

function closeGasWindow() {
	$("#gas_information").replaceWith('<div id="gas_information"></div>');
	$("#gas_information").hide();
	$(".ajax_gas").css("backgroundColor", "#FFFFFF");
}

function createGasMarker(station_point, station_name, station_address, station_city, station_state, station_id, station_ppg, station_datetime) {  
	var gasIcon = new GIcon(G_DEFAULT_ICON);
	gasIcon.image = 'images/map.gas_pumps.png';
	gasIcon.iconSize = new GSize(32, 32);
	gasIcon.iconAnchor = new GPoint(32, 16);
	gasIcon.infoWindowAnchor = new GPoint(2, 16);
	gasIcon.shadow = 'images/icon_shadow.png';
	gasIcon.shadowSize = new GSize(32, 32);

	var marker = new GMarker(station_point, { icon: gasIcon });	
	GEvent.addListener(marker, 'click', function() {
		$("." + station_id).css("backgroundColor", "#C0D1BE");										 
		$("#gas_information").replaceWith('<div id="gas_information"></div>');
		$("#gas_information").slideDown();
		$("#gas_information").html('<strong>' + station_name  + '</strong><a href="javascript:void(0);" onClick="closeGasWindow();"><img id="close" src="images/closebutton.gif" title="Close this window" class="close"/></a><br/><br/>' + station_address + '<br/>' + station_city + ', ' + station_state + '<br/><strong>PPG $' + station_ppg + '</strong> Last updated: ' + station_datetime + '<br/><br/>Report a Tip - <b>610-778-7900</b><br/>traffic@mcall.com');	
	});		
	return marker;
}

function displayMap(map, path, bounds, position) {
	GDownloadUrl(path, function(data, responseCode) {
		if (data.length >= 1) {
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {
				var station_point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
				var station_name = markers[i].getAttribute("name");
				var station_address = markers[i].getAttribute("address");
				var station_city = markers[i].getAttribute("city");
				var station_state = markers[i].getAttribute("state");
				var station_id = markers[i].getAttribute("id");	
				var station_ppg = markers[i].getAttribute("station_ppg");	
				var station_datetime = markers[i].getAttribute("datetime");	
				var marker = createGasMarker(station_point, station_name, station_address, station_city, station_state, station_id, station_ppg, station_datetime);
				map.addOverlay(marker);	
				bounds.extend(station_point);
			}
			map.setZoom(map.getBoundsZoomLevel(bounds));
        	map.setCenter(bounds.getCenter());
		}
		else {
			position = position.split(",");
			var lat = position[0];
			var lng = position[1];
			map.setCenter(new GLatLng(lat,lng), 11);	
		}
	});
}

function gasMap(point_id) {
	var page = $("#page").val();
	if (page == "gas_pa") {
		var location = $("#location").val();
		var city = $("#city").val();
		var saved = (city != "") ? "pa_" + city : location;
	}
	if (page == "gas_nj") {
		var location = $("#location").val();
		var city = $("#city").val();
		var saved = (city != "") ? "nj_" + city : location;		
	}	
	if (page == "gas_ny") {
		var saved = $("#location").val();
	}
	if (GBrowserIsCompatible()) {
		var trafficInfo = new GTrafficOverlay();
		var map = new GMap2(document.getElementById("gas_map"));
		map.setCenter(new GLatLng(0,0),0);
		var bounds = new GLatLngBounds();
		map.removeMapType(G_HYBRID_MAP);
		map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
		map.addControl(new GSmallMapControl());
		var data = "";
		GDownloadUrl("./cache/" + saved + ".xml", function(data) {
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {
				var station_point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
				var station_name = markers[i].getAttribute("name");
				var station_address = markers[i].getAttribute("address");
				var station_city = markers[i].getAttribute("city");
				var station_state = markers[i].getAttribute("state");
				var station_id = markers[i].getAttribute("id");	
				var station_ppg = markers[i].getAttribute("station_ppg");	
				var station_datetime = markers[i].getAttribute("datetime");	
				var marker = createGasMarker(station_point, station_name, station_address, station_city, station_state, station_id, station_ppg, station_datetime);
				map.addOverlay(marker);
				if (station_id == point_id) {
					marker.show();
					$("." + station_id).css("backgroundColor", "#C0D1BE");
					bounds.extend(station_point);
				}	
				else {
					marker.hide();
					$("." + station_id).css("backgroundColor", "#FFFFFF");	
				}
			}
			map.setZoom(map.getBoundsZoomLevel(bounds));
        	map.setCenter(bounds.getCenter());
		});
	}	
}

function getDirections() {
	var map_from_address = $("#user_address").val();
	var map_from_city = $("#user_city").val();
	var map_from_state = $("#user_state").val();
	var map_from_zipcode = $("#user_zipcode").val();
	var map_to_address = $("#user_work_address").val();
	var map_to_city = $("#user_work_city").val();
	var map_to_state = $("#user_work_state").val();
	var map_to_zipcode = $("#user_work_zipcode").val();	
	var fromAddress = map_from_address + ' ' + map_from_city + ' ' + map_from_state + ' ' + map_from_zipcode;
	var toAddress = map_to_address + ' ' + map_to_city + ' ' + map_to_state + ' ' + map_to_zipcode;	
	var map_directions = new GMap2(document.getElementById("map_canvas"));
    gdir = new GDirections(map_directions, document.getElementById("directions"));
    GEvent.addListener(gdir, "error", handleErrors);
    setDirections(fromAddress, toAddress, "en_US");
}

function getNewDirections() {
	var fromAddress = $("#fromAddress").val();
	var toAddress = $("#toAddress").val();	
	$("#map_canvas").show();
	var map = new GMap2(document.getElementById("map_canvas"));
    gdir = new GDirections(map, document.getElementById("directions"));
    GEvent.addListener(gdir, "error", handleErrors);
    setDirections(fromAddress, toAddress, "en_US");
}

function getpageNJ(pn) {
	p = pn;
	loadNJ(p);
	p = 0;
}

function getpageNY(pn) {
	p = pn;
	loadNY(p);
	p = 0;
}

function getpagePA(pn) {
	p = pn;
	loadPA(p);
	p = 0;
}

function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS || gdir.getStatus().code == G_GEO_SERVER_ERROR || gdir.getStatus().code == G_GEO_MISSING_QUERY || gdir.getStatus().code == G_GEO_BAD_KEY || gdir.getStatus().code == G_GEO_BAD_REQUEST)
	 alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
}

function loadNJ(p) {
	p = (p == "" || p == undefined || p == "undefined") ? 0 : p;
	var location = $("#location").val();
	var city = $("#city").val();
	var string = (city == "" || city == undefined || city == "undefined") ? "&location=" + location + '&p=' + p : "&location=" + location + "&city=" + city + '&p=' + p;
	$.ajax({
		type: "POST",
		url: "models/ajax-gas-nj.php",
		data: string,
		success: function(html){
			$("#show_gas_nj").replaceWith('<div id="show_gas_nj">' + html + '</div>');
			if (city == "" || city == undefined || city == "undefined") {
				showGas(location.toLowerCase(), p);
			}
			else {
				showCity(city.toLowerCase(), p);
				$("select[id='city'] option[value='" + city + "']").attr("selected","selected");
			}
		}
	});
}

function loadNY(p) {
	p = (p == "" || p == undefined || p == "undefined") ? 0 : p;
	var location = $("#location").val();
	var string = "&location=" + location + '&p=' + p;
	$.ajax({
		type: "POST",
		url: "models/ajax-gas-ny.php",
		data: string,
		success: function(html){
			$("#show_gas_ny").replaceWith('<div id="show_gas_ny">' + html + '</div>');
			showGas(location.toLowerCase(), p);
		}
	});
}

function loadPA(p) {
	p = (p == "" || p == undefined || p == "undefined") ? 0 : p;
	var location = $("#location").val();
	var city = $("#city").val();
	var string = (city == "" || city == undefined || city == "undefined") ? "&location=" + location + '&p=' + p : "&location=" + location + "&city=" + city + '&p=' + p;
	$.ajax({
		type: "POST",
		url: "models/ajax-gas-pa.php",
		data: string,
		success: function(html){						 
			$("#show_gas_pa").replaceWith('<div id="show_gas_pa">' + html + '</div>');
			if (city == "" || city == undefined || city == "undefined") {
				showGas(location.toLowerCase(), p);
			}
			else {
				showCityPA(city.toLowerCase(), p);
				$("select[id='city'] option[value='" + city + "']").attr("selected","selected");
			}
		}	
	});
}

function myGas() {
	if ($("input[@name='home_default']").is(":checked")) {
		var default_lat = $("#default_lat").val();
		var default_lng = $("#default_lng").val();
		var default_city = $("#user_city").val();
		
	}
	if ($("input[@name='work_default']").is(":checked")) {
		var default_lat = $("#default_lat").val();
		var default_lng = $("#default_lng").val();
		var default_city = $("#user_work_city").val();
	}	
	default_city = (default_city == "" || default_city == undefined) ? "allentown" : default_city.toLowerCase();
	default_lat = (default_lat == "" || default_lat == undefined || default_lat == 0) ? "40.602229" : default_lat;
	default_lng = (default_lng == "" || default_lng == undefined || default_lng == 0) ? "-75.471537" : default_lng;	
	if (default_lat == 0 || default_lng == 0) {
		default_city = "allentown";
		default_lat = "40.602229";
		default_lng = "75.471537";
	}
	if (GBrowserIsCompatible()) {
		var trafficInfo = new GTrafficOverlay();
		var map = new GMap2(document.getElementById("mygas"));
		map.setCenter(new GLatLng(0,0),0);
		var bounds = new GLatLngBounds();
		map.removeMapType(G_HYBRID_MAP);
		map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
		map.addControl(new GSmallMapControl());
		var path = "./cache/pa_" + default_city + ".xml";	
		GDownloadUrl(path, function(data, responseCode) {
			if (data.length >= 1) {
				var xml = GXml.parse(data);
				var markers = xml.documentElement.getElementsByTagName("marker");
				for (var i = 0; i < markers.length; i++) {
					var station_point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
					var station_name = markers[i].getAttribute("name");
					var station_address = markers[i].getAttribute("address");
					var station_city = markers[i].getAttribute("city");
					var station_state = markers[i].getAttribute("state");
					var station_id = markers[i].getAttribute("id");	
					var station_ppg = markers[i].getAttribute("station_ppg");	
					var station_datetime = markers[i].getAttribute("datetime");	
					var marker = createGasMarker(station_point, station_name, station_address, station_city, station_state, station_id, station_ppg, station_datetime);
					map.addOverlay(marker);	
					bounds.extend(station_point);
				}
				map.setZoom(map.getBoundsZoomLevel(bounds));
        		map.setCenter(bounds.getCenter());
			}
			else {
				alert('There are no gas stations in your area. Please go to GasBuddy.com to add some.');
				map.setCenter(new GLatLng(default_lat,default_lng), 14);	
			}
		});
	}	
}

function setDirections(fromAddress, toAddress, locale) {	
	if (fromAddress != "" && toAddress != "") {
		gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "en_US" });
	}
}

function showCityNJ(city, p) {
	var position = city_Geocodes['nj_' + city];
	if (GBrowserIsCompatible()) {
		var trafficInfo = new GTrafficOverlay();
		var map = new GMap2(document.getElementById("gas_map"));
		map.setCenter(new GLatLng(0,0),0);
		var bounds = new GLatLngBounds();	
		map.removeMapType(G_HYBRID_MAP);
		map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
		map.addControl(new GSmallMapControl());
		var path = "./cache/nj_" + city + ".xml";	
		displayMap(map, path, bounds, position);
	}	
}

function showCityPA(city, p) {
	var position = city_Geocodes['pa_' + city];
	if (GBrowserIsCompatible()) {
		var trafficInfo = new GTrafficOverlay();
		var map = new GMap2(document.getElementById("gas_map"));
		map.setCenter(new GLatLng(0,0),0);
		var bounds = new GLatLngBounds();
		map.removeMapType(G_HYBRID_MAP);
		map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
		map.addControl(new GSmallMapControl());
		var path = "./cache/pa_" + city + ".xml";	
		displayMap(map, path, bounds, position);
	}	
}

function showGas(location, p) {
	if (GBrowserIsCompatible()) {
		var trafficInfo = new GTrafficOverlay();
		var map = new GMap2(document.getElementById("gas_map"));
		map.setCenter(new GLatLng(0,0),0);
		var bounds = new GLatLngBounds();
		map.removeMapType(G_HYBRID_MAP);
		map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
		map.addControl(new GSmallMapControl());
		var path = "./cache/" + location + ".xml";	
		displayMap(map, path, bounds);
	}	
}


