///// Initialize  ////
var xmlhttpGPS;
var xmlhttpAd;
var xmlhttpMarker;
var curLat;
var curLng;
var curAdID;
var curAdLng;
var curAdLat;
var curAdDesc;
var geoType = 'static';
var map;
var mcnt = 0;
var bcloader;
var adloader;
var adMarker;
var adTrack;
var ghostcasticon;
var tempmark;
var bcmarkers = new Array();
var allbcmarkers = new Array();
var bcmarkercache = new Array();
var curInfoWindow = '_';
var marking = false;
var adInitDelay = 2000;
var adRefreshTime = 60000;
var bcRefreshTime = 5000;
var focusZoom = 14;
var minFocusZoom = 14;
var liveStaticZoom = 12;
var liveDynamicZoom = 17;
var homeZoom = 12;
var autoTrack = true;
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var live;
var home_lat;
var home_lng;
var tlastad;
var autoRecLive;
var connLive;
var	ghostcasting = false;
var swfReady = false;

///// SEERO MAP FUCNTIONS /////
function updateSeeroMap(lat,lng,zoom,force) {
	if (geoType == 'static') {
		curLat = lat;
		curLng = lng;
		if (zoom != null && ( map.getZoom() < minFocusZoom || force==true ) ) {
				map.setCenter(new GLatLng(lat,lng), parseFloat(zoom));
		} else {
			map.panTo(new GLatLng(lat,lng),3000);
		}
	} else if (geoType=='broadcaster' || geoType == 'ghostcaster' ) {
		if (autoTrack) {
			curLat = lat;
			curLng = lng;
			var loc = new GLatLng(lat,lng)
			if (zoom != null && ( map.getZoom() < minFocusZoom || force==true ) ) {
				map.setCenter(new GLatLng(lat,lng), parseFloat(zoom));
			} else if ( map.getZoom() < minFocusZoom) {
				map.setCenter(new GLatLng(lat,lng), minFocusZoom);
			} else if (isPercentFromEdge(loc,25)) {
				map.panTo(new GLatLng(lat,lng),3000);
			}
		}
	}
};

function isPercentFromEdge(loc,percent) {
	bounds = map.getBounds();
	//check if the location is a certain percentage 
	//from the edge of the map
	boundSW = bounds.getSouthWest();
	boundNE = bounds.getNorthEast();
	//double check percent
	if (percent > 50) { 
		percent=50; 
	} else if (percent < 0) {
		percent=0;
	}
	n_lat=boundNE.lat();
	e_lng=boundNE.lng();
	w_lng=boundSW.lng();
	s_lat=boundSW.lat();
	//check lng first
	lng = loc.lng();
	d_ew = Math.abs( e_lng-w_lng );
	d_lng = Math.max(Math.abs(e_lng-lng),Math.abs(w_lng-lng));
	if ( 1- d_lng/d_ew < percent/100) { return true; };
	//checklatsecond
	lat = loc.lat();
	d_ns = Math.abs( n_lat-s_lat );
	d_lat = Math.max(Math.abs(n_lat-lat),Math.abs(s_lat-lat));
	if (1- d_lat/d_ns < percent/100) { return true; };
	//within bounds
	return false;
};
	

