// set up some variables for the AIS map
var map;
var polyShape;
var polygonMode;
var polygonDepth="20";
var polyPoints=[];
var fillColor="#0000FF"; // blue fill
var lineColor="#FFFFFF"; // white line
var opacity= 0.5;
var lineWeight=2;
var mpol=new Array();
var myarr;
var gmarkers;  // we make use of global scope of variable so we don't have to pass it.
var gtrack;	// we make use of global scope of variable so we don't have to pass it.
var deselectCurrent=function(){};

//functions for sidebar from Google Maps Applications with PHP and Ajax
function windowHeight(){
	// Mozilla, Safari, Opera, etc...
	if(window.innerHeight){
		return window.innerHeight;}
	//IE 6&7
	if(document.documentElement && document.documentElement.clientHeight){
		return document.documentElement.clientHeight;}
	//IE 5
	if(document.body){
		return document.body.clientHeight;}
	// just in case
	return 0;
}

// function to handle resizing ....
function handleResize(){
	var height=windowHeight() - document.getElementById('toolbar').offsetHeight -30;
	document.getElementById('map').style.height=height+'px';
	document.getElementById('sidebar').style.height=height+'px';
}

// function to change class in body of html
function changeBodyClass(from,to){
	document.body.className=document.body.className.replace(from,to);
	return false;
}


function ais_type(id)
{
  var type1 = new Array('unspecified', 
			'Reserved', 
			'Wing In Ground',
			 '',
			 'High Speed Craft',
			 '',
			 'Passenger',
			 'Cargo',
			 'Tanker',
			 'Other');
  var type2 = new Array('', // All ships of this type
			'Hazard A', /* Major Hazard */
			'Hazard B', /* Hazard */
			'Hazard C', /* Minor Hazard */
			'Hazard D', /* Recogniseable Hazard */
			'',
			'',
			'',
			'',
			'' // No additional information
                        );

  type3 =new Array('Fishing', 'Towing', 'Towing and length of tow exceeds 200m or breadth exceeds 25m', 'Dredging or Underwater Operation', 'Dive Vessel', 'Military Ops', 'Sail', 'Pleasure Craft', 'Reserved', 'Reserved');
  type5 =  new Array('Pilot Vessel', 'SAR', 'Tug', 'Port Tender', 'Anti-pollution', 'Law enforce', 'Local Vessel', 'Local Vessel', 'Medical Trans', 'Special craft');

  type = Math.floor(id / 10);
  rem = id % 10;
  result = '';
  if (type == 3)
    result = type3[rem];
  else if (type == 5){
    result = type5[rem];
  } else {
    result = type1[type];
    if (id < 100 && type2[rem] != '')
      result = result +' '+type2[rem];
  }
  return result;
}


