//global vars
var clockID = 0;
var sweep = 0;
var geocoder = null;
var map;
var center;
var venue;
var time;

var name;
var lng;
var lat;	
var llat;
var llng;
var bombsLeft;
var bombCapacity
var locality;
var postalCode;
var rank;

var team;
var teamaka;
var tlng;
var tlat;
var turfTeam;
var turfTeamAka;
var teamColor;
var teamDisplayName;

var turfSize=.005;
var bombMaxTime=4;
var startup=true;
var reportsLoaded=false;

function load() {
	//draw maps
 	map = new GMap2(document.getElementById("map"));
	map.enableScrollWheelZoom();
	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);
	map.addControl(new GSmallZoomControl());
	map.clearOverlays(); 
	map.removeMapType(G_HYBRID_MAP);


	if (LokiAPI.isInstalled()==true)	//load position
	{
		lokiLoad();	
		//setInterval("lokiLoad()",60000);
	
		//setup google geocoder
		geocoder = new GClientGeocoder();
		
	
		//set rank
		makeHttpRequest("../php/setRank.php?team="+team+"&name="+name,nada);
	
		//check to see if any bombs have exploded
		makeHttpRequest("../php/getArmedBombs.php",checkBombTimes);
		
		//check
		//makeHttpRequest("../php/getFlags.php",checkFlags);
	
		//check and display number of bombs left and capacity
		makeHttpRequest("../php/getBombsLeft.php",loadBombsLeft);
	}
}
	






//BOMB FUNCTIONS
function checkBombTimes(response){
	var result = eval('(' + response + ')');
	if(result!=null)
	{
		for (var i=0; i<result.length; i++)
		{	
			if( checkExploded(result[i].timestamp) )
			{
				makeHttpRequest("../php/updatebombstate.php?id="+result[i].id+"&bombstate=exploded", nada);
				//compare bomb lat lng to turf
				//findNearestTurf(point, size);
				var bombPoint= new GLatLng(result[i].lat,result[i].lng);
				changeTurfPosession(bombPoint, turfSize, result[i].name, result[i].team, result[i].neighborhood);			
			}
		}	
	}
}
	
	
function checkFlags(response){
	var result = eval('(' + response + ')');
	if(result!=null)
	{
		for (var i=0; i<result.length; i++)
		{	
			//check whos turf it's no now
			var turfPointNeighborhood=findNearestTurf(new GLatLng(result[i].lat,result[i].lng),turfSize);
				
			if( result[i].team!=turfPointNeighborhood )
			{
				//makeHttpRequest("../php/updateFlag.php?id="+result[i].id+"&tpNeighborhood="+turfPointNeighborhood, nada);
			}
		}	
	}
}


function drawMarkers(response){
	var result = eval('(' + response + ')');
	if(result!=null)
	{
		for (var i=0; i<result.length; i++)
		{	
			 var point = new GLatLng(result[i].lat,result[i].lng);	 
			 if(result[i].bombstate=='armed'||result[i].bombstate=='flag'||result[i].bombstate=='venue'){
			 //id, bombstate, name, team, lat, lng, venue, neighborhood, note, timestamp
			 map.addOverlay(createMarker(point, result[i].timestamp, result[i].id, result[i].bombstate, result[i].name, result[i].team, result[i].neighborhood, result[i].note, result[i].distance));
			 }
			 //map.setCenter(point, 15);
		}
	}
}

