/////////////////////////////////////////////////////////////////////////////////////////////
//
//  4CULTURE public art map
//	
var map;
var mapElement;
var pLon=-122.2;
var pLat=47.68;
var zoom=9;
var markers;
var xmlData;
var client;
var quadrant='all';
var id=0;
var address='';
var baseURL='';//http://www.4culture.org/publicart.net/';

/////////////////////////////////////////////////////////////////////////////////////////////
//
//  INIT APP
//
function init() {
	preload=['all','seattle','nw','ne','sw','se'];
	for(i=0; i<preload.length; i++) {
		img=new Image();
		img.src='graphics/map/map_tabs_'+preload[i]+'_on.gif';
	}

	mapElement=document.getElementById("map_canvas")
	map = new GMap2(mapElement);
	map.setCenter(new GLatLng(pLat, pLon),parseInt(zoom,11));
	
	bubble=document.getElementById("map_bubble");
	//bubble.parentNode.removeChild(bubble);
	//var pane=map.getPane(G_MAP_FLOAT_PANE);
	//pane.appendChild(bubble);
	
	geocoder = new GClientGeocoder();

	//GEvent.addListener(map, "dragend", showDebug);
	//GEvent.addListener(map, "zoomend", showDebug);
	GEvent.addListener(map, "movestart", CloseBubble);
	//GEvent.addListener(map, "moveend", ShowDebug);
	GEvent.addListener(map, "click", CloseBubble);	
	
	if (window.location.search) {
		var query=window.location.search.substring(1);
		var pairs=query.split("&");
		for (var i=0; i<pairs.length; i++) {
			var vals=pairs[i].split("=");
				if (vals[0]=='q') {
					quadrant=vals[1];	
				}
				else if (vals[0]=='id') {
					id=vals[1];
				}
				else if (vals[0]=='address') {
					address=vals[1];
				}
			}
		}
	
	
	tab=document.getElementById('map_tab_'+quadrant.toLowerCase());
	// need IE fix
	tab.style.background='url(graphics/map/map_tabs_'+quadrant.toLowerCase()+'_on.gif)';
	
	
	Location();
	LoadData();
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  SET QUADRANT
//
function SetQuadrant(q) {
	location.href='?q='+q;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  ZOOM IN
//
function ZoomIn() {
	SetZoom(map.getZoom()+1);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  ZOOM OUT
//
function ZoomOut() {
	SetZoom(map.getZoom()-1);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  SET ZOOM
//
function SetZoom(z) {
	zoom=Math.min(15,Math.max(8,z));
	map.setZoom(zoom);
	m=document.getElementById('map_zoom_marker');
	m.style.top=(128-(zoom-8)*15)+'px';
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  INIT GALLERY STRIP
//
function initGallery() {
	gallery=document.getElementById("map_gallery_content");
	var count=0;
	for (var i=0; i<markers.length; i++) {
			
		if (quadrant!='all') {
			if (markers[i].getAttribute('quadrant')!=quadrant) continue;
		}
		
		if ( ! GetValue('lon',i) || GetValue('lon',i)==0 ) continue;
		count++;
		
		var link=document.createElement("a");
		link.href='javascript:LoadProject('+i+')';
		link.title="View more details";
		link.style.display='block';
		var img=document.createElement("img");
		img.src=baseURL+markers[i].getElementsByTagName('img')[0].getAttribute('src');
		img.border=0;
		img.width=120;
		img.height=120;
		link.appendChild(img);
		
		var link2=document.createElement("a");
		link2.href='javascript:LoadProject('+i+')';
		link2.title=GetValue('title',i);
		link2.setAttribute('class','map_gallery_link');
		link2.className='map_gallery_link';
		link2.style.color='#3a2121';
		var text2=document.createTextNode(GetValue('title',i));
		link2.appendChild(text2);
		
		var div=document.createElement("div");
		div.setAttribute('class','map_gallery_item');
		div.setAttribute('id','map_gallery_'+i);
		div.className='map_gallery_item';		
		div.appendChild(link);
		div.appendChild(link2);
		gallery.appendChild(div);

	
	}
	gallery.style.width=((count+1)*130-60)+'px';
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  INIT MAP MARKERS
//
function initMap() {
	map.clearOverlays();
	minLon=minLat=99999999;
	maxLon=maxLat=-99999999;
	for (i=0; i<markers.length; i++) {
		if (quadrant!='all') {
			if (markers[i].getAttribute('quadrant') != quadrant) continue;
		}
		
		lon=parseFloat(GetValue('lon',i));
		if (lon>0) lon=-lon;
		lat=parseFloat(GetValue('lat',i));
		if (lon!=null && lat!=null && lon!=0 && lat!=0) {
			if (lon<minLon) minLon=lon;
			if (lon>maxLon) maxLon=lon;
			if (lat<minLat) minLat=lat;
			if (lat>maxLat) maxLat=lat;
			
			pos=new GLatLng(lat,lon);
			if (pos.lat()) {
				var icon=new Icon(i,pos,'#ff0000');
				map.addOverlay(icon);
			}
		}
	}
	
	if (quadrant=='Seattle') {
		map.setCenter(new GLatLng(47.6011529,-122.329719),14);
		SetZoom(14);
	} else {
		var markerBounds=new GLatLngBounds(new GLatLng(minLat,minLon),new GLatLng(maxLat,maxLon));
		var zoom=map.getBoundsZoomLevel(markerBounds);
		map.setCenter(markerBounds.getCenter(),zoom);
		SetZoom(zoom);
	}

}

function GetValue(val,index) {
	var result=markers[index].getElementsByTagName(val)[0];
	if (result) result=result.firstChild;
	if (result) result=result.nodeValue;
	return result;
}

function GetValue2(node,val) {
	var result=node.getElementsByTagName(val)[0];
	if (result) result=result.firstChild;
	if (result) result=result.nodeValue;
	return result;
}


/////////////////////////////////////////////////////////////////////////////////////////////
//
//  LOAD XML DATA
//
function LoadData() {
	if (client) client.abort();
	client=GXmlHttp.create();
	client.onreadystatechange = DataLoaded;
	client.open("GET", baseURL+'mapdata.ashx',true);
	client.send(null);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  DATA LOADED
//
function DataLoaded() {
	if (client.readyState==4) {
		xmlData=client.responseXML;
		if (xmlData.documentElement) {
			//document.getElementById('debug').value+="\nData received "+xmlData.documentElement.length+" samples";
			markers2=xmlData.documentElement.getElementsByTagName('project');
			// sort data here
			markers=[];
			for(i=0;i<markers2.length;i++) {
				markers.push(markers2[i]);
			}
			markers.sort(function (a,b) {
				stra=GetValue2(a,'title');
				strb=GetValue2(b,'title');
				if (stra>strb) return 1;
				else if (stra<strb) return -1;
				else return 0;
			});
			//markers=markers2;
			//alert('loaded! '+markers.length +' id: '+id);
			if (address!='') window.location.href='http://maps.google.com/maps?f=d&source=s_d&saddr='+address+'&daddr='+GetValue('address',id)+'&ie=UTF8&t=h&z=7';
			initGallery();
			initMap();
			if (id>0) LoadProjectById(id);
		} else {
			alert('no data!');
		}
	}
}

function RollOver(id,x,y) {
	el=document.getElementById('map_flag');
	if (el) {
		el.style.display='block';
		el.style.zindex='1000';
		el.style.left=x+'px';
		el.style.top=y+'px';
		el.innerHTML=GetValue('title',id);
	}
}

function RollOut() {
	el=document.getElementById('map_flag');
	if (el) {
		el.style.display='none';
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////
//
//  ICON CLASS FOR MAP MARKERS
//
function Icon(id, pos, opt_color) {
	this.id_=id;
	this.pos_=pos;
	this.color_ = opt_color || "#888888";
}

Icon.prototype = new GOverlay();

Icon.prototype.initialize = function(map) {
	
	var link=document.createElement("a");
	link.setAttribute('class','map_icon_link');
	link.href='javascript:LoadProject('+this.id_+')';
	//link.title=GetValue('title',this.id_);
	link.id_=this.id_;

		link.onmouseover=function(e) {
			posx=0;posy=0;
			var e=(!e)?window.event:e;//IE:Moz
			if (e.pageX){//Moz
				posx=e.pageX//+window.pageXOffset;
				posy=e.pageY//+window.pageYOffset;
			}
			else if(e.clientX){//IE
				if(document.documentElement){//IE 6+ strict mode
					posx=e.clientX+document.documentElement.scrollLeft;
					posy=e.clientY+document.documentElement.scrollTop;
				}
				else if(document.body){//Other IE
					posx=e.clientX+document.body.scrollLeft;
					posy=e.clientY+document.body.scrollTop;
				}
			}
			RollOver(this.id_,posx,posy);
		}
		link.onmouseout=function() { RollOut(this.id_); }

	var img=document.createElement("img");
	img.src='graphics/map/map_marker.gif';
	img.border=0;
	link.appendChild(img);
	
	var div=document.createElement("div");
	div.style.position='absolute';
	div.appendChild(link);
	map.getPane(G_MAP_MARKER_PANE).appendChild(div);
	this.map_ = map;
	this.div_ = div;
}

Icon.prototype.remove = function() {
	this.div_.parentNode.removeChild(this.div_);
}

Icon.prototype.copy = function() {
	return new Icon(this.id_, this.pos_, this.color_);
}

Icon.prototype.redraw = function(force) {
	// We only need to redraw if the coordinate system has changed
	if (!force) return;
	var screen = this.map_.fromLatLngToDivPixel(this.pos_);
	this.div_.style.left = (screen.x-5) + "px";
	this.div_.style.top = (screen.y-5) + "px";
}


function LoadProjectById(id) {
	for (var i=0; i<markers.length; i++) {
		if (markers[i].getAttribute('id')==id) {
			LoadProject(i);
			return;
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////
//
//  LOAD A MARKER POPUP BUBBLE
//
function LoadProject(i) {

	var zoom=parseInt(markers[i].getAttribute('zoom'),10);
	if (! zoom) zoom=map.getZoom();
	
	pos=new GLatLng(GetValue('lat',i),GetValue('lon',i));
	map.setCenter(pos,zoom);
	bounds=map.getBounds();
	
	pos=new GLatLng(pos.lat()+(bounds.getNorthEast().lat()-bounds.getSouthWest().lat())/4,GetValue('lon',i));
	
	map.setCenter(pos,zoom);
	SetZoom(zoom);
	
	var screen=map.fromLatLngToDivPixel(pos);
	var mapOffX=parseInt(getLiveStyle(map.getPane(G_MAP_MARKER_PANE).parentNode,'left'));
	var mapOffY=parseInt(getLiveStyle(map.getPane(G_MAP_MARKER_PANE).parentNode,'top'));
	
	bubble.style.left='252px';
	bubble.style.top='215px';
	bubble.style.visibility='visible';
	bubble.style.display='block';
	
	bubbleimg=document.getElementById('map_bubble_image');
	bubbleimg.src=baseURL+markers[i].getElementsByTagName('img')[0].getAttribute('src');
	bubbleimg.width=140;
	
	bubbletitle=document.getElementById('map_bubble_title');
	bubbletitle.innerHTML=GetValue('title',i);

	var coll='collection';
	if (markers[i].getAttribute('type')==2) coll='consulting';
	bubblelocation=document.getElementById('map_bubble_location_text');
	bubblelocation.innerHTML='Location: '+GetValue('address',i)+
	'<p><a href="'+coll+'/profile.aspx?projectID='+markers[i].getAttribute('id')+'">View Project Page</a></p><p>Get Directions - From:</p>'+
	'<form><input type="hidden" name="id" value="'+markers[i].getAttribute('id')+'" /><input type="text" name="address" style="width:130px;" id="map_bubble_address" /><input type="submit" value="Go" /></form>';
	
	el=document.getElementById('map_bubble_learnmore_artist');
	el.innerHTML=GetValue('artist',i);
	el=document.getElementById('map_bubble_learnmore_description');
	el.innerHTML=GetValue('description',i);
	
	
	var url=markers[i].getElementsByTagName('mp3')[0].getAttribute('src');
	var flashvars = { audio:baseURL+url };
	var params = { wmode:'transparent'};
	var attributes = {};
	el=document.getElementById('map_bubble_audio');

	if (url!='') {
		swfobject.embedSWF("graphics/map/mediaplayer.swf", "map_bubble_audio", "89", "191", "9",null, flashvars, params, attributes );
		el.style.display='block';
	} else {
		el.style.display='none';	
	}
	
	Location();
	
	
}

/////////////////////////////////////////////////////////////////////////////////////////////
//
//  LEARN MORE TAB
//
function LearnMore() {
	el=document.getElementById('map_bubble_location');
	el.style.visibility='hidden';
	el=document.getElementById('map_bubble_learnmore');
	el.style.visibility='visible';

	el=document.getElementById('map_bubble_tab2');
	el.style.display='block';
	el=document.getElementById('map_bubble_tab');
	el.style.display='none';
	
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  LOCATION TAB
//
function Location() {
	el=document.getElementById('map_bubble_location');
	el.style.visibility='visible';
	el=document.getElementById('map_bubble_learnmore');
	el.style.visibility='hidden';
	
	el=document.getElementById('map_bubble_tab');
	el.style.display='block';
	el=document.getElementById('map_bubble_tab2');
	el.style.display='none';

	
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  CLOSE POPUP BUBBLE
//
function CloseBubble() {
	bubble.style.display='none';
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
//  GET LIVE STYLE
//
function getLiveStyle(el, cssprop) {
	if (el.currentStyle) {
		if (cssprop=='width') return el.offsetWidth;
		else return el.currentStyle[cssprop];
	}
	else if (document.defaultView && document.defaultView.getComputedStyle) return document.defaultView.getComputedStyle(el, "")[cssprop]
	else return el.style[cssprop];
}

init();

