var map;
var vodKMLman;
var homeKMLman;
var bcmarkers = new Array();
var allbcmarkers = new Array();
var bcmarkercache = new Array();
var oldbcmarkers = new Array();
var marking = false;
var mcnt = 0;
var bcloader;
var defaultZoomLevel = 4;
var maxLat;
var maxLng;
var minLat;
var minLng;
var minDefaultZoom;
var worldViewCenter = new GLatLng( 10, 17);
var worldViewZoom = 1;
var geocoder = new GClientGeocoder();
var liveHTML;
var recentVideosHTML;
var popularBroadcastersHTML;
var popularVideosHTML;
var locator;
var locatorTracker;

var noLiveHTML ='<div style="text-align:center;padding-right:20px;">';
  noLiveHTML += '<h2>No Live Broadcasters.</h2><i>Use the map to find videos<br/>';
  noLiveHTML += '&amp; broadcasters, ';
  noLiveHTML += '<a href="javascript:void(0);" onclick="showMapHelp();">click here for help</a>.</i><br/></div>';

  
var introLiveHTML ='<div style="text-align:center;padding-right:20px;">';
  introLiveHTML += '<h2>Live Broadcasters.</h2><i>Use the map to narrow selection and navigate, ';
  introLiveHTML += '<a  href="javascript:void(0);" onclick="showMapHelp();">click here for help</a>.</i></div>';

var introBroadcastersHTML ='<div style="text-align:center;padding-right:20px;">';
  introBroadcastersHTML += '<h2>Broadcasters</h2>';
  introBroadcastersHTML += '<i>Use the map to find broadcasters, ';
  introBroadcastersHTML += '<a  href="javascript:void(0);" onclick="showMapHelp();">click here for help</a>.</i><br/></div>';

var introVideosHTML ='<div style="text-align:center;padding-right:20px;">';
  introVideosHTML += '<h2>Videos</h2>';
  introVideosHTML += '<i>Use the map to find videos around the world, ';
  introVideosHTML += '<a  href="javascript:void(0);" onclick="showMapHelp();">click here for help</a>.</i><br/></div>';



function loadMap() {
 if (GBrowserIsCompatible()) {
        map = new GMap2($("google-map"));
		
		recentVideosHTML = $('recent-videos').innerHTML;
		popularVideosHTML = $('popular-videos').innerHTML;
		popularBroadcastersHTML = $('popular-broadcasters').innerHTML;
		
		//set up kml manager
		map.getInfoWindow();
		vodKMLman = new KMLManager(this.map,'vod_v1',false);
		homeKMLman = new KMLManager(this.map,'bchomev00001',false);
		
        map.setCenter(new GLatLng(37,-97.5),defaultZoomLevel, G_HYBRID_MAP);
        GEvent.addListener(this.map, "infowindowopen", updateInfo);
		map.addControl( new GLargeMapControl() );
		map.addControl(new ContentSwapControl());
		map.addControl(new HelpControl());
		
		this.map.addControl(new ContinentQuickZoom());
		loadLive();

	}
}
   
/*
function activateLocator(lat,lng) {
	if (locator) {
		locator.setLatLng( new GLatLng(lat,lng) );
		locatorTracker.enable();
		locator.show();
	} else {
		var locatorIcon = new GIcon( G_DEFAULT_ICON );
	    locatorIcon.image = 'http://s3.amazonaws.com/seerowww/fire_throb.gif';
	    locatorIcon.iconSize = new GSize(32,32);
	    locatorIcon.iconAnchor = new GPoint(16,16);
	    locator = new GMarker( new GLatLng(lat, lng) , locatorIcon);
		var opts = { weight: 10, length: 20 };
		locatorTracker = new MarkerTracker(locator, map, opts);
		map.addOverlay(locator);
	}
}

function disableLocator() {
	if (locator) {
		locatorTracker.disable();
		locator.hide();
	}
}
*/

function visitPlace(place) {
  $('visit-input').value=place;
  geocoder.getLatLng(place,
    	function(loc) {
      		if (!loc) {
        		alert("'"+place+"' was not found or is not specific enough, please try again.");
      		} else {
				clearBCMarkers();
				vodKMLman.enable();
				homeKMLman.disable();
				$('liveControl').style.textDecoration = 'none';
				$('broadcastersControl').style.textDecoration = 'none';
				$('videosControl').style.textDecoration = 'underline';
	      		zoomto(loc.lat(),loc.lng(),6);
      		}
    	}
  );
}