function createMarker(point, btimestamp, bid, bbombstate, bname, bteam, bneighborhood, bnote, bdist){
	// Create our "tiny" marker icon
	var tinyIcon = new GIcon();
	if(bbombstate=="armed"){
		tinyIcon.image = "http://turfbombing.com/images/Bomb_32x32.png";
		tinyIcon.iconSize = new GSize(32, 32);
		tinyIcon.iconAnchor = new GPoint(16, 16);	
		tinyIcon.infoWindowAnchor = new GPoint(16, 0);
		
		//var info=  "<h3>"+bname +" of "+bteam +"</h3><p>--<br/>"+bnote+"</p>";
		var info=  "<h3>"+bname +"</h3><p>"+bnote+"</p>";
		
		// Set up our GMarkerOptions object literal
		markerOptions = { icon:tinyIcon };
		var marker = new GMarker(point, markerOptions);
		
		GEvent.addListener(marker, "click", function() 
		{
			updateClock(btimestamp, bid, bname);	
			marker.openInfoWindowHtml(info);
			
			if(bname==name){
				document.getElementById("note").innerHTML = 
				"Edit your note below.<textarea class='bombnote' id='notetext' rows='2' cols='30' maxlength='140' name='note'>"+bnote+"</textarea>";
				document.getElementById("checkin").innerHTML = "<button value='edit' onclick=editNote("+bid+") >save note</button>";
			}
			else{
				//show bombs within 15 miles only diffuse those within 5 blocks
				if(bdist<0.402336){
					document.getElementById("note").innerHTML = 
					"Leave a note below.<textarea class='bombnote' id='notetext' rows='2' cols='30' maxlength='140' name='note'></textarea>";
					document.getElementById("checkin").innerHTML = "<button value='diffuse' onclick=diffuse('"+bid+"','"+escape(bteam)+"','"+escape(bneighborhood)+"') >diffuse</button>";
				}
				else{
				document.getElementById("note").innerHTML = 
					"You must be within 5 blocks of this bomb to diffuse it.";
					document.getElementById("checkin").innerHTML = "";
				}
			}
			//document.getElementById("diffuseButton").innerHTML = "<warn>[<a value='diffuse' onclick=diffuse('"+bid+"','"+escape(bteam)+"','"+escape(bneighborhood)+"') >diffuse</a>]</warn>";
		});
		
	}
	
		else if(bbombstate=="flag")
		{
			
			if(bteam==bneighborhood){
				tinyIcon.image = "http://turfbombing.com/images/flag.png";
				tinyIcon.iconSize = new GSize(16, 16);
				tinyIcon.iconAnchor = new GPoint(16, 8);	
				tinyIcon.infoWindowAnchor = new GPoint(16, 0);
			}
			
			else {
				tinyIcon.image = "http://turfbombing.com/images/whiteflag.png";
				tinyIcon.iconSize = new GSize(10, 10);
				tinyIcon.iconAnchor = new GPoint(5, 5);	
				tinyIcon.infoWindowAnchor = new GPoint(5, 0);
			}
	
			
			//var info=  "<h3>"+bname +" of "+bteam +"</h3><p>--<br/>"+bnote+"</p>";
			var info=  "<h3>"+bname +"</h3><p>"+bnote+"</p>";
	
		
			// Set up our GMarkerOptions object literal
			fmarkerOptions = { icon:tinyIcon };
			var marker = new GMarker(point, fmarkerOptions);
			
			GEvent.addListener(marker, "click", function() 
			{
				//updateClock(btimestamp, bid, bname);	
				marker.openInfoWindowHtml(info);
				
				if(bname==name){
				document.getElementById("note").innerHTML = 
					"Edit your note below.<textarea class='bombnote' id='notetext' rows='2' cols='30' maxlength='140' name='note'>"+bnote+"</textarea>";
				document.getElementById("checkin").innerHTML = "<button value='edit flag' onclick='editNote("+bid+")' >edit note</button>";
				}
			});
		}
	
		else if(bbombstate=="venue")
		{
		
			tinyIcon.image = "http://turfbombing.com/markers/yellow_small.png";
			tinyIcon.iconSize = new GSize(15, 26);
			tinyIcon.iconAnchor = new GPoint(7, 26);	
			tinyIcon.infoWindowAnchor = new GPoint(7, 6);
		
			
			var info=  "<h3>"+bname +"</h3><p>--<br/>"+bnote+"</p>";
		
		
			// Set up our GMarkerOptions object literal
			fmarkerOptions = { icon:tinyIcon };
			var marker = new GMarker(point, fmarkerOptions);
			
			GEvent.addListener(marker, "click", function() 
			{
				marker.openInfoWindowHtml(info);
				
			});
		}
	
			
	GEvent.addListener(marker, "infowindowclose", function() 
	{
		killClock();
		setButtons();
	});
	return marker;
	
}

function diffuse(bid, bteam, bneighborhood){

	bteam=unescape(bteam);
	bneighborhood=unescape(bteam);
	document.getElementById("timeState").innerHTML = "Bomb diffused. "
	
	var note=document.getElementById('notetext').value;
	document.getElementById("checkin").innerHTML = "";
	document.getElementById("note").innerHTML = "";
	
	teamReport("Diffused a bomb near "+venue+" on your turf. "+note, name, team);
	teamReport("Diffused a bomb your team planted near "+venue+" on "+bneighborhood+"\'s turf. "+note,name, bteam);
	
	var message=name+" diffused a bomb near "+venue+" on "+bneighborhood+"\'s turf."+note;
	makeHttpRequest("../php/twitter.php?message="+escape(message),nada);
		
	document.getElementById("diffuseButton").innerHTML =""; 
	killClock();
	makeHttpRequest("../php/updatebombstate.php?id="+bid+"&bombstate=diffused", lokiLoad);

}