function createMarker(point,title,type,infoHTML)  {
	if (infoHTML == null) {
		infoHTML="";
	} 	
	var m;
	m = new GMarker(point, new GIcon(G_DEFAULT_ICON));
	if (type == 'ad') {
		 m.getIcon().image = "http://s3.amazonaws.com/seerowww/advert.png";
		 m.getIcon().iconSize = new GSize(26, 32);
		 m.getIcon().iconAnchor = new GPoint(13,16);
		 m.getIcon().shadowSize = new GSize(43, 30);
		 m.getIcon().shadow = "http://s3.amazonaws.com/seerowww/advert_shad.png";			 
		GEvent.addListener(m, "click", function() {
			m.openInfoWindowHtml(infoHTML);
			curInfoWindow=title;
		});
	} else 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() {
			m.openInfoWindowHtml(infoHTML);
			curInfoWindow=title;
		});
	} else if (type.substring(0,2) == 'gh') {
		if (type.substring(2,4) == "N") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster_N.png";
		} else if (type.substring(2,4) == "NW") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster_NW.png";
		} else if (type.substring(2,4) == "W") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster_W.png";
		} else if (type.substring(2,4) == "SW") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster_SW.png";
		} else if (type.substring(2,4) == "S") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster_S.png";
		} else if (type.substring(2,4) == "SE") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster_SE.png";
		} else if (type.substring(2,4) == "E") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster_E.png";
		} else if (type.substring(2,4) == "NE") {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster_NE.png";
		} else {
			m.getIcon().image = "http://s3.amazonaws.com/seerowww/ghostcaster.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/ghostcaster_shad.png"; 	 
		GEvent.addListener(m, "click", function() {
			m.openInfoWindowHtml(infoHTML);
			curInfoWindow=title;
		});
	} else {	
		GEvent.addListener(m, "click", function() {
			nm.openInfoWindowHtml(infoHTML);
			curInfoWindow=title;
		});
	}
	return m;
};


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 isset(varname){
  return(typeof(window[varname])!='undefined');
};

function refreshMarkers(response) {
	if (!marking && swfReady) {
		marking=true;
		var oldbcmarkers = bcmarkers;
		//delete bcmarkers;
		bcmarkers = new Array();
		var v = response.documentElement.getElementsByTagName('bc');
	    mcnt=0;
	 
		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;
			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 infoHTML = '<div onclick=\'loadLiveVideo("'+mtit+'");\' style=\'cursor:pointer\'><table><tr><td><img style=\'margin:10px;border:1px solid #999999;padding:4px;\' src=\''+mthm+'\'/></td><td><span style=\'font-size:18px\'>'+mtit+' </span><span style=\'font-size:10px\'><br/>From:<br/>'+mcit+', '+mreg+',<br/>'+mcou+'<br/><span style=\'color:#003399\'>(<b>LIVE</b> click to watch)</span></span></td></tr></table></div>';
			
			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");
				}
			}
			if (mtit == curBroadcaster) {
				foundCurLive = true;
				throbLive();
				if ((!connLive && autoRecLive ) || ( connLive == undefined && autoRecLive == undefined)) {
					loadLiveVideo();
				}
				if (autoTrack && !ghostcasting) {
					var zoom = null;
					var force = false;
					if (geoType != 'broadcaster') {
						zoom = liveDynamicZoom;
						force = true;
					}
			   		geoType='broadcaster';
					updateSeeroMap(mlat,mlng,zoom,force);
				}
			}
			bcmarkers.push(mtit);
			mcnt++;
		}
		if (!foundCurLive && connLive) {
			connLive=false;
			killLiveVideo();
		}
		//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;
				}
			}
		}
		refreshList();
		marking=false;
	}
	
	window.setTimeout( function() { loadBCMarkers(); }, bcRefreshTime);
};

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
};

function refreshList() {
	var listHTML = '<table>';
	var bcname;
	for (var i=0; (i < bcmarkers.length && i < 5) ; i++) { 
		if ( bcmarkers[i].length > 14 ) {
			bcname = bcmarkers[i].substr(0,10)+'...';
		} else {
			bcname = bcmarkers[i];
		}
		listHTML += '<tr><td><img src="http://s3.amazonaws.com/seerowww/broadcaster.png"></img></td><td><strong>'+bcname+'</strong></td></tr>';
	}
	listHTML +='</table>';
	$('mapList').update(listHTML);
};

