var original = new Point(28.738889, -88.389722);
var current = original;
var geoloc = new GeoLoc();
var map;
var spill = new MapBlob();
var autoDetected = false;

$(function() { 
	map = new google.maps.Map($("#map_canvas").get(0), {	
		zoom: 7,
		center: new google.maps.LatLng(original.lat, original.lng),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	geoloc.addEvent("ready", geolocComplete);
	$.ajax({
		url: 'js/disasters/data/bp.xml',
		success: renderSpill,
		dataType: 'xml'
	});
});	


function renderSpill(data) {
	kml = data;
	var polys = kml.getElementsByTagName('coordinates');
	for ( var i=0; i < polys.length; i++ ) {
		poly = polys[i];
		if ( poly.parentNode.parentNode.tagName.toLowerCase() != 'outerboundaryis' ) {
			continue;
		}
		var placemark = findPlacemark(poly);
		var color = placemark.getElementsByTagName('PolyStyle')[0].getElementsByTagName('color')[0];
		var colorStr = color.textContent;
		if ( !colorStr ) {
			colorStr = color.text;
		}
		
		var text = poly.textContent;
		if ( !text ) {
			text = poly.text;
			if ( !text ) {
				continue;
			}
		}

		var poly = new Polygon();
		poly.parse(text);
		
		poly.fillColor = '000000';
		poly.strokeColor = false;
		
		if ( colorStr == 'ffd10000' ) {
			poly.fillColor = '050505';
		}
		if ( colorStr == 'ffffff00' ) {
			poly.fillColor = '0A0A0A';
		}
		if ( colorStr == 'ff000000' ) { 
			poly.fillColor = '101010';
			poly.strokeColor = '000000';
		}
		
		spill.add(poly);	
	}
	spill.draw(map);
	geoloc.autoDetect();
}

function findPlacemark(tag) {
	if ( tag.parentNode.tagName == 'Placemark' ) {
		return tag.parentNode;
	}
	if ( tag.parentNode ) {
		return findPlacemark(tag.parentNode);
	}
	return fale;
}

function geolocComplete() {
	if ( geoloc.loc ) {
		spill.moveTo(current, geoloc.loc);
		spill.centerAndZoom(map);
		spill.draw(map);
	} 
	if ( geoloc.str ) {
		$(".current_geoloc").each(function(i, s) {
			s.innerHTML = geoloc.str;
		});
		$('#geolocInput').val(geoloc.str);
		if ( !autoDetected ) {
			$('#move_local').val("Put it in "+geoloc.str);
			$('#move_local').show();
			autoDetected = geoloc.loc;
		}
	}
	current = geoloc.loc;

}

function resetSpill() {
	spill.moveTo(current, original);
	spill.centerAndZoom(map);
	spill.draw(map);
	current = original;
}

function moveSpill() {
	geoloc.find($('#geolocInput').val());	
}

function moveSpillLocal() {
	spill.moveTo(current, autoDetected);
	spill.centerAndZoom(map);
	spill.draw(map);
	current = autoDetected;
}