function visitOnEnter(e) {
  if (window.event && window.event.keyCode == 13) {
	visitPlace($('visit-input').value);
  } else if (e && e.which == 13) {
    visitPlace($('visit-input').value);
  }
  return true;
}

function loadBCMarkers() {
	bcloader = null;
	bcloader = new Ajax.Request('/query/fetchBCs.php', {
    	method: 'get',
		evalScripts: true,
		onComplete: function(transport) {
			try {
				if (window.ActiveXObject) {
					// code for IE
					var doc = new ActiveXObject("Microsoft.XMLDOM");
					doc.async="false";
					doc.loadXML(transport.responseText);
				} else {
					// code for Mozilla, Firefox, Opera, etc.
					var parser=new DOMParser();
					var doc=parser.parseFromString(transport.responseText,"text/xml");
				}
				refreshMarkers(doc);
				//purge(doc);
				delete doc;
				//purge(transport);
				delete transport;
			} catch(e) {
				//window.setTimeout( function() { loadBCMarkers(); }, bcRefreshTime);
				//alert(e.name+':'+e.message);
			}
			delete this;
		}
	});
}


function pointsRClose(pnt1,pnt2) {
	if (Math.abs(pnt1.lat() - pnt2.lat()) > 0.0001) {
		return false; 
	} else if (Math.abs(pnt1.lng() - pnt2.lng()) > 0.0001) {
		return false;
	}	
	return true;
};