function selectGeoVOD(video) {
	connLive=false;
   	map.closeInfoWindow();
   	proxy.call('play_movie',video);
	//zoomtoVod(lat,lng);
	newBC = (video.match(/(.*)_[0-9]*/)[1]);
	if (newBC != curBroadcaster) {
		curBroadcaster = newBC;
		updateBroadcastProfile(newBC,video);
	} else {
		updateVideoInfo(newBC,video);
	}

};


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));
	}
	stopAutoTrack();
	curLat = lat;
	curLng = lng;
	refreshAdOnce();
};

function zoomtoVod(lat,lng) {
	autoRecLive=false;
	stopAutoTrack();
	geoType='static';
   	updateSeeroMap(lat,lng,focusZoom,true);
	refreshAdOnce();
};

var stopAutoTrack = function () {
	if (autoTrack) {
		autoTrack = false;
		$('autoTrackDivOn').style.display="none";
		$('autoTrackDivOff').style.display="";
   	}
}

function startAutoTrack() {
	if (!autoTrack) {
		autoTrack = true;
		$('autoTrackDivOff').style.display="none";
		$('autoTrackDivOn').style.display="";
   	}
}


var getMapBounds =  function () {
	var bounds = map.getBounds();
  	var sw = bounds.getSouthWest();
  	var ne = bounds.getNorthEast();
  	return(sw.lat()+'|'+sw.lng()+'|'+ne.lat()+'|'+ne.lng());
};

var curBC = function() {
	return(curBroadcaster);
};

function loadBCMarkers() {
	bcloader = null;
	bcloader = new Ajax.Request('/query/fetchBCs.php', {
    	method: 'get',
   		parameters: { bounds : getMapBounds(), broadcaster : curBC() },
		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) {
				//alert("XML PARSING ERROR: "+e.message);
				//return;
				window.setTimeout( function() { loadBCMarkers(); }, bcRefreshTime);
			}
			delete this;
		}
	});
}

////// GHOSTCAST FUNCTIONS //////
function ghostcast(ghostlat,ghostlng,gheading) {
	ghostcasting = true;
	if (!ghostcasticon) {
		ghostcasticon = createMarker(new GLatLng(parseFloat(ghostlat),parseFloat(ghostlng)),'ghostcaster','gh'+gheading,'This is the recorded track of the video you are watching now.');
		map.addOverlay(adMarker);
	} else {
		map.removeOverlay(ghostcasticon);
		ghostcasticon.setPoint(new GLatLng(parseFloat(ghostlat),parseFloat(ghostlng)));
		map.addOverlay(ghostcasticon);
	
		if (gheading == "N") {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster_N.png");
		} else if (gheading == "NW") {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster_NW.png");
		} else if (gheading == "W") {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster_W.png");
		} else if (gheading == "SW") {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster_SW.png");
		} else if (gheading == "S") {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster_S.png");
		} else if (gheading == "SE") {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster_SE.png");
		} else if (gheading == "E") {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster_E.png");
		} else if (gheading == "NE") {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster_NE.png");
		} else {
			ghostcasticon.setImage("http://s3.amazonaws.com/seerowww/ghostcaster.png");
		}
	}
	if (autoTrack) {
		var zoom=null;
		var force=false;
		if (geoType != 'ghostcaster') {
			zoom = liveDynamicZoom;
			force = true;
		}
		geoType='ghostcaster';
		updateSeeroMap(ghostlat,ghostlng,zoom,force);
	}
}

function clearGhostcast() {
	ghostcasting = false;
	if (ghostcasticon) { map.removeOverlay(ghostcasticon) };
}