function getstatus(status) {
 switch (parseInt(status)) {
  case 0: return 'Underway';
   break;
  case 1: return 'At Anchor';
   break;
  case 2: return 'Not Under Command';
   break;
  case 3: return 'Restricted Manoeuvrability';
   break;
  case 4: return 'Constrained by Her Draught';
   break;
  case 5: return 'Moored';
   break;
  case 6: return 'Aground';
   break;
  case 7: return 'Engaged in Fishing';
   break;
  case 8: return 'Underway by Sail';
   break;
  case 15: return 'Default (15)';
   break;
  default: return status;
   break;
  }
}
// function to get colors so we can color the ship paths based upon type of ship
function shipcolor(type){
	var itype=Math.floor(type/10);
	switch(itype){
		case 1:
			scolor="#FFFFFF"; // white, other
			break;
		case 2:
			scolor="#FFFFFF"; // white, Wing in Ground
//			scolor="#FFA500"; //orange, Wing in Ground
			break;
		case 3:
			if(type==30){
				scolor="#008000";} // green, fishing
			if(type==31){
				scolor="#FFFF00";} // yellow, towing
			if(type==32){
				scolor="#FFFF00";} // yellow, towing
			if(type==33){
				scolor="#A52A2A";} //brown, dredging or underwater ops
			if(type==34){
				scolor="#FFFFFF";  // white, diving ops
				//scolor="#00FFFF";} //cyan, diving ops
			}
			if(type==35){
				scolor="#0000FF";} // blue, military ops
			if(type==36){
				scolor="#EE82EE";} //violet, sailing
			if(type==37){
				scolor="#EE82EE";  //violet, pleasure craft
				//scolor="#D8BFD8";} // thistle, pleasure craft
				}
			if(type==38){
				scolor="#FFFFFF";} // white, reserved
			if(type==39){
				scolor="#FFFFFF";} // white, reserved
			break;
		case 4:
			scolor="#FFFFFF";  // white, High speed craft
//			scolor="#DDA0DD";  // plum, High speed craft
			break;
		case 5:
			if(type==50){
				scolor="#C0C0C0";} // silver, Pilot vessel
			if(type==51){
				scolor="#FFA500"; // orange, SAR vessels
				//scolor="#C0C0C0";} // silver, SAR vessels
			}
			if(type==52){
				scolor="#FFFF00";} // yellow, tugs
			if(type==53){
				scolor="#C0C0C0";} // silver, port tender
			if(type==54){
				scolor="#808080";  // gray, anti-pollution vessels
				//scolor="#00FF00";} // lime, anti-pollution vessels
				}
			if(type==55){
				scolor="#0000FF";} // blue, law enforcement,military
			if(type==56){
				scolor="#FFFFFF";} //white, spare for local vessels
			if(type==57){
				scolor="#FFFFFF";} // white, spare for local vessels
			if(type==58){
				scolor="#FFFFFF";  // white, medical transport
			//	scolor="#FFC0CB";} // pink, medical transport
				}
			if(type==59){
				scolor="#FFFFFF";} //white, resolution 18 ships
			break;
		case 6:
			scolor="#FFCOCB"; // pink, passenger vessels
//			scolor="#00FF00"; // green, passenger vessels
			break;
		case 7:
			scolor="#FF0000"; //red, Cargo carriers
			break;
		case 8:
			scolor="#000000"; // black, Tankers
			break;
		case 9:
			scolor="#FFFFFF"; // white  Other types of ship
			break;
		}
	return scolor;
}
		

// creates a table off info for each ship about name/size/call sign/etc...
function makeinfo(){
	infostr=new Array(num_ships);
	for(i=0; i< num_ships; i++){
		leadstr='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">\n';

		callstr='<tr><td>Call Sign:</td><td>'+call_sign[i]+'</td></tr>\n';
		deststr='<tr><td>Destination:</td><td>'+ship_destination[i]+'</td></tr>\n';
		etastr='<tr><td>ETA:</td><td>'+ship_eta[i]+'</td></tr>\n';
		spdstr='<tr><td>Speed:</td><td>'+ship_speed[i]+' kts</td></tr><tr><td>Heading:</td><td> '+ship_course[i]+' deg</td></tr>\n';
		namstr='<tr><td>Name:</td><td>'+ship_name[i]+'</td></tr>\n';
		mmistr='<tr><td>MMSI:</td><td>'+mmsi[i]+'</td></tr>\n';
		sizestr='<tr><td>Size(LxWxD):</td><td>'+ship_length[i]+'m x '+ship_width[i]+'m x '+ship_draught[i]+'m </td></tr>\n';
		tabsstr='<div><table width=320 height=100 cellpadding="0" cellspacing="0">\n';
		tabestr='</table></div>\n';
		endstr='</html>\n';
		infostr[i]=tabsstr+mmistr+namstr+callstr+deststr+etastr+spdstr+sizestr+tabestr;
	}
	return infostr;
}
// function to create popup string text
function makepopstr(){
		popupstr=new Array(num_ships);
		for(i=0; i< num_ships; i++){
			typestr=ais_type(ship_type[i]);
			navstr=getstatus(ship_nav[i]);
			popupstr[i]=ship_name[i]+' '+navstr+' '+typestr;
		}
		return popupstr;
}
// function create ship tracks....
function createtracks(mypoints,lineColor,popuptext){
	var lineWeight=2;
	var polyShape=new GPolyline(mypoints,lineColor,lineWeight,1);
	//alert(polyShape);
	//alert(polyShape.length);
	map.addOverlay(polyShape);
// This almost works but can't get the ship info up now....
		GEvent.addListener(polyShape,"mouseover",function(){
//Get the number of vertices of the line
			ntr=polyShape.getVertexCount();
//compute "center vertex" for display of ship info
			ntrp=Math.floor(ntr/2);
			point=polyShape.getVertex(ntrp);
			map.openInfoWindow(point,popuptext);
			//	GLog.write(point);
			});
		GEvent.addListener(polyShape,"mouseout",function(){
			map.closeInfoWindow();
			//tooltip.style.visibility="hidden";
			});
	return polyShape;
}

