// Markers
var mapMarkers = {
	'New York' : {
		latitude	: 40.702749,
		longitude	: -73.98954,
		zoom		: 16,
		zipcode		: '11201-1070'
	},
	'Maryland' : {
		latitude	: 39.170363,
		longitude	: -76.808038,
		zoom		: 12,
		zipcode		: '21046-3427'
	}
}

// Default location / zoom
var mapDefaults = {
	latitude	: 39.952385,
	longitude	: -75.162277,
	zoom		: 6,
	dirLabel	: 'Get directions from'
}


// main

var map, map_overlay=null, map_default;

TextResizeDetector.TARGET_ELEMENT_ID = 'masthead';
TextResizeDetector.USER_INIT_FUNC = resizeInit;

function resizeInit() {
	var iBase=TextResizeDetector.addEventListener(onFontResize,null);
}

function onFontResize(e,args) {
	if(typeof map=='object'){
		map.checkResize();
		map.setCenter(map.center);
	}
	if(map_overlay!=null) map_overlay.redraw(true);
}

function addLoadEvent(func) {
	var oldonload=window.onload;
	if (typeof window.onload!='function') window.onload=func;
	else{
		window.onload=function(){
			oldonload();
			func();
		}
	}
}

function createElement(element) {
	if (typeof document.createElementNS!='undefined') return document.createElementNS('http://www.w3.org/1999/xhtml',element);
	if (typeof document.createElement!='undefined') return document.createElement(element);
	return false;
}

function insertAfter(newElement,targetElement) {
	var parent=targetElement.parentNode;
	if (parent.lastChild==targetElement) parent.appendChild(newElement);
	else parent.insertBefore(newElement,targetElement.nextSibling);
}

function stopDefaultEvent(e) {
	if(window.event){
		window.event.cancelBubble=true;
		window.event.returnValue=false;
	}
	if (e&&e.preventDefault&&e.stopPropagation){
		e.preventDefault();
		e.stopPropagation();
	}
}



/* --- Google Maps functions ---
*/

function initMap() {
	setTimeout("if(typeof GMap2!='undefined') loadMap();",10);
}

function loadMap() {
	if (
		!GBrowserIsCompatible()
		|| !(document.createElementNS || document.createElement)
		|| !document.createTextNode
		|| !(typeof mapMarkers == 'object')
		) return false;

	// try to get map elements
	var elMap=getMapElement("map");

	// create map
	map=new GMap2(elMap);
	if(!map) return false;

	// load event for keyboard accessibility patch
	GEvent.addDomListener(map, "load", function() { setTimeout('GKeyboardPatch(map);',3000); });

	// add controls
	map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_LEFT));
	map.addControl(new GMapTypeControl());

	// setting
	//map.disableDoubleClickZoom();

	// center map on Philadelphia
	map_default=new GLatLng(mapDefaults.latitude,mapDefaults.longitude);
	map.setCenter(map_default,mapDefaults.zoom);
	map.center=map.getCenter();

	// additional keyboard accessibility once map is focused
	new GKeyboardHandler(map);

	// add markers
	var mapHtml;
	for (m in mapMarkers) {
		// set html
		mapHtml='<div id="map-bubble">';

		mapHtml += '<div id="bubble-top">';
		mapHtml += '<h2><em>'+m+'</em> <img src="/i/presentation/ico16-close.gif" alt="Close" title="Close this" onclick="closeOverlay()" /></h2>';
		mapHtml += '</div>';

		mapHtml += '<div id="bubble-content"><form method="get" action="http://maps.google.com/maps">';
		mapHtml += '<p><label for="saddr">'+mapDefaults.dirLabel+': </label><input class="text" type="text" id="saddr" name="saddr" value="" /><input type="hidden" name="daddr" value="' + mapMarkers[m].zipcode + '" /><input type="hidden" name="hl" value="en" /><input class="submit" type="submit" value="Go" /></p>';
		mapHtml += '</form></div>';

		mapHtml += '</div>';

		mapMarkers[m].html=mapHtml;

		// set position
		mapMarkers[m].latlng=new GLatLng(parseFloat(mapMarkers[m].latitude),parseFloat(mapMarkers[m].longitude));

		// create and add marker
		mapMarkers[m].marker=new GMarker(mapMarkers[m].latlng,createIcon());
		mapMarkers[m].marker.value=m;
		map.addOverlay(mapMarkers[m].marker);

		// add overlay onclick
		GEvent.addListener(mapMarkers[m].marker,'click',procMarker);

		GEvent.addListener(map,"zoomend",function()
		{
			if(map_overlay!=null) map_overlay.redraw(true);
		});

	};

	// jQuery
	$(document).ready(function(){
		if(!map) return;
		$('#new-york h2 a').attr('href','javascript:;').click(function(){
			procMarker(0);
		});
		$('#maryland h2 a').attr('href','javascript:;').click(function(){
			procMarker(1);
		});
	});

	return true;
}