function getMoreBombs(){
	if(team==turfTeam){
		bombsLeft++;
		if(bombsLeft>=bombCapacity)bombsLeft=bombCapacity;
		makeHttpRequest("../php/setBombsLeft.php?bombsLeft="+bombsLeft,loadBombsLeft);
	}
	else{
		document.getElementById('alert').innerHTML="<warn>you need to be on home turf to get more bombs</warn>";
	}
}


function plantBomb(){

	var note=document.getElementById('notetext').value;
	document.getElementById("checkin").innerHTML = "";
	document.getElementById("note").innerHTML = "";
	makeHttpRequest("../php/plantBomb.php?note="+note+"&lat="+lat+"&lng="+lng+"&neighborhood="+turfTeam+"&venue="+venue+"&name="+name+"&team="+team,function()
	{
		teamReport("planted a bomb near "+venue+" on "+turfTeamAka+"\'s turf. "+note, name, team);
		teamReport("<warn>planted a bomb near "+venue+" on your turf.</warn> "+note, name, turfTeam);
		var message=name+" planted a bomb near "+venue+" on "+turfTeamAka+"\'s turf. "+note;
		makeHttpRequest("../php/twitter.php?message="+escape(message),nada);

		bombsLeft--;
		makeHttpRequest("../php/setBombsLeft.php?bombsLeft="+bombsLeft,loadBombsLeft);	
		//makeHttpRequest("../php/getBombs.php?lat="+lat+"&lng="+lng,drawMarkers);
		lokiLoad();
	});
}



function dropFlag(){

	var note=document.getElementById('notetext').value;
	document.getElementById("checkin").innerHTML = "";
	document.getElementById("note").innerHTML = "";
	
	makeHttpRequest("../php/plantFlag.php?note="+note+"&lat="+lat+"&lng="+lng+"&neighborhood="+turfTeam+"&venue="+venue+"&name="+name+"&team="+team,function()
	{
		//makeHttpRequest("../php/getBombs.php?lat="+lat+"&lng="+lng,drawMarkers);
		lokiLoad();
	});

}


function editNote(noteId){
	var note=document.getElementById('notetext').value;
	document.getElementById("checkin").innerHTML = "";
	document.getElementById("note").innerHTML = "";
	
	makeHttpRequest("../php/updateNote.php?note="+note+"&id="+noteId,function()
	{
		//makeHttpRequest("../php/getBombs.php?lat="+lat+"&lng="+lng,drawMarkers);
		lokiLoad();
	});

}



function loadBombsLeft(response){
	var result = eval('(' + response + ')');
		if(result!=null)
	{
		for (var i=0; i<result.length; i++)
		{
			bombsLeft=result[i]['bombs'];
			bombCapacity=result[i]['capacity'];
			if(bombsLeft<5){
			document.getElementById("bombsLeft").innerHTML="<warn>"+bombsLeft+"</warn> / "+bombCapacity;
			}
			else{
			document.getElementById("bombsLeft").innerHTML=bombsLeft+" / "+bombCapacity;
			}
		}
	}
}

function timeDifference(dateA, dateB){
	var minutes = 1000*60;
	var hours = minutes*60;
	var difference=(dateA.getTime()/hours-dateB.getTime()/hours);
	return difference;
}