// function to find what boxes are checked...
function getcheck(){
	
	var ischecked=new Array();
	if(document.getElementById("all_ships").checked){
		ischecked[0]=1;
	}else{
		ischecked[0]=0;}
	if(document.getElementById("Fishing").checked){
		ischecked[1]=1;
	}else{
		ischecked[1]=0;}
	if(document.getElementById("Tugs").checked){
		ischecked[2]=1;
	}else{
		ischecked[2]=0;}
	if(document.getElementById("Pilot").checked){
		ischecked[3]=1;
	}else{
		ischecked[3]=0;}
	if(document.getElementById("Military").checked){
		ischecked[4]=1;
	}else{
		ischecked[4]=0;}
	if(document.getElementById("Passenger").checked){
		ischecked[5]=1;
	}else{
		ischecked[5]=0;}
	if(document.getElementById("Cargo").checked){
		ischecked[6]=1;
	}else{
		ischecked[6]=0;}
	if(document.getElementById("Tanker").checked){
		ischecked[7]=1;
	}else{
		ischecked[7]=0;}
	if(document.getElementById("Other").checked){
		ischecked[8]=1;
	}else{
		ischecked[8]=0;}
	if(document.getElementById("Pleasure").checked){
		ischecked[9]=1;
	}else{
		ischecked[9]=0;}
	if(document.getElementById("Research").checked){
		ischecked[10]=1;
	}else{
		ischecked[10]=0;}
	return ischecked;
}
// function now plot ship or not
	function toplotit(ischecked,thetype){
		var myplotit=0;
		if (ischecked[0]==1){
			myplotit=1;
			return myplotit;
		}
		var itype=Math.floor(thetype/10);
		switch (itype){
			case 8:
				if(ischecked[7]==1){
					myplotit=1;
				}else{
					myplotit=0;}
				return myplotit;
				break;
			case 9:
				if(ischecked[8]==1){
					myplotit=1;
				}else{
					myplotit=0;}
				return myplotit;
				break;
			case 6:
				if(ischecked[5]==1){
					myplotit=1;
				}else{
					myplotit=0;}
				return myplotit;
				break;
			case 7:
				if(ischecked[6]==1){
					myplotit=1;
				}else{
					myplotit=0;}
				return myplotit;
				break;
			case 5:
				if(thetype==55){
					if(ischecked[4]==1){
						myplotit=1;}}
				if(thetype==50){
					if(ischecked[3]==1){
						myplotit=1;}}
				if(thetype==53){
					if(ischecked[3]==1){
						myplotit=1;}}
				if(thetype==52){
					if(ischecked[2]==1){
						myplotit=1;}}
				return myplotit;
				break;
			case 3:
				if(thetype==30){
					if(ischecked[1]==1){
						myplotit=1;}}
				if(thetype==32){
					if(ischecked[2]==1){
						myplotit=1;}}
				if(thetype==31){
					if(ischecked[2]==1){
						myplotit=1;}}
				if(thetype==33){
					if(ischecked[10]==1){
						myplotit=1;}}
				if(thetype==35){
					if(ischecked[4]==1){
						myplotit=1;}}
				if(thetype==36){
					if(ischecked[9]==1){
						myplotit=1;}}
				if(thetype==37){
					if(ischecked[9]==1){
						myplotit=1;}}
				return myplotit;
				break;
			default: return myplotit;
			break;
		}
}