// add the auto track toggle control
function AutoTrackControl() {
};
AutoTrackControl.prototype = new GControl();
AutoTrackControl.prototype.initialize = function(map) {
	//var autoTrackToggle=autoTrack;
	var container = document.createElement("div");
	container.style.border = "1px solid black";
	container.style.color = "black";
	container.style.width = "120px";
	container.style.cursor = "pointer";
	container.style.textAlign = "center";
	//container.style.margin = "0px";
	//container.style.padding = "0px";
	
	var autoTrackDivOn = document.createElement("div");
	autoTrackDivOn.id = 'autoTrackDivOn';
	autoTrackDivOn.style.backgroundColor="#D4FF91";
	autoTrackDivOn.style.borderTop = "1px solid #B0B0B0";
	autoTrackDivOn.style.borderLeft = "1px solid #B0B0B0";
	autoTrackDivOn.style.borderBottom = "1px solid #D4FF91";
	autoTrackDivOn.style.borderRight = "1px solid #D4FF91";
	autoTrackDivOn.style.fontWeight = "bolder";
	autoTrackDivOn.style.cursor = "pointer";
	autoTrackDivOn.style.height = "15px";
	container.appendChild(autoTrackDivOn);
	autoTrackDivOn.appendChild(document.createTextNode("Auto Track (On)"));
  
	var autoTrackDivOff = document.createElement("div");
	autoTrackDivOff.id = 'autoTrackDivOff';
	autoTrackDivOff.style.display="none";
	autoTrackDivOff.style.backgroundColor="#FFFFFF";
	autoTrackDivOff.style.borderTop = "1px solid white";
	autoTrackDivOff.style.borderLeft = "1px solid white";
	autoTrackDivOff.style.borderBottom = "1px solid #B0B0B0";
	autoTrackDivOff.style.borderRight = "1px solid #B0B0B0";
	autoTrackDivOff.style.cursor = "pointer";
	autoTrackDivOff.style.height = "15px";
	container.appendChild(autoTrackDivOff);
	autoTrackDivOff.appendChild(document.createTextNode("Auto Track (Off)"));
	
	GEvent.addDomListener(autoTrackDivOn, "click", function() {
		autoTrack = false;
		autoTrackDivOn.style.display="none";
		autoTrackDivOff.style.display="";
	});
	GEvent.addDomListener(autoTrackDivOff, "click", function() {
		autoTrack = true;
		autoTrackDivOff.style.display="none";
		autoTrackDivOn.style.display="";
	});
	map.getContainer().appendChild(container);
	return container;
};
	
// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
AutoTrackControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(220, 7));
};

function loadMap() {
    if (GBrowserIsCompatible()) {
        this.map = new GMap2(document.getElementById("map"));	

		//set up kml manager
		var kmlman = new KMLManager(this.map,'vod_v1', true);
		
		GEvent.addListener(this.map, "infowindowopen", updateInfo);
		GEvent.addListener(this.map, "dragstart", map.closeInfoWindow);

		if (!curLat) {
			curLat = home_lat;
			curLng = home_lng;
		}
        this.map.setCenter(new GLatLng(home_lat,home_lng), liveStaticZoom, G_HYBRID_MAP);
		this.map.addControl(new GMapTypeControl());
		this.map.addControl(new GLargeMapControl());
		this.map.addControl(new AutoTrackControl());
		this.map.enableContinuousZoom();
		
  		loadBCMarkers(true);
		window.setTimeout( function() { refreshAd(); }, adInitDelay);
		proxy.call('startFlash');
	}
}

//keep this function around for the proxy
function setGeoType(type) {
	geoType=type;
}

function killLiveVideo() {
	proxy.call('startNotLiveCycle',curBroadcaster);
}

function loadLiveVideo(broadcaster) {
	if (broadcaster) {
		map.closeInfoWindow();
		if (curBroadcaster != broadcaster) {
			curBroadcaster=broadcaster;
			updateBroadcastProfile(broadcaster,null);
		}
	}
	if (curBroadcaster != '') {
		startAutoTrack();
		proxy.call('connectToBroadcast',curBroadcaster);
	}
}


function notifyStatus(autoRecLiveIN,connLiveIN) {
	swfReady=true;
	autoRecLive=autoRecLiveIN;
	connLive=connLiveIN;
}

function throbLive() {
	for (i=0;i<3;i++) {
		setTimeout("$('liveButton').addClassName('yellow');",700*i);
		setTimeout("$('liveButton').removeClassName('yellow');",700*i+400);
	}
}