function updateClock(btimestamp,bid) {
	var bombTimeDate=btimestamp.split(" ");
	var bombDate=bombTimeDate[0].split("-");
	var bombTime=bombTimeDate[1].split(":");

	var bDate= new Date(bombDate[0],parseInt(bombDate[1])-1,bombDate[2],parseInt(bombTime[0])+bombMaxTime,bombTime[1],bombTime[2]);
	var tDate = new Date();

	var difference=timeDifference(bDate,tDate);
	
	if(difference<=0)makeHttpRequest("../php/getArmedBombs.php",checkBombTimes);

	var hoursLeft=Math.floor(difference);
	var minutesLeft=Math.floor((difference-hoursLeft)*60);
	var secondsLeft=Math.floor( ((difference-hoursLeft)*60-minutesLeft)*60 );

	minutesLeft = minutesLeft + "";
	if (minutesLeft.length == 1)  minutesLeft = "0" + minutesLeft;
	secondsLeft = secondsLeft + "";
	if (secondsLeft.length == 1)  secondsLeft = "0" + secondsLeft;
	document.getElementById("timeState").innerHTML = "Bomb will detonate in";
	document.getElementById("time").innerHTML = " &nbsp;<warn>" +hoursLeft + ":"  + minutesLeft + ":" + secondsLeft+"</warn>";
	

	if(clockID) {
	clearTimeout(clockID);
	clockID  = 0;
	}
	

	clockID = setTimeout("updateClock('"+btimestamp+"','"+bid+"')", 1000);

}

function killClock() {
   if(clockID) {
		clearTimeout(clockID);
		clockID  = 0;
		document.getElementById("time").innerHTML = "";	
		document.getElementById("timeState").innerHTML = "";	
   }
}

function checkExploded(btimestamp){
	var bombTimeDate=btimestamp.split(" ");
	var bombDate=bombTimeDate[0].split("-");
	var bombTime=bombTimeDate[1].split(":");

	var bDate= new Date(bombDate[0],parseInt(bombDate[1])-1,bombDate[2],parseInt(bombTime[0])+bombMaxTime,bombTime[1],bombTime[2]);
	var tDate = new Date();

	var difference=timeDifference(bDate,tDate);
	
	if(difference<=0)return true;
	else return false;
}


function setButtons(){
		
	//if you're in unclaimed turf
	if(turfTeam==null)
	{
		//document.getElementById("currentNeighborhood").innerHTML = "<b>in "+locality+"</b>";
		document.getElementById("note").innerHTML = "You're in unchartered territory.  Claim this turf!";
		document.getElementById("checkin").innerHTML = "<button value='claim this turf' onclick='claimTurf()' >claim this turf</button>";
	}
	//if you're in your home turf
	else if(team==turfTeam) 
	{
		document.getElementById("note").innerHTML = "You are on home turf.  You can replenish your bomb supply here.  If you see any bombs on the map, diffuse them!<br/><br/>To claim more turf, get off your ass and go for a walk, a bike-ride or a drive!  Take your laptop with you and visit different neighborhoods to claim or bomb them.<br/><br/>Plant a flag on home turf with a note below.<textarea class='bombnote' id='notetext' rows='2' cols='30' maxlength='140' name='note'></textarea>";
		//document.getElementById("checkin").innerHTML = "<button value='Plant a bomb here' onclick='getMoreBombs()' >get more bombs</button>";
		document.getElementById("checkin").innerHTML = "<button value='plant a flag' onclick='dropFlag()' >plant a flag</button>";
	}
	//if you're not in someone elses turf
	else if(team!=turfTeam)
	{
		if(bombsLeft>0)
		{
			document.getElementById("note").innerHTML = "You are on foreign turf. Plant a bomb here.  If nobody comes to diffuse the bomb within "+bombMaxTime+" hours, this turf is yours. <br/><br/>Leave a note below.<textarea class='bombnote' id='notetext' rows='2' cols='30' maxlength='140' name='note'></textarea>";
			document.getElementById("checkin").innerHTML = "<button value='Plant a bomb' onclick='plantBomb()' >plant a bomb</button>";
		}
		else 
		{
			document.getElementById("note").innerHTML = "No bombs left. Go home to get more bombs.";
			document.getElementById("checkin").innerHTML = "";			
		}
	}		
}
///////////////////////////////////////////////////////////BOMB FUNCTIONS









///////////////////////////////////////////TURF FUNCTIONS
function findNearestTurf(point, size){
	//cast point to floats
	var plat=parseFloat(point.lat());
	var plng=parseFloat(point.lng());
	
	//remove decimals from lat lng to calculate modulo
	var modlat=Math.round(plat*1000000.0)%(size*1000000);
	var modlng=Math.round(plng*1000000.0)%(size*1000000);
	
	//get southwest corner of turf
	var ttlat=(Math.round(plat*1000000.0)-modlat)/1000000.0;
	var ttlng=(Math.round(plng*1000000.0)-modlng)/1000000.0;
	
	makeHttpRequest("../php/whosTurf.php?lat="+ttlat+"&lng="+ttlng, function(response)
	{
		var result = eval('(' + response + ')');
		if(result!=null)
		{
			return result[0].team;
		}
	});
	//return new GLatLng(ttlat,ttlng);
}



