function CoordMapType(tileSize) {
    this.tileSize = tileSize;
}
 
CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
	var div = ownerDocument.createElement('DIV');
	div.innerHTML = coord;
	div.style.width = this.tileSize.width + 'px';
	div.style.height = this.tileSize.height + 'px';
	div.style.fontSize = '10';
	div.style.borderStyle = 'solid';
	div.style.borderWidth = '1px';
	div.style.borderColor = '#AAAAAA';
	return div;
};
 
var map;
var geocoder;
var hIcon = "/wp-content/themes/abogo/images/abogo_icon.png";
var default_position = new google.maps.LatLng(40.27, -97.6);
var default_zoom = 3;

var abogoTiles = {
	getTileUrl: function(coord, zoom) {
		return "http://abogo.htaindex.org/abogo_mst.php?" +
		"z=" + zoom + "&x=" + coord.x + "&y=" + coord.y + "&client=api";
	},
	tileSize: new google.maps.Size(256, 256),
	isPng: true
};

var labelTiles = {
	getTileUrl: function(coord, zoom) {
		return "http://mt0.google.com/vt/v=apt.116&hl=en-US&" +
		"z=" + zoom + "&x=" + coord.x + "&y=" + coord.y + "&client=api";
	},
	tileSize: new google.maps.Size(256, 256),
	isPng: true
};


var abogoTileLayer = new google.maps.ImageMapType(abogoTiles);
var googleLabelLayer = new google.maps.ImageMapType(labelTiles);

		
function initialize() 
{
	geocoder = new google.maps.Geocoder();
	var mapOptions = {
		zoom: default_zoom,
		center: default_position,
		disableDefaultUI: true,
		panControl: true,
		zoomControl: true,
		zoomControlOptions: {
			style: google.maps.ZoomControlStyle.SMALL
		},
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	map.overlayMapTypes.insertAt(0, abogoTileLayer);
	map.overlayMapTypes.insertAt(1, googleLabelLayer);

	if(lat != "" && lng != ""){
		var location = new google.maps.LatLng(lat, lng);
		map.setCenter(location);
		map.setZoom(13);
		getVals();
		var marker = new google.maps.Marker({
			map: map, 
			position: location,
			icon: hIcon
		});
	}
	
}

function getGeo() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
		var addresses = results.length;
		if (addresses == 1){
			lat = results[0].geometry.location.lat();
			lng = results[0].geometry.location.lng();
			centerOnAddress();
		}
		else{
			var addressOptions = "Found "+addresses+" possible addresses:<br />";
			for (var i=0; i<addresses; i++){
				var this_lat = results[i].geometry.location.lat();
				var this_lng = results[i].geometry.location.lng();
				addressOptions = addressOptions + "<a href=\"javascript: void(0);\" onclick=\"close_error_box(); lat="+this_lat+"; lng="+this_lng+"; centerOnAddress();\">"+(i+1)+". "+results[i].formatted_address+"</a><br />";
			}
			document.getElementById("error_box").innerHTML = addressOptions;
			open_error_box("address");
		}
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

function centerOnAddress(){
	var location = new google.maps.LatLng(lat, lng);
	map.setCenter(location);
	map.setZoom(13);
	getVals();
	var marker = new google.maps.Marker({
		map: map, 
		position: location,
		icon: hIcon
	});
}  

  
function goToAddress()
{
	var search = document.getElementById("address").value;
	document.location = "?address="+encodeURIComponent(search);
}

  

function getVals()
{
	$(".hourglass").show();
	var gas = document.getElementById("gas").value;
	var url="/wp-content/themes/abogo/getvals.php";
	url=url+"?lat="+lat;
	url=url+"&lng="+lng;
	url=url+"&gas="+gas;
	$.getJSON(url, function(htaindex) {
	// get JSON values
		var tcost = document.getElementById('transportation_cost');
		var income = document.getElementById('income');
		var d_l_tcost = document.getElementById('display_local_tcost');
		var d_r_tcost = document.getElementById('display_regional_tcost');
		var d_l_co2 = document.getElementById('display_local_co2');
		var d_r_co2 = document.getElementById('display_regional_co2');
		var d_l_tcost_gas = document.getElementById('display_local_tcost_gas');
		var d_gas_price_increase = document.getElementById('display_gas_increase');
		
		var match = htaindex.match;
		if (match.indexOf("block groups with a similar gross density and median income")==-1 && match != "No nearby block groups or block groups with similar gross density available.")
		{
			tcost.value = htaindex.monthly_transportation_cost;
			if (last_update == 'income')
			{
				update_hcost();
			}
			else if(last_update == 'hcost')
			{
				update_income();
			}
			d_l_tcost.innerHTML = htaindex.monthly_transportation_cost;
			d_l_tcost_gas.innerHTML = htaindex.monthly_transportation_cost_gas;
			d_gas_price_increase.innerHTML = Math.round((htaindex.monthly_transportation_cost_gas-htaindex.monthly_transportation_cost)/htaindex.monthly_transportation_cost*100);
			d_r_tcost.innerHTML = htaindex.regional_monthly_transportation_cost;
			d_l_co2.innerHTML = htaindex.monthly_co2;
			d_r_co2.innerHTML = htaindex.regional_monthly_co2;

			document.getElementById('vals').style.display = 'block';
			document.getElementById('outofrange').style.display = 'none';
			
			if (match == "Preliminary estimates for non-metro areas.")
			{
				document.getElementById('asteric').style.visibility = 'visible';
				document.getElementById('footnote').style.display = 'block';
			}
			else
			{
				document.getElementById('asteric').style.visibility = 'hidden';
				document.getElementById('footnote').style.display = 'none';
			}
			

		}
		else
		{
			tcost.value = "";
			d_l_tcost.innerHTML = "";
			d_r_tcost.innerHTML = "";
			d_l_co2.innerHTML = "";
			d_r_co2.innerHTML = "";
			
			document.getElementById('vals').style.display = 'none';
			document.getElementById('outofrange').style.display = 'block';
		}
		$(".hourglass").hide();
	});
}

function GetXmlHttpObject()
{ 
	var objXMLHttp=null;
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
} 


function close_error_box()
{
	hide_blanket();

	ebx=document.getElementById('error_box');
//	cout=document.getElementById('error_calloutDown');
//	cout2=document.getElementById('error_calloutDown2');

	ebx.innerHTML="";
	ebx.style.visibility="hidden";
	ebx.style.display="none";

//	cout.style.visibility='hidden'; 
//	cout.style.display='none'
//	cout2.style.visibility='hidden'; 
//	cout2.style.display='none'
	
}

function open_error_box(error_field_id)
{

	toggle_blanket();
	ebx=document.getElementById("error_box");

//	pos=findPos(document.getElementById(error_field_id));
//	lft=pos.substring(0,pos.indexOf(","));
//	tp=pos.substring(pos.indexOf(",")+1,pos.length);

//	cout=document.getElementById('error_calloutDown');
//	cout2=document.getElementById('error_calloutDown2');

//	lft=(lft-150);
//	tp=(tp-164);
//	ebx.style.left = lft + 'px';
//	ebx.style.top = tp + 'px';
		
//	if(lft<0){ebx.style.left = '10px';}

//	cout.style.left=(lft+160) + 'px';
//	cout.style.top = (tp+156) + 'px';
	
	ebx.style.visibility='visible'; 
	ebx.style.display='block'
//	cout.style.visibility='visible'; 
//	cout.style.display='block'
//	cout2.style.visibility='visible'; 
//	cout2.style.display='block'
}

function toggle_gas(){
	if ($("#gas_price:visible").length===0) {
		$("#gas_price").show();
		$("#gas_price_blanket").show();
		_gaq.push(['_trackPageview','/gas_slider']);
		if (!lat) {
			$(".display_ok").hide();
			$(".display_error").show();
		}
	}
	else {
		$("#gas_price").hide();
		$("#gas_price_blanket").hide();
		$(".display_error").hide();
		$(".display_ok").show();
	}
	return false;
}


function toggle_blanket(){
	var el = document.getElementById("blanket");
	if ( el.style.display == 'none' ) 
	{
		blanket_size();
		el.style.display = 'block';
	}
		
	else {el.style.display = 'none';}
}

function hide_blanket(){
	var el = document.getElementById("blanket");
	el.style.display = 'none';
}

function blanket_size() {
	if (typeof window.innerWidth != 'undefined') {
		viewportheight = window.innerHeight;
	} else {
		viewportheight = document.documentElement.clientHeight;
	}
	if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
		blanket_height = viewportheight;
	} else {
		if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
			blanket_height = document.body.parentNode.clientHeight;
		} else {
			blanket_height = document.body.parentNode.scrollHeight;
		}
	}
	var blanket = document.getElementById("blanket");
	blanket.style.height = blanket_height + 'px';
}


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