function goToHomeLocation() {
	zoomto(homeZoom,home_lat,hom_lng);
}

function link2js(link) {
	var zoomRE = /zoomto/g;
	var videoRE = /\/video\/(.*)/g;
	if ( link.search(zoomRE) != -1 ) {
		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 if (link != ";") {
			js = link+'();';
		}
	} else if ( link.search(videoRE) != -1 ) {
		var js = "selectGeoVOD('";
		js += link.substring(link.search(videoRE) + 7);
		js += "')";
	}
	return(js);		
}


function updateInfo() {
	var el;
	if (el  = $('iw_kml')) {
		//el.style.marginTop='10px';
		
		links = el.getElementsByTagName('a');
		if ( links.length <= 1 ) {
			el.style.height='auto';
			el.style.width='auto';
			el.style.height='50px';
			el.style.width='315px';
		} else {
			el.style.overflow='auto';
			el.style.height='115px';
			el.style.width='315px';
		}
		var i=0;
		for (i=0 ; i < links.length; i=i+1) {
			link = links[i].getAttribute('href') ;
			if ( link != null && link != '' && link.search(/javascript/) < 0 ) {
				newl = link2js(link);
				links[i].setAttribute('href','javascript:'+newl+';');
				links[i].setAttribute('target','_self');
			}
		}
	}
}

function updateBroadcastProfile(newBC,video) {
	$('bcheader').update(newBC);
	$loaderhtml = "<div style='padding-top:30px;text-align:center;' class='loading'><img src='http://s3.amazonaws.com/seerowww/loading.gif'/></div>";
	$('broadcaster-profile').update($loaderhtml);
    chatupdater.stop();
	$('broadcaster-chat').update($loaderhtml);
	$('broadcaster-link').update($loaderhtml);
	$('broadcaster-flag').update($loaderhtml);
	$('agenda').update($loaderhtml);
	$('vote-div').update($loaderhtml);
	$('rssContentContainer').update($loaderhtml);
	new Ajax.Updater('broadcaster-profile', '/loadBCProfile.php?bc='+newBC, {
	});
	new Ajax.Request('/loadChat.php?bc='+newBC, {
    	onComplete : function(resp) {
			$('broadcaster-chat').update(resp.responseText);
			chatupdater = new Ajax.PeriodicalUpdater('chat-div', "/chatter.php", {
				frequency : 1, 
				decay : 2,
				onSuccess : function(resp) { 
				  $('chat-div').scrollTop = $('chat-div').scrollHeight;
				},
				parameters : {room : $F('room') }
		  	});
			$('chat-div').scrollTop = $('chat-div').scrollHeight;
		}
	});
	if (video == null) {
		new Ajax.Updater('broadcaster-link', '/loadLinks.php?bc='+newBC, {
		});
		new Ajax.Updater('broadcaster-flag', '/loadFlagging.php?bc='+newBC, {
		});
		rewriteLightboxURLs('http://www.seero.com/broadcaster/'+newBC);
	} else {
		updateVideoInfo(newBC,video);
	}
	new Ajax.Updater('agenda', '/getcalendar.php?bc='+newBC, {
		onComplete : function(resp) {
			adjustDate(0);
		}
	});
	new Ajax.Updater('vote-div', '/voting-div.php?bc='+newBC, {
				onComplete : function(resp) { 
					var lbox = document.getElementsByClassName('votebutton');
					for(i = 0; i < lbox.length; i++) {
						var valid = new lightbox(lbox[i]);		  
					}
				}
	});
	new Ajax.Updater('rssContentContainer', '/rss-content.php?bc='+newBC, {
	});
	new Ajax.Updater('leaderboard', '/loadLeaderboard.php?bc='+newBC, {
	});
}