function changeTurfPosession(bombPoint, size, tname, tteam, tneighborhood){
	//cast point to floats
	var plat=parseFloat(bombPoint.lat());
	var plng=parseFloat(bombPoint.lng());
	
	//remove decimals from lat lng to calculate modulo
	var modlat=Math.round(plat*1000000.0)%(size*1000000);
	var modlng=Math.round(plng*1000000.0)%(size*1000000);
	
	//get southwest corner of turf
	var ttlat=(Math.round(plat*1000000.0)-modlat)/1000000.0;
	var ttlng=(Math.round(plng*1000000.0)-modlng)/1000000.0;
	

	var taka;
	var naka;
	makeHttpRequest("../php/getTeamColorAKA.php?team="+tteam,function(response){
		var result = eval('(' + response + ')');
		if(result!=null)
		{	
			taka=result[0].aka;
			if(taka=="" || taka==null || taka=="undefined")
			{
				taka=tteam;
			}
			teamReport("'s bomb exploded. <warn>You lost some turf to "+taka+".</warn>", tname, tneighborhood);

		}
	});
	
	makeHttpRequest("../php/getTeamColorAKA.php?team="+tneighborhood,function(response){
		var result = eval('(' + response + ')');
		if(result!=null)
		{	
			naka=result[0].aka;
			if(naka==""||naka==null || naka=="undefined")
			{
				naka=tneighborhood;
			}
			teamReport("'s bomb exploded. <warn>A piece of "+naka+"'s turf is now yours.</warn>", tname, tteam);
			var message=tname+"'s bomb exploded. A piece of "+naka+"'s turf is now "+taka+"'s.";
			makeHttpRequest("../php/twitter.php?message="+escape(message),nada);
	
	}
	});
	

	makeHttpRequest("../php/updateTurf.php?name="+tname+"&team="+tteam+"&teamaka="+taka+"&lat="+ttlat+"&lng="+ttlng, nada);

}


function whosTurf(point, size){

	//cast point to floats
	var plat=parseFloat(point.lat());
	var plng=parseFloat(point.lng());
	
	//remove decimals from lat lng to calculate modulo
	var modlat=Math.round(plat*1000000.0)%(size*1000000);
	var modlng=Math.round(plng*1000000.0)%(size*1000000);
	
	//get southwest corner of turf
	tlat=(Math.round(plat*1000000.0)-modlat)/1000000.0;
	tlng=(Math.round(plng*1000000.0)-modlng)/1000000.0;
	
	
	makeHttpRequest("../php/whosTurf.php?lat="+tlat+"&lng="+tlng, function(response)
		{
			var result = eval('(' + response + ')');
			if(result!=null)
			{
				turfTeam=result[0].team;
				if(turfTeam!=null){
					getTurfTeamAKA(turfTeam);
				}	
			}
			//set buttons after we figure out who's turf we're on
			setButtons();
		});
}

function getTurfTeamAKA(ateam){
	makeHttpRequest("../php/getTeamColorAKA.php?team="+ateam,function(response){
		var result = eval('(' + response + ')');
		if(result!=null)
		{	
			//var akaTeamColor=result[0].color;
			turfTeamAka=result[0].aka;
			if(turfTeamAka==""|| turfTeamAka==null ||  turfTeamAka=="undefined")
			{
				turfTeamAka=ateam;
			}
				if(turfTeam==team)document.getElementById("currentNeighborhood").innerHTML = "<b>on home turf</b>";
				else document.getElementById("currentNeighborhood").innerHTML = "<b>on "+turfTeamAka+"\'s turf</b>";
		}
	});
}


function claimTurf(){
	document.getElementById("checkin").innerHTML = "";
	document.getElementById("note").innerHTML = "";
	
	makeHttpRequest("../php/setTurfs.php?lat="+tlat+"&lng="+tlng+"&name="+name+"&team="+team+"&teamaka="+teamaka+"&teamColor="+teamColor,function()
	{
		teamReport("claimed some turf near "+venue+" in "+locality+"", name, team);
		
		var message=name+" claimed some turf near "+venue+" in "+locality+"";
		makeHttpRequest("../php/twitter.php?message="+escape(message),nada);
		
		lokiLoad();
	});
}