// function to create a marker....
// Maybe we won't use this...
function createmarker(point,tabletext){
	var marker=new GMarker(point);
	var listItem=document.createElement('li');
	var listItemLink=listItem.appendChild(document.createElement('a'));
	var visible=false;
	listItemLink.href="#";
	listItemLink.innerHTML=tabletext;

	var focusPoint=function() {
		deselectCurrent();
		listItem.className='current';
		deselectCurrent=function(){ listItem.className='';}
		marker.openInfoWindowHtml(tabletext);
		map.panTo(point);
		return false;
	}

	GEvent.addListener(marker,'click',focusPoint);
	listItemLink.onclick=focusPoint;

	point.show=function(){
		if (!visible) {
			document.getElementById('sidebar-list').appendChild(listItem);
			map.addOverlay(marker);
			visible=true;
		}
	}
	point.hide=function(){
		if (visible) {
			document.getElementById('sidebar-list').removeChild(listItem);
			map.removeOverlay(marker);
			visible=false;
		}
	}
	point.show();

//      GEvent.addListener(marker, "click", function() {
//         	marker.openInfoWindowHtml(tabletext);
//       });
//	map.addOverlay(marker);
	return marker;
}
// Okay here is where the trouble begins...
// function to draw markers....
function drawCoordinates(){
	var locations;
	var gmarkers=new Array();
	var gtrack=new Array();
	html=makeinfo();
	mypopup=makepopstr();
	//alert(num_ships);
	var lineColor="#FFFFFF"; // white line color
	var opacity=0;
	var fillColor="#000000";
	var lineWeight=2;
	var ischecked=new Array();
	var ic=0;
	for(i=0; i< num_ships; i++){
		var polyPoints=[];
		lineColor=shipcolor(ship_type[i]);
		lat=ship_latitude[i];
		//if(i > 28){
		//alert(i);
		//alert(lineColor);
		//alert(lat);}
		if(lat!=undefined){
			if(lat.length > 1){
				for(j=0; j< lat.length; j++){
					ploc=new GLatLng(ship_latitude[i][j],ship_longitude[i][j]);
					polyPoints.push(ploc);
				}
				jnktxt=mypopup[i];
				gtrack[ic]=createtracks(polyPoints,lineColor,jnktxt);
			}
//		var point=new GLatLng(ship_latitude[i][lat.length-1],ship_longitude[i][lat.length-1]);
			locations=new GLatLng(ship_latitude[i][lat.length-1],ship_longitude[i][lat.length-1]);
			var teststr=html[i];
			gmarkers[ic]=createmarker(locations,teststr);
		}
		ic=ic+1;
//		var mymarker=new GMarker(point);
// new code for listing? from the book
//		var listItem=document.createElement('li');
//		var listItemLink=listItem.appendChild(document.createElement('a'));
//		var visible=false;

//		listItemLink.href="#";
//		listItemLink.innerHTML=teststr;
		
//		var focusPoint=function() {
//			deselectCurrent();
//			listItem.className='current';
//			deselectCurrent=function(){ listItem.className='';}
			//gmarker[i].openInfoWindowHtml(html[i]);
//			mymarker.openInfoWindowHtml(teststr);
//			map.panTo(point);
//			return false;
//		}
		
//		GEvent.addListener(mymarker,'click',focusPoint);
//		listItemLink.onclick=focusPoint;

//		locations.show=function(){
//			if (!visible) {
//				document.getElementById('sidebar-list').appendChild(listItem);
//				map.addOverlay(mymarker);
//				visible=false;
//			}
//		}
//		locations.show();
	}
	return [gtrack, gmarkers];
}
// function to draw markers....
function drawCoordinates2(){
	var locations;
	var nrv=gmarkers.length;
	//alert(gmarkers.length);
	for(i=0; i< nrv; i++){
		if(gmarkers[i]!=undefined){
		map.removeOverlay(gmarkers[i]);}
		//map.removeOverlay(gtrack[i]);
	}
	var nrt=gtrack.length;
	//alert(gtrack.length);
	for(i=0; i< nrt; i++){
		test=gtrack[i];
		//alert(i);
		//alert(test);
		if(test!=undefined){
		map.removeOverlay(test);}
	}
	//map.removeOverlay(gtrack);
	//map.removeOverlay(gmarkers);
	gtrack=new Array();
	gmarkers=new Array();
	//var gmarkers=new Array();
	//var gtrack=new Array();
	html=makeinfo();
	mypopup=makepopstr();
	var lineColor="#FFFFFF"; // white line color
	var opacity=0;
	var fillColor="#000000";
	var lineWeight=2;
	var ischecked=new Array();
	ischecked[0]=1; ischecked[1]=0; ischecked[2]=0; ischecked[3]=0;
	ischecked[4]=0; ischecked[5]=0; ischecked[6]=0; ischecked[7]=0;
	ischecked[8]=0;
	ischecked=getcheck();
	//alert(ischecked);
	//alert("drawcoordinates2");
	icount=0;
	y=document.getElementById('sidebar-list');
	if(y.hasChildNodes()){
		while(y.childNodes.length >=1){
			y.removeChild(y.firstChild);
		}
	}
	//alert(y);
	//document.Element.removeChild(y);
	//map.clearOverlays();
	gtrack.length=0;
	gmarkers.length=0;
	//marker.length=0;
	//polyShape.length=0;
	for(i=0; i< num_ships; i++){
		myp=toplotit(ischecked,ship_type[i]);
		if(myp==1){
			var polyPoints=[];
			lineColor=shipcolor(ship_type[i]);
			lat=ship_latitude[i];
			if(lat.length > 1){
				for(j=0; j< lat.length; j++){
					ploc=new GLatLng(ship_latitude[i][j],ship_longitude[i][j]);
					polyPoints.push(ploc);
				}
				jnktxt=mypopup[i];
				gtrack[icount]=createtracks(polyPoints,lineColor,jnktxt);
			}
			locations=new GLatLng(ship_latitude[i][lat.length-1],ship_longitude[i][lat.length-1]);
			teststr=html[i];
			gmarkers[icount]=createmarker(locations,teststr);
			icount++;
		}
	}
	//nmsKML=new GGeoXml("http://www.cencoos.org/sections/ais/nms.kml");
	//map.addOverlay(nmsKML);
	map.addOverlay(llGrat);
	return [gtrack, gmarkers];
}