function refreshMarkers(response) {
	if (!marking) {
		marking=true;
		oldbcmarkers = bcmarkers;
		//delete bcmarkers;
		bcmarkers = new Array();
		var v = response.documentElement.getElementsByTagName('bc');
	    mcnt=0;
	    liveHTML = introLiveHTML+'<ul>';
	    
		var foundCurLive = false;
		for(var i = 0; i < v.length; i++) {
			
			var mlat = v[i].getElementsByTagName('latitude')[0].firstChild.nodeValue;
			var mlng = v[i].getElementsByTagName('longitude')[0].firstChild.nodeValue;
			if (mcnt == 0) {
				maxLat = mlat;
				minLat = mlat;
				maxLng = mlng;
				minLng = mlng;
			} else {
				maxLat = Math.max(maxLat,mlat);
				minLat = Math.min(minLat,mlat);
				maxLng = Math.max(maxLng,mlng);
				minLng = Math.min(minLng,mlng);
			}
			var mheading = v[i].getElementsByTagName('bcheading')[0].firstChild.nodeValue;
			var mtit = v[i].getElementsByTagName('title')[0].firstChild.nodeValue;
			var mcit = v[i].getElementsByTagName('city')[0].firstChild.nodeValue;
			var mreg = v[i].getElementsByTagName('region')[0].firstChild.nodeValue;
			var mcou = v[i].getElementsByTagName('country')[0].firstChild.nodeValue;
			var bc_id = v[i].getElementsByTagName('bc_id')[0].firstChild.nodeValue;
			var mthm = v[i].getElementsByTagName('thumb')[0].firstChild.nodeValue;		
			var descrip = v[i].getElementsByTagName('profile_text')[0].firstChild.nodeValue;
			if ( descrip.length > 100) {
				descrip = descrip.substring(0,97)+'...';
			};

			var infoHTML = '<li><a href=\'/broadcaster/'+mtit+'\' style=\'color:rgb(67, 81, 92);\'>';
				infoHTML +='<div style=\'padding: 10px 5px 10px 0px;height=66px;\'>';
	   			infoHTML +='<img align="left" src=\''+mthm+'\'alt=\''+bc_id+'\'';
	   			infoHTML +='width=\'60\' height=\'60\' class=\'img-broadcaster\' style=\'background-color:#FFFFFF;border:1px solid #999999;padding: 4px;margin: 0px 4px 0px 4px;\'/>';
	   			infoHTML +='<span style=\'font-size:16px;font-weight:bold;color:#43515C;line-height:18px;\'>'+mtit+'</span><br/>';
	   			infoHTML +='<span class=\'loc\' style=\'font-size:12px;color:#888888;\'>From:<br/>'+mcit+', '+mreg+',<br/>'+mcou+'</span><br/>';  			
	   			infoHTML +='<img src=\'http://s3.amazonaws.com/seerowww/sep.gif\'/>';
	   			infoHTML +='</div><div>'+descrip+'</div></a></li>';
			
			liveHTML += infoHTML;
			
			if (allbcmarkers.indexOf(mtit) < 0 ) {
				//new marker needs to be created
				bcmarkercache[mtit]=createMarker(new GLatLng(mlat,mlng),mtit,"bc"+mheading,infoHTML);
				map.addOverlay(bcmarkercache[mtit]);
				allbcmarkers.push(mtit);
			} else {
				//change location
				var pnt;
				//eval('pnt = bcm_'+mtit+'.getLatLng();');
				pnt = bcmarkercache[mtit].getLatLng();
				var pnt2 = new GLatLng(mlat,mlng);
				var closetob4 = pointsRClose( pnt , pnt2 );
				//do heading
				if (!closetob4) {
					bcmarkercache[mtit].setPoint(new GLatLng(mlat,mlng));
					if (curInfoWindow == mtit && !map.getInfoWindow().isHidden()) {
						map.getInfoWindow().hide();
						bcmarkercache[mtit].openInfoWindow(infoHTML);
					}
				}
				if (oldbcmarkers.indexOf(mtit) < 0 ) {
					//already created but not displayed
					map.addOverlay(bcmarkercache[mtit]);
				}
				if (mheading == "N") {
					bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster_N.png");
				} else if (mheading == "NW") {
					bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster_NW.png");
				} else if (mheading == "W") {
					bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster_W.png");
				} else if (mheading == "SW") {
					bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster_SW.png");
				} else if (mheading == "S") {
					bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster_S.png");
				} else if (mheading == "SE") {
					bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster_SE.png");
				} else if (mheading == "E") {
					bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster_E.png");
				} else if (mheading == "NE") {
					bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster_NE.png");
				} else {
					//bcmarkercache[mtit].setImage("http://s3.amazonaws.com/seerowww/broadcaster.png");
				}
			}
			bcmarkers.push(mtit);
			mcnt++;
		}
		//remove overlays not on the map
		for (var j = 0; j < oldbcmarkers.length; j++) {
			if (oldbcmarkers.length > 0) {
				if (bcmarkers.indexOf(oldbcmarkers[j]) < 0 ) {
					//hide the marker
		    		map.removeOverlay(bcmarkercache[oldbcmarkers[j]]);
		    		oldbcmarkers[j]=null;
				}
			}
		}
		
	    liveHTML = liveHTML+'</ul>';
		if (mcnt == 0 ) {
			vodKMLman.enable();
			$('liveControl').style.textDecoration = 'none';
			$('videosControl').style.textDecoration = 'underline';
			$('infoPanel').update(noLiveHTML+recentVideosHTML);
			$('infoPanel').scrollTop = 0;
		} else if (mcnt == 1) {
			$('liveControl').style.textDecoration = 'underline';
			map.setCenter( new GLatLng( maxLat, maxLng ) );
			$('infoPanel').update(liveHTML+recentVideosHTML);
			$('infoPanel').scrollTop = 0;
		} else {
			$('liveControl').style.textDecoration = 'underline';
			reloadMap(minLat, minLng, maxLat, maxLng);
			$('infoPanel').update(liveHTML+recentVideosHTML);
			$('infoPanel').scrollTop = 0;
		}
		marking=false;
	}
};


function clearBCMarkers() {
	//remove overlays not on the map
	for (var j = 0; j < bcmarkers.length; j++) {
		if (bcmarkers.length > 0) {
			//hide the marker
			map.removeOverlay(bcmarkercache[bcmarkers[j]]);
			bcmarkers[j]=null;
		}
	}
	delete(bcmarkers);
	bcmarkers = new Array();
};


function createMarker(point,title,type,infoHTML)  {
	if (infoHTML == null) {
		infoHTML="";
	} 	
	var m;
	m = new GMarker(point, new GIcon(G_DEFAULT_ICON));
	if (type.substring(0,2) == 'bc') {
		if (type.substring(2,4) == "N") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster_N.png";
		} else if (type.substring(2,4) == "NW") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster_NW.png";
		} else if (type.substring(2,4) == "W") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster_W.png";
		} else if (type.substring(2,4) == "SW") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster_SW.png";
		} else if (type.substring(2,4) == "S") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster_S.png";
		} else if (type.substring(2,4) == "SE") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster_SE.png";
		} else if (type.substring(2,4) == "E") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster_E.png";
		} else if (type.substring(2,4) == "NE") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster_NE.png";
		} else {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/broadcaster.png";
		}
		m.getIcon().iconSize = new GSize(30, 36);
		m.getIcon().iconAnchor = new GPoint(15,32);
		m.getIcon().shadowSize = new GSize(40, 22);
		m.getIcon().shadow = "http://s3.amazonaws.com/seerowww/broadcaster_shad.png"; 	 
		GEvent.addListener(m, "click", function() {
			$('infoPanel').update(introLiveHTML +'<ul>'+infoHTML+'</ul>');
			curInfoWindow=title;
			$('infoPanel').scrollTop = 0;
		});
	} else {	
		GEvent.addListener(m, "click", function() {
			$('infoPanel').update(introLiveHTML +'<ul>'+infoHTML+'</ul>');
			curInfoWindow=title;
			$('infoPanel').scrollTop = 0;
		});
	}
	return m;
};