function drawTurfs(response){
var result = eval('(' + response + ')');
	if(result!=null)
	{
		var nameCount=0;
		var teamCount=0;
		for (var i=0; i<result.length; i++)
		{
			var polyPoint=new GLatLng(result[i].lat,result[i].lng);
			var pteam=result[i].teamaka;
			if (pteam==""||pteam==null||pteam=="undefined")pteam=result[i].team;
			drawPolygons(polyPoint,turfSize, "#"+result[i].color, pteam, result[i].name);
			
			//count user has n turfs
			if(team==result[i].team)teamCount++;
			if(name==result[i].name)nameCount++;
		}
		
		//show turf counts
		document.getElementById("turfclaimed").innerHTML=nameCount;
		document.getElementById("turfclaimedteam").innerHTML=teamCount;
		//set user turf count so we can rank players
		makeHttpRequest("../php/setUserHasNTurfs.php?name="+name+"&turfs="+nameCount, nada);
		killsweepLoader();
	}
}


function drawTurfsForLogin(response){
var result = eval('(' + response + ')');
	if(result!=null)
	{
		for (var i=0; i<result.length; i++)
		{
			var polyPoint=new GLatLng(result[i].lat,result[i].lng);
			drawPolygons(polyPoint,turfSize, "#"+result[i].color, result[i].team, result[i].name);
		}
		
		killsweepLoader();
	}
}


function drawPolygons(point,size, pcolor, pteam, pname){
	//sw corner of turf
	var plat=parseFloat(point.lat());
	var plng=parseFloat(point.lng());
	
	//GPolygon(latlngs, strokeColor?, strokeWeight?, strokeOpacity?, fillColor?, fillOpacity?, opts?)
	var polygon = new GPolygon(
			[
			   new GLatLng(plat, plng ),
			   new GLatLng(plat, plng-size ),
			   new GLatLng(plat+size, plng-size ),
			   new GLatLng(plat+size, plng ),
			   new GLatLng(plat, plng ),
			], 
			pcolor, 2, .2, pcolor, 0.5);
				
	GEvent.addListener(polygon, "mouseover", function() 
	{
		document.getElementById("turfteam").innerHTML = pteam+"\'s turf claimed by "+pname;
		document.getElementById("turfteam").style.backgroundColor = pcolor;
		document.getElementById("turfteam").style.padding = '10px 10px 10px 10px';
	});
		GEvent.addListener(polygon, "mouseout", function() 
	{
		document.getElementById("turfteam").innerHTML = "";
		document.getElementById("turfteam").style.padding = '0px 0px 0px 0px';
	});
			
	map.addOverlay(polygon);
}



///////////////////////////////////////////////////////////////////////////////////////////TURF FUNCTIONS






var dots=".";
function sweepLoader(){
  	document.getElementById('alert').innerHTML="aquiring position and sweeping area for bombs..."+dots;
	if(sweep) {
		clearTimeout(sweep);
		sweep  = 0;
	}
	
	dots=dots+".";
	if(dots==".........................................................................................................................................")dots=".";
	sweep = setTimeout("sweepLoader()", 100);

}
function killsweepLoader() {
	if(sweep) {
		clearTimeout(sweep);
		sweep  = 0;
		document.getElementById('alert').innerHTML="";
	}
	dots=".";
}

function checkRank(){
	if (rank=="General"){
		document.getElementById("teamname").disabled=false;
		//document.getElementById("teamInfo").innerHTML="As the general of your gang, you can edit your team name (top left) by clicking on it.";
		document.getElementById("teamInfo").innerHTML="As the general of your gang, you can edit your team name by clicking on it. <warn>[<a onclick='editTeam()'>top left</a>]</warn>";
		document.getElementById("teamname").onclick=editTeam;
	}

	
}


function editTeam(){

			document.getElementById("teamname").focus();
			document.getElementById("teamname").style.borderStyle="solid";

}


function editTeamName(newTeamName){
	document.getElementById("teamname").style.borderStyle="none";
	if(teamDisplayName!=newTeamName){
		makeHttpRequest("php/setAKA.php?team="+team+"&aka="+escape(newTeamName),function(response)
		{
			loadTeamColorAKA();
		});
		makeHttpRequest("php/setTurfTeamAka.php?team="+team+"&aka="+escape(newTeamName), nada);
		lokiLoad();
	}
}