// My load/initialize function
function aismapinit(){
	shipload();
	//alert('Got here');
	document.getElementById('button-sidebar-hide').onclick=function(){ return changeBodyClass('sidebar-right','nosidebar'); };
	document.getElementById('button-sidebar-show').onclick=function(){ return changeBodyClass('nosidebar','sidebar-right'); };
	handleResize();
	//alert('got here');
	map=new GMap2(document.getElementById("map"));
	//var copyrights= new GCopyrightCollection("AIS Data:");
	//var aisnps= new GCopyright(
	//		1,
	//		new GLatLngBounds(new GLatLng(-90,-180),new GLatLng(90,180)),
	//		0,
	//		'Naval Postgraduate School');
	//copyrights.addCopyright(aisnps);
	//var cplayers=new GTileLayer(copyrights);
	//cplayers.getTileUrl=function(){return;};
	//cplayers.isPng=function(){return false;}
	//cplayers.getOpacity=function(){return 1.0;}
	//var mycplayer=new GTileLayerOverlay(cplayers);
	var gcr=google.maps.MapType.prototype.getCopyrights;
	// google.maps.MapType.prototype.getCopyrights=function(bounds,zoom){
	//	return ['Naval Postgraduate School'].concat(gcr.call(this,bounds,zoom));
	//}
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(36.69,-122.4),7);
	llGrat=new LatLonGraticule(true);
	map.addOverlay(llGrat);
	nmsKML=new GGeoXml("http://www.cencoos.org/sections/ais/nms.kml");	map.addOverlay(nmsKML);
	//alert('Got here');
	myarr=drawCoordinates();
	//alert(myarr.length);
	gmarkers=myarr[1];
	gtrack=myarr[0];
	//alert(gmarkers.length);
	//alert(gtrack.length);
	//alert(gtrack[0]);
	//map.addOverlay(mycplayer);
	return [gtrack, gmarkers];
}

window.onresize=handleResize;
//if(window.attachEvent){window.attachEvent('onload',myarr=aismapinit);}
//else if (window.addEventListener){window.addEventListener('load',myarr=aismapinit,false);}
//else { document.addEventListener('load',myarr=aismapinit,false);}
window.onload=aismapinit;
//prev=window.onload;
//alert(prev);