// this spits out the default style for these buttons
function getStandardButton() {
	var button = document.createElement("div");
	button.style.display = "inline";
	button.style.borderRight = "1px solid #888";
	button.style.borderLeft = "1px solid #000";
	button.style.borderBottom = "1px solid #888";
	button.style.width = "120px";
	button.style.paddingRight = "12px";
	button.style.paddingLeft = "12px";
	button.style.textAlign = "center";
	
	GEvent.addDomListener(button, "mouseover", function() {
		button.style.background='#FFFF88';
	});
	GEvent.addDomListener(button, "mouseout", function() {
		button.style.background='#FFFFFF';
	});
	GEvent.addDomListener(button, "mousedown", function() {
		button.style.background='#E0F0F5';
	});
	GEvent.addDomListener(button, "mouseup", function() {
		button.style.background='#FFFF88';
	});
	return button;
}

// add the auto track toggle control
function ContinentQuickZoom() {
};


ContinentQuickZoom.prototype = new GControl();
ContinentQuickZoom.prototype.initialize = function(map) {

	var container = document.createElement("div");
	container.style.border = "1px solid black";
	container.style.color = "black";
	container.style.cursor = "pointer";
	container.style.background = "white";
	container.style.textAlign = "center";
	
	var NAmerica = getStandardButton();
	NAmerica.style.borderLeft = "0px";
	container.appendChild(NAmerica);
	NAmerica.appendChild(document.createTextNode("N.America"));
	GEvent.addDomListener(NAmerica, "click", function() {
		zoomto(42.0,-95.0,3);
	});
	
	var SAmerica = getStandardButton();
	container.appendChild(SAmerica);
	SAmerica.appendChild(document.createTextNode("S.America"));
	GEvent.addDomListener(SAmerica, "click", function() {
		zoomto(-22.0,-64.0,3);
	});
	
	var Europe = getStandardButton();
	container.appendChild(Europe);
	Europe.appendChild(document.createTextNode("Europe"));
	GEvent.addDomListener(Europe, "click", function() {
		zoomto(48.0,14.0,4);
	});
	
	var Africa = getStandardButton();
	container.appendChild(Africa);
	Africa.appendChild(document.createTextNode("Africa"));
	GEvent.addDomListener(Africa, "click", function() {
		zoomto(3.0,25.0,3);
	});
	
	var Asia = getStandardButton();
	container.appendChild(Asia);
	Asia.appendChild(document.createTextNode("Asia"));
	GEvent.addDomListener(Asia, "click", function() {
		zoomto(40.0,95.0,3);
	})
	
	var Australia = getStandardButton();
	container.appendChild(Australia);
	Australia.appendChild(document.createTextNode("Australasia"));
	GEvent.addDomListener(Australia, "click", function() {
		zoomto(-22.0,135.0,3);
	});
	
	map.getContainer().appendChild(container);
	return container;
};
ContinentQuickZoom.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(100, 15));
};


// add the content tabs
function ContentSwapControl() {
};