function loadTeamColorAKA(){
		makeHttpRequest("../php/getTeamColorAKA.php?team="+team,function(response){
		var result = eval('(' + response + ')');
		if(result!=null)
		{	
			teamColor=result[0].color;
			document.getElementById("teamname").style.color="#"+teamColor;
			document.getElementById("teamcolor").style.backgroundColor="#"+teamColor;

			teamaka=unescape(result[0].aka);
			if(teamaka=="" || teamaka==null || teamaka=="undefined")	teamDisplayName=team;
			else	teamDisplayName=teamaka;

			document.getElementById("teamname").value=teamDisplayName;

		}

	});

}


///////////////////////////////////////////////////////GEOCODE
function lokiLoad()
{
	reportsLoaded=false;
	document.getElementById("checkin").innerHTML = "";
	document.getElementById("note").innerHTML = "";
	//document.getElementById("mapLoadOverlay").style.display = "show";

  var loki = LokiAPI();
	//load team reports and chat
	makeHttpRequest("../php/getReport.php?team="+team,loadReport);
		
  	if(startup){
  		//get last known location
		center=new GLatLng(llat, llng);
		map.setCenter(center, 13);

		//set teamname color and aka
		loadTeamColorAKA();

		checkRank();
		startup=false;
	}
	

	sweepLoader();

  if (loki) { 
    loki.onSuccess = function(location) { 
		lat=location.latitude;
		lng=location.longitude;

		center=new GLatLng(lat, lng);
		map.setCenter(center, 16);
		map.clearOverlays(); 

		revGeo(center);
		localSearch(lat,lng);
		whosTurf(center, turfSize);
		makeHttpRequest("../php/getTurfs.php", drawTurfs);
		makeHttpRequest("../php/logUser.php?lat="+lat+"&lng="+lng,nada);
		makeHttpRequest("../php/getBombs.php?lat="+lat+"&lng="+lng,drawMarkers);
		//document.getElementById('alert').innerHTML="";
	}
	loki.setKey('cwwang.com');
    loki.requestLocation(true,loki.LIMITED_STREET_ADDRESS_LOOKUP);
    
	loki.onFailure = function(error,message) 
	{
		//alert(message)
		killsweepLoader() ;
		document.getElementById('alert').innerHTML="<warn>"+message+". We could not determine your position. Try moving around and sweep the area again.</warn>" ;
		//get last known location
		center=new GLatLng(llat, llng);
		map.setCenter(center, 13);
		map.clearOverlays(); 
		makeHttpRequest("../php/getTurfs.php", drawTurfs);
	}
  }
}


function loginLoad()
{

	//draw maps
 	map = new GMap2(document.getElementById("map"));
	map.enableScrollWheelZoom();
	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);
	map.addControl(new GSmallZoomControl());

	//get default location
	center=new GLatLng(40.729568,-73.993435);
	map.setCenter(center, 13);
	map.clearOverlays(); 

	//setup google geocoder
	geocoder = new GClientGeocoder();

 	makeHttpRequest("../php/getTurfs.php", drawTurfsForLogin);

}


function lokiAddress()
{
  var loki = LokiAPI();
  if (loki) { 
 
    loki.onSuccess = function(location) 
    { 
		lat=location.latitude;
		lng=location.longitude;
		center=new GLatLng(lat, lng);
		
		//addressToTeam(center);	
		makeHttpRequest("../php/geocode.php?q="+center+"", assignTeam);
	}
	loki.setKey('cwwang.com');
    loki.requestLocation(true,loki.LIMITED_STREET_ADDRESS_LOOKUP);
	loki.onFailure = function(error,message) {alert(message)}
  }
}


function localSearch(lat,lng)
{
	//get search result for food at lat lng
	makeHttpRequest("../php/localSearch.php?rsz=small&q=food&center="+lat+","+lng, 
	function(response){
		var result = eval('(' + response + ')');
		if(result!=null)
		{	
			var resultVenue=result.responseData.results[0];
			if(resultVenue==null||resultVenue=="")localSearch(lat,lng);
			venue=result.responseData.results[0].titleNoFormatting;
			var venuePoint=new GLatLng(resultVenue.lat,resultVenue.lng);
			//draw venue marker
			map.addOverlay(createMarker(venuePoint, "", "", "venue", venue, "", resultVenue.city, resultVenue.addressLines, 0));
			
			document.getElementById('currentVenue').innerHTML=venue;
		}
	});
}