function check_this_int(field)
{
	if (field.value == 0)
	{
		return true;
	}
	else if (field.value = Math.round(field.value))
	{
		return true;
	}
	else
	{
		field.value = "";
		document.getElementById('error_box').innerHTML = "Please enter an integer.<br /><input type='button' value='OK' onclick='close_error_box()' />";
		open_error_box(field.id);
		return false;
	}	
}

var last_update = '';
function update_income()
{
	var tcost = document.getElementById('transportation_cost').value*1;
	var hcost = document.getElementById('housing_cost').value*1;
	var income = document.getElementById('income');
	income.value = Math.round(((tcost+hcost)/.45))
	last_update = 'hcost';
}

function update_hcost()
{
	var tcost = document.getElementById('transportation_cost').value*1;
	var income = document.getElementById('income').value*1;
	var hcost = document.getElementById('housing_cost');
	hcost.value = Math.round((income*.45-tcost));
	last_update = 'income';
}


function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

	
$(document).ready(function(){
	var gas_min_price = 3;
	var gas_max_price = 7;
	var gpa = $("#WP_gas_price").text();
	gpa = parseFloat(gpa);
	if (gpa == 0 || isNaN(gpa)) {
		gpa = 3.84;
	}
	var gas_default_price = gpa;
  $("#gas").val(gas_default_price);	
  $("#gas_price_display").text(formatCurrency(gas_default_price));	
  $("#gas").trigger("change");	   	
	$("#gas_price_average_display").text(formatCurrency(gpa));
	gpa = (gpa - gas_min_price) / (gas_max_price - gas_min_price) * 95; 
	gpa = gpa + "%";
	$("#gas_price_average").css("left", gpa)
	$("#gas_slider").slider({min:gas_min_price, max:gas_max_price, value:gas_default_price, step: 0.05});
	$("#gas_slider").slider({
   slide: function(event, ui) {
   	$("#gas").val(ui.value);	
   	var amount = formatCurrency(ui.value);
   	$("#gas_price_display").text(amount);	
   }, 
   change: function(event, ui) {
   	$("#gas").trigger("change");	   	
   }
	});
	$("#gas_price_reset").click(function() {
		$("#gas").val(gas_default_price);	
		$("#gas_price_display").text(formatCurrency(gas_default_price));	
		$("#gas_slider").slider("option", "value", gas_default_price );
		$("#gas").trigger("change");	   
		return false;
	});
	
});

  