function getMapElement(id) {
	var elMap=document.getElementById(id);
	if(!elMap) return false;
	while(elMap.hasChildNodes()) elMap.removeChild(elMap.firstChild);
	return elMap;
}

function createIcon() {
	var icon=new GIcon();
	icon.image="http://s.omniti.net/i/presentation/exp32-map.png";
	icon.shadow="http://s.omniti.net/i/presentation/ico32-shadow.png";
	icon.iconSize=new GSize(32, 32);
	icon.shadowSize=new GSize(32, 32);
	icon.iconAnchor=new GPoint(32, 25);
	icon.infoWindowAnchor=new GPoint(5, 1);
	return icon;
}

function procMarker(i) {
	if(i==null||typeof i=='object') i=this.value;
	if(map_overlay==null){
		openOverlay(i);
	}else{
		var j=map_overlay.value;
		closeOverlay();
		if(i!=j) openOverlay(i);
	}
}

function openOverlay(m) {
	map.setCenter(mapMarkers[m].latlng, mapMarkers[m].zoom);
	map.center=map.getCenter();
	map_overlay=new Omnilay(map,mapMarkers[m].latlng,mapMarkers[m].html);
	map_overlay.value=m;
	map_overlay.initialize();

	// jQuery
	$('#saddr').attr('value',mapDefaults.dirLabel+'...').focus(function(){
		if(this.value==mapDefaults.dirLabel+'...') this.select();
	}).blur(function(){
		if(this.value=='') this.value=mapDefaults.dirLabel+'...';
	})
	$('#bubble-content form').submit(function(){
		if($('#saddr').attr('value')==mapDefaults.dirLabel+'...') $('#saddr').attr('value','');
		//this.submit();
	});

	map_overlay.redraw(true);
}

function tweakLatLng(l,x,y) {
	var c=map.fromLatLngToDivPixel(l);
	c.x+=parseFloat(x);
	c.y+=parseFloat(y);
	return map.fromDivPixelToLatLng(c);
}

function closeOverlay() {
	map_overlay.remove();
	map_overlay=null;
}

function focusDirections(e) {
	document.getElementById('saddr').focus();
}

// keyboard accessibility patch, http://dev.opera.com/articles/view/keyboard-accessible-google-maps/
function GKeyboardPatch(map) {
	var button, button_style = 'width:100%;height:100%;padding:2px;margin:2px;background:transparent;border-width:0px;border-style:solid;cursor:pointer;overflow:hidden;text-indent:-100em;position:absolute;top:-2px;left:-2px;';
	var divs = map.getContainer().getElementsByTagName('DIV');
	for (var i = 0; i < divs.length; i++) {
		if ( divs[i].getAttribute('log') || ( divs[i].getAttribute('id') && (divs[i].getAttribute('id')!='map_magnifyingglass') ) ) {
			button = document.createElement("BUTTON");
			button.setAttribute('value',divs[i].getAttribute('title'));
			// proper W3C DOM methods for styling
			button.setAttribute('style',button_style);
			// ...and now to make it work in IE
			button.style.cssText = button_style;
			divs[i].appendChild(button);
			if (divs[i].getAttribute('log')) { // only control buttons
				// override the IE opacity filter that Google annoyingly sets
				divs[i].style.filter = '';
				// should really set to 'transparent'
				divs[i].style.background = 'url(http://www.google.com/intl/en_ALL/mapfiles/transparent.png)';
			}
		}
	}
}

addLoadEvent(initMap);

window.onunload=function() {
	if(typeof GUnload!='undefined') GUnload();
}


// overlay

function Omnilay(_map,_latlng,_html,_xo,_yo)
{
	this.map=_map;
	this.latlng=_latlng;
	this.html=_html;
	this.xo=_xo || 0;
	this.yo=_yo || 0;
}

Omnilay.prototype=new GOverlay();

Omnilay.prototype.initialize=function()
{
	var pane=this.map.getPane(G_MAP_FLOAT_PANE);
	pane.innerHTML=this.html;
	var ediv=pane.getElementsByTagName("div");
	if (!ediv) return;
	if (ediv.length) ediv=ediv[0];
	ediv.style.position="absolute";
	this.ediv=ediv;
	GEvent.addDomListener(document.getElementById('saddr'), "click", focusDirections);
}

Omnilay.prototype.redraw=function(force)
{
	if(!force) return;
	var p=this.map.fromLatLngToDivPixel(this.latlng);
	var xo,yo;
	xo=this.xo;
	yo=this.yo;
	this.ediv.style.left=p.x + xo + "px";
	this.ediv.style.bottom=- p.y + yo + "px";
}

Omnilay.prototype.remove=function()
{
	this.ediv.parentNode.removeChild(this.ediv);
}