function revGeo(center){
	makeHttpRequest("../php/geocode.php?q="+center.lat()+","+center.lng(), function(response) 
	{
		var geo=response.split(",");

		//remove whitespace
		postalCode = geo[3].replace(/\s/g,'');
		locality = geo[4].replace(/\s/g,'');
		if(locality==null || postalCode==null || locality=="" || postalCode=="")
		{
			revGeo(center);
		}
		if(turfTeam==null) document.getElementById("currentNeighborhood").innerHTML = "<b>in "+locality+"</b>";
	});
}

function assignTeam(response){
		var geo=response.split(",");
		//remove whitespace
		postalCode=geo[3].replace(/\s/g,'');
		locality = geo[4].replace(/\s/g,'');
		if(locality==null || postalCode==null || locality=="" || postalCode=="")
		{
			document.getElementById("address").innerHTML = "";
			document.getElementById("registerNeighborhood").innerHTML = "<b><warn>could not be determined. Please check your address.</warn></b>";
			document.getElementById("neighborhood").value ="";
		}
		else
		{
			//alert(locality);
			document.getElementById("registerNeighborhood").innerHTML = "<b><warn>"+locality+", "+postalCode+"</warn></b>";
			document.getElementById("neighborhood").value =""+locality+", "+postalCode+"";
		}
}


function addressToTeam(address){
	makeHttpRequest("../php/geocode.php?q="+address+"", assignTeam);
	//document.getElementById("address").innerHTML = address;
}


//////////////////////////////////////////////////////////////////////////////GEOCODE










////////////////////////////////////////////////CHAT
function loadReport(response){
	var result = eval('(' + response + ')');
	if(result!=null)
	{
		//for (var i=0; i<result.length; i++)
		for (var i=result.length-1;i>=0; i--)

		{
			addElement("reportsandchat", result[i].name+": "+result[i].report+"<br>--", "chat"+result[i].id)
		}
	}
	document.getElementById("chat").innerHTML = "<input id='chattextbox' type='text' name='chatbox' onkeypress='teamChat(event,this.value)' value='say something to your team' onFocus=' this.value=\"\" '></input>";	
	//document.getElementById("chattextbox").focus();
}


function teamReport(report, rname, rteam){
	//send report to database 
	makeHttpRequest("../php/enterChat.php?report="+escape(report)+"&team="+rteam+"&name="+rname,function()
	{	
		//refresh reports for current team
		if(reportsLoaded==false){
			makeHttpRequest("../php/getReport.php?team="+team,loadReport);
			reportsLoaded=true;
		}
	});
}

function teamChat(e,report){
	var key=e.keyCode || e.which;
	if (key==13){
			makeHttpRequest("../php/enterChat.php?report="+report+"&team="+team+"&name="+name,function()
		{
			makeHttpRequest("../php/getReport.php?team="+team,loadReport);
		});
	}
}

function addElement(commentBox, comment, id) {
	var ni = document.getElementById(commentBox);
	var newdiv = document.createElement('div');

  if( document.getElementById(id)==undefined )
	{
		//newdiv.setAttribute('id', id);
		newdiv.setAttribute('id', id);

		newdiv.innerHTML = comment;
		
		ni.insertBefore(newdiv,document.getElementById(commentBox).firstChild);
		//ni.insertBefore(newdiv,document.getElementById(commentBox).lastChild);
		//ni.appendChild(newdiv).firstChild;
		//ni.appendChild(newdiv).lastChild;
	}
}

function removeElement(id) {
  var d = document.getElementById('commentBox');
  var olddiv = document.getElementById(id);
  d.removeChild(olddiv);
}


/////////////////////////////////////////////////////////////////CHAT


function highScores(){
	makeHttpRequest("../php/getHighScores.php",function(response){
		var result = eval('(' + response + ')');
		if(result!=null)
		{	
			var highscoreteams = new Array();
			var highturfcount = new Array();
			
			for(var i=0;i<result.length; i++)
			{
				highscoreteams[i]=result[i].teamaka;
				highturfcount[i]=result[i].turfcount;
			}
			//display
			var ni = document.getElementById("main");
			
			var newdiv = document.createElement('div');
			newdiv.setAttribute('id',"highscores_container");
			newdiv.innerHTML = highscoreteams[0];
			ni.appendChild(newdiv);
		}
	});
}





function compareDist(a,b) {
	return a.distance-b.distance;
}

function nada(){}