function updateVideoInfo(newBC,video) {
		new Ajax.Updater('broadcaster-link', '/loadLinks.php?vod='+video, {
		});
		new Ajax.Updater('broadcaster-flag', '/loadFlagging.php?vod='+video, {
		});
		var filevname = video.match(/(.*_[0-9]*)\.?f?l?v?$/);
		if ( filevname.length > 1 ) {
			rewriteLightboxURLs('http://www.seero.com/video/'+filevname[1] );
		}
}


////// AD FUNCTIONS //////
function updateDisplayedAd() {
	if (!adMarker) {
		adMarker = createMarker(new GLatLng(parseFloat(curAdLat),parseFloat(curAdLng)),'admarker','ad','This is the current Ad!');
		var adMtOpt = { 
		  'color':'#FFFF3D',
		  'weight':8,
		  'padding':30,
		  'length': 15,
		  'iconScale': 0.7 };
		adTrack = new MarkerTracker(adMarker,map,adMtOpt);
		
  		GEvent.bind(adTrack.babyMarker_, 'click' , this, stopAutoTrack );
		map.addOverlay(adMarker);
	} else {
		map.removeOverlay(adMarker);
		adMarker.setPoint(new GLatLng(parseFloat(curAdLat),parseFloat(curAdLng)));
		map.addOverlay(adMarker);
		adTrack.enable();
	}
	$('adItem').update('<table><td><img src="http://s3.amazonaws.com/seerowww/advert.png"></img></td><td>'+curAdDesc+'</td></table>');
}

function clearAd() {
	$('magicBox').update('');
	$('adItem').update('');
	if (adMarker) { 
		map.removeOverlay(adMarker) 
		adTrack.disable();
	};
}



function refreshAd() {
	dt = new Date();
	if ((dt.getTime() - tlastad) < adRefreshTime) {
		window.setTimeout( function() { refreshAd(); }, adRefreshTime - (dt.getTime() - tlastad));
	} else {
		adloader = null;
		adloader = new Ajax.Request('/query/localAd_zone3_geob.php', {
			method: 'get',
			parameters: { geoBOn : 1 , sourceLat : curLat , sourceLon : curLng , maxDist : 100},
			evalScripts: true,
			onSuccess: function (response) {
				if (response.responseText == '') {
					loadPSAd();
					window.setTimeout( function() { refreshAd(); }, 30000);
				} else {
					responseRe= new RegExp ("(.*)<scr"+"ipt>(.*)<.scr"+"ipt>(.*)", "g");
					responseData = responseRe.exec(response.responseText);
					eval(responseData[2]);
					$('magicBox').update(response.responseText);
					updateDisplayedAd();
					dt = new Date();
					tlastad = dt.getTime();
					window.setTimeout( function() { refreshAd(); }, adRefreshTime);
				}
			},
			onFailure: function (response) {
				//clearAd();
				//window.setTimeout( function() { refreshAd(); }, adRefreshTime);
			}
		});
	}
}

function refreshAdOnce() {
	adloader = null;
	adloader = new Ajax.Request('/query/localAd_zone3_geob.php', {
		method: 'get',
		parameters: { geoBOn : 1 , sourceLat : curLat , sourceLon : curLng , maxDist : 100},
		evalScripts: true,
		onSuccess: function (response) {
			if (response.responseText == '') {
				//nada
			} else {
				responseRe= new RegExp ("(.*)<scr"+"ipt>(.*)<.scr"+"ipt>(.*)", "g");
				responseData = responseRe.exec(response.responseText);
				eval(responseData[2]);
				$('magicBox').update(response.responseText);
				updateDisplayedAd();
				dt = new Date();
				tlastad = dt.getTime();
			}
		}
	});
}

function loadPSAd() {
	adloader = null;
	adloader = new Ajax.Request('/query/localAd_zone5.php', {
		method: 'get',
		evalScripts: true,
		onSuccess: function (response) {
			if (response.responseText == '') {
				//nada
			} else {
				clearAd();
				$('magicBox').update(response.responseText);
				dt = new Date();
				tlastad = dt.getTime();
			}
		}
	});
}