ContentSwapControl.prototype = new GControl();
ContentSwapControl.prototype.initialize = function(map) {

	var container = document.createElement("div");
	container.style.border = "1px solid black";
	container.style.color = "black";
	container.style.cursor = "pointer";
	container.style.background = "white";
	container.style.textAlign = "center";
	container.style.fontWeight = "bold";
	container.style.fontSize = "14px";
	
	var Live = getStandardButton();
	container.appendChild(Live);
	Live.id = 'liveControl';
	Live.style.borderLeft = "0px";
	Live.appendChild(document.createTextNode("Live!"));
	GEvent.addDomListener(Live, "click", function() {
		Live.style.textDecoration = "underline";
		Broadcasters.style.textDecoration = "none";
		Videos.style.textDecoration = "none";
		loadLive();
	});
		
	var Broadcasters = getStandardButton();
	container.appendChild(Broadcasters);
	Broadcasters.id = 'broadcastersControl';
	Broadcasters.appendChild(document.createTextNode("Broadcasters"));
	GEvent.addDomListener(Broadcasters, "click", function() {
		Broadcasters.style.textDecoration = "underline";
		Videos.style.textDecoration = "none";
		Live.style.textDecoration = "none";
		loadHome();
	});
	var Videos = getStandardButton();
	container.appendChild(Videos);
	Videos.id = 'videosControl';
	Videos.appendChild(document.createTextNode("Videos"));
	GEvent.addDomListener(Videos, "click", function() {
		Videos.style.textDecoration = "underline";
		Broadcasters.style.textDecoration = "none";
		Live.style.textDecoration = "none";
		loadVideos();
	});
	
	var Help = getStandardButton();
	container.appendChild(Help);
	Help.id = 'helpControl';
	Help.appendChild(document.createTextNode("?"));
	GEvent.addDomListener(Help, "click", function() {
		showMapHelp();
	});
	
	
	map.getContainer().appendChild(container);
	return container;
};
ContentSwapControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(15, 15));
};

// add the help tabs
function HelpControl() {
};

HelpControl.prototype = new GControl();
HelpControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	container.id = 'mapHelpPane';
	container.innerHTML = "<img src='/images/home_map_help.gif'/>";
	container.style.display = 'none';
	GEvent.addDomListener(container, "click", function() {
		$('mapHelpPane').style.display = 'none';
	});
	map.getContainer().appendChild(container);
	return container;
};
HelpControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(60, 60));
};

function showMapHelp() {
	$('mapHelpPane').style.display = 'block';
}

function zoomto(lat,lng,zoom) {
	if ( !zoom ) {
		this.map.setCenter(new GLatLng(lat,lng), this.map.getZoom() + 2 );
	} else {
		this.map.setCenter(new GLatLng(lat,lng), parseFloat(zoom));
	}
};

function loadHome() {
	clearBCMarkers();
	vodKMLman.disable();
	homeKMLman.enable();
	$('infoPanel').update(introBroadcastersHTML+popularBroadcastersHTML);
	$('infoPanel').scrollTop = 0;
}

function loadVideos() {
	clearBCMarkers();
	homeKMLman.disable();
	vodKMLman.enable();
	$('infoPanel').update(introVideosHTML+popularVideosHTML);
	$('infoPanel').scrollTop = 0;
}


function loadLive() {
	vodKMLman.disable();
	homeKMLman.disable();
	loadBCMarkers();
}


function reloadMap(lat1, lng1, lat2, lng2) { 
	var sw = new GLatLng(lat1, lng1); 
	var ne = new GLatLng(lat2, lng2); 
	var bounds = new GLatLngBounds(sw, ne); 
	level  = map.getBoundsZoomLevel(bounds);
	if ( level <= 1 ) {
		map.setCenter(worldViewCenter, worldViewZoom);
	} else {
		map.setCenter(new GLatLng(0.5*lat1+0.5*lat2, 0.5*lng1+0.5*lng2), level); 
	}
} 


function link2js(link) {
	link = link.split('?');
	if (link.length > 1) {
		link = link[1].split('&');
		var js = '';
		var i=0;
		for (i=0 ; i < link.length; i=i+1) {
			var str = link[i].split('='); 
			var param = "'"+str[1].split(',').join("','")+"'";
			js +=str[0]+'('+param+');';
		}
	} else {
		js = link+'();';
	}
	return(js);
}


function updateInfo() {	
	iw = map.getInfoWindow();
	map.panTo(iw.getPoint());
	var el;
	//if ( el  = document.getElementById('iwsw')) {
	if ( el  = document.getElementById('iw_kml')) {

		links = el.getElementsByTagName('a');
		var i=0;
		for (i=0 ; i < links.length; i=i+1) {
			link = links[i].getAttribute('href') ;
			if ( link != null ) {
				var zoomRE = /zoomto/g;
				if ( link.search(zoomRE) != -1 ) {
					links[i].setAttribute('onclick',link2js(link));
					links[i].removeAttribute('href');
				}
				links[i].setAttribute('target','_self');
			}
		}
        $('infoPanel').update(el.innerHTML);
        $('infoPanel').scrollTop = 0;
        //iw.hide();
	}

	return false;
}
