//Copyright 2009 EarthNC, Inc www.earthnc.com
//initialize clock for load timer
var markersmap = new Array(); var markersmapcount=0;
var searcher = null;
var gsearch = Array(); var searchControl=null;
var icons = new Array();
var rlevel = null;
var rchart = null;
var mapcontrol = null;
var tilelayers = null;   var map = null;
var rastermap = null; var opacity=.5;
var zmin; var zmax;
var routemakerloaded=0;
var rastermaploaded = 1;
var rasterloadedname = "'OneChart' View - Click for Individual Charts"; var rasterloadednum = "onechart.c5.5.17";
var map; 
var mLoc = null; var locList = null;
if (google.gears) var geo = google.gears.factory.create('beta.geolocation');

google.load("maps", "2.c");
google.load("search", "1");

function load() { //alert("not calling load function");

resize();

function EarthNCLogoControl() {}
EarthNCLogoControl.prototype = new GControl();
EarthNCLogoControl.prototype.initialize = function(map) {
  var container=document.createElement("div");
  container.setAttribute("id","earthlogo");
  var zoomInDiv=document.createElement("div");this.setButtonStyle_(zoomInDiv);
  container.appendChild(zoomInDiv);
   
  var img=document.createElement('img');
  img.setAttribute('src','images/map_logo.png');//old file is map_logo.jpg
   
   zoomInDiv.appendChild(img);
   GEvent.addDomListener(zoomInDiv,"click",function(){
   var center = map.getCenter();
   window.open('http://earthnc.rave-staging.com');
   });
   
  map.getContainer().appendChild(container);return container;}

EarthNCLogoControl.prototype.getDefaultPosition = function() {
	
	if(earthnc_getUrlVariable('em'))
	{
	  
	  
	  return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(363, 25));//for embedde mode and hide left panel 
	  
	}
	else
	{
	   
	   return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(524, 25));//for fulscreen 54 7
		 
	}
	
 //edited by me
 //hide('earthlogo')
 
  }

EarthNCLogoControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "#0000cc";
  button.style.textAlign = "center";
  button.style.width = "6em";
  button.style.cursor = "pointer";
}




 
function EarthNCTransControl() {}
EarthNCTransControl.prototype = new GControl();
EarthNCTransControl.prototype.initialize = function(map) {
  var container=document.createElement("div");
 var transDiv=document.createElement("div");this.setButtonStyle_(transDiv);
// transDiv.innerHTML = 'Toggle Chart Transparency';
 container.appendChild(transDiv); 
  GEvent.addDomListener(transDiv,"click",function(){
  setTileOpacity();
  });
   
  map.getContainer().appendChild(container);return container;}

EarthNCTransControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 33));
  }

EarthNCTransControl.prototype.setButtonStyle_ = function(button) {
  button.style.background="#CCCCCC";
  //button.style.textDecoration = "underline";
  button.style.color = "#222222";
  button.style.textShadow= "0 0.5px 1px"; 
  button.style.textAlign = "center";
  button.style.width = "100px";
  button.style.cursor = "pointer";
}





if (earthnc_getUrlVariable('ht')){document.getElementById('map').style.height=earthnc_getUrlVariable('ht');}
if (earthnc_getUrlVariable('wd')){document.getElementById('map').style.width=earthnc_getUrlVariable('wd');}
   tlat = lat;
   tlon = lon;
  
   var str_ll=earthnc_getUrlVariable('ll');
   if (str_ll){
	   if(str_ll.search('%2C')!='-1')
	   {
		  str_ll = str_ll.replace('%2C',',') ;
	   }
	
   lat = str_ll.split(',')[0];
   lon = str_ll.split(',')[1];
   tlat = lat;
   tlon = lon;
   } 
   else if (earthnc_getUrlVariable('zmkml')){
   } else {
    if (geo) {geo.getCurrentPosition(updatePosition, handleError);}
    else if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {  
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    tlat = lat;
    tlon = lon;
    zoom = 14;
    updatePosition2(tlat,tlon,zoom);
    }); 
    }
   	else if (google.loader.ClientLocation) {
      zoom = 13;
      lat = google.loader.ClientLocation.latitude;
      lon = google.loader.ClientLocation.longitude;
      tlat = lat;
      tlon = lon;
     }
    
   }
   
   if (earthnc_getUrlVariable('z')){
   zoom = earthnc_getUrlVariable('z');
   }

   if (earthnc_getUrlVariable('op')){
   document.getElementById('chartopacity').checked=true;
   opacity = .5;
   }

   if (GBrowserIsCompatible()) {     
        map = new google.maps.Map2(document.getElementById("map"));
        mapcontrol = new GMapTypeControl();
        map.addControl(mapcontrol);
        if (!earthnc_getUrlVariable('em')){
        map.addControl(new GLargeMapControl());
        var adcount = 2;
        } else {map.addControl(new GSmallMapControl()); var adcount=1;}

        map.setCenter(new GLatLng(tlat, tlon), parseInt(zoom)); 
        map.removeMapType(G_SATELLITE_MAP);
        map.addMapType(G_SATELLITE_3D_MAP);
        map.setMapType(G_HYBRID_MAP);
        map.enableContinuousZoom();
	    map.enableScrollWheelZoom();
        map.addControl(new EarthNCLogoControl());
        map.addControl(new EarthNCTransControl());
		map.addControl(new GOverviewMapControl());

        
        var publisher_id = 'pub-7720029083570370'; // Replace 1234123412341234 with your Google AdSense publisher id.
        var adPos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 30)); // Set the anchor position and GSize offset to your desired values.
        
        adsManagerOptions = {
        maxAdsOnMap : adcount,
        style: 'adunit',
        channel: '6820387357', // This field is optional - replace 12345678 with a channel number that you created for GooYAMLgle AdSense tracking
        position: adPos
        };

        adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
        adsManager.enable();
        

         //check for custom content
        if (earthnc_getUrlVariable("url")){
        var url = earthnc_getUrlVariable("url");
        url = url.replace(/%26/g,"&").replace(/%3F/g,"?").replace(/%3D/g,"=").replace(/%2F/g,"/"); 
        loadUrl();
      } 

        if (earthnc_getUrlVariable("cap")){
        var cap = earthnc_getUrlVariable("cap");
        cap = cap.replace(/%26/g,"&").replace(/%3F/g,"?").replace(/%3D/g,"=").replace(/%20/g," ");
        document.getElementById("caption").innerHTML = cap;
        }
      }
    
	//earthnc_chartload_1();
    //comment next line if you do not wish to load the chart layer automatically  
    if (earthnc_getUrlVariable("chart")){
    loadraster_single(earthnc_getUrlVariable("chart"));
    } else {loadraster_single("onechart");}
   // resize(); 
    map.setCenter(new GLatLng(tlat, tlon), parseInt(zoom));
    //earthnc_chartload();
	
    
    //set up the lat/lon 'finder'
    locList = GEvent.addListener(map, "singlerightclick",
        function (pixels,overlay){
        var zoom = map.getZoom();
        var latlng = map.fromContainerPixelToLatLng(pixels);   
        mLoc = new GMarker(latlng, {draggable: true});
        var tmhtml = getPositionHtml(latlng);
        
        GEvent.addListener(mLoc, "drag", function() { 
            var latlng = mLoc.getLatLng();
            var tmhtml = getPositionHtml(latlng);
            mLoc.openInfoWindowHtml(tmhtml);
        });
        GEvent.addListener(mLoc, "dragend", function() { 
            var latlng = mLoc.getLatLng();
            var tmhtml = getPositionHtml(latlng);
            mLoc.openInfoWindowHtml(tmhtml);
        });
        GEvent.addListener(mLoc, "click", function() { 
            var latlng = mLoc.getLatLng();
            var tmhtml = getPositionHtml(latlng);
            mLoc.openInfoWindowHtml(tmhtml);
        });
    map.addOverlay(mLoc);
    mLoc.openInfoWindowHtml(tmhtml);    
    }); 
    //callback to update chart overlay as users pan map when layer is 'on'
  GEvent.addListener(map, "moveend", enc_showmarkers);  
  GEvent.addListener(map, "click", function(overlay, point) {
   if (overlay) {
     // we now need a check here in case the overlay is the info window
     // only our markers will have a .myhtml property
     if (overlay.extern){
      markerExternDetail(overlay.did,overlay.extern+"markersmap");
     }
     else if (overlay.tname) {
       markerDetail(overlay.did,"markersmap");
       //close_menus();
     }
     else if (overlay.description) {
       overlay.openInfoWindowHtml(overlay.description);
       close_menus();
     }
   }
 });
 
searchControl = new google.search.SearchControl();
searcher = new google.search.LocalSearch(); // create the object
searcher.setCenterPoint(map); // bind the searcher to the map

var options = new google.search.SearcherOptions(); // create the object
  options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);

// Add the searcher to the SearchControl
searchControl.addSearcher(searcher , options);

 // And second, we need is a search complete callback!
 searchControl.setSearchCompleteCallback(searcher , function() {

    var results = searcher.results; // Grab the results array
    // We loop through to get the points
    if (results.length>0){
    for (var i = 0; i < results.length; i++) {
      var tmpIcon = new GIcon(G_DEFAULT_ICON);
      tmpIcon.image = 'http://maps.google.com/mapfiles/kml/paddle/'+(i+1)+'.png';
      tmpIcon.iconSize = new GSize(24,24);
      var tmpmarkerOptions = { icon:tmpIcon };
      var result = results[i]; // Get the specific result
      var markerLatLng = new google.maps.LatLng(parseFloat(result.lat),
                                                parseFloat(result.lng));
      var marker = new google.maps.Marker(markerLatLng,tmpmarkerOptions); // Create the marker

      // Bind information for the infoWindow aka the map marker popup
      marker.bindInfoWindow(result.html.cloneNode(true));
      result.marker = marker; // bind the marker to the result
      map.addOverlay(marker); // add the marker to the map
     window['gsearch']['google-'+i]= marker;
      
      // put in result list
       var tmp = document.createElement('div');
      tmp.setAttribute('id','google-'+i);
      tmp.setAttribute('lat',parseFloat(result.lat));
      tmp.setAttribute('lon',parseFloat(result.lng));
      tmp.setAttribute('class','esResult');
      tmp.google = result.html.innerHTML;
      tmp.innerHTML = '<div class="esRTitle"><img src="'+tmpIcon.image+'" height="24px">'+result.title+'</div>' + 
                     '<div class="esRMenu"><a href="javascript:searchDetail(\'google-'+i+'\');searchGoto(\'google-'+i+'\');">More Info</a></div>';
      el('searchResults').appendChild(tmp);
      }
      

    // Store where the map should be centered
    var center = searcher.resultViewport.center;

    // Calculate what the zoom level should be
    var ne = new google.maps.LatLng(searcher.resultViewport.ne.lat,
                                    searcher.resultViewport.ne.lng);
    var sw = new google.maps.LatLng(searcher.resultViewport.sw.lat,
                                    searcher.resultViewport.sw.lng);
    var bounds = new google.maps.LatLngBounds(sw, ne);
    var zoom = map.getBoundsZoomLevel(bounds, new google.maps.Size(350, 350));

    // Set the new center of the map
    // parseFloat converts the lat/lng from a string to a float, which is what
    // the LatLng constructor takes.
    map.setCenter(new google.maps.LatLng(parseFloat(center.lat),
                                         parseFloat(center.lng)),
                                         zoom);
    } else {searchChart('all:'+el('searchText').value);}
  });
  
  // Draw the control
  searchControl.draw(controlContainer);
  var controlContainer = document.createElement('div'); // build the control div
  controlContainer.style.width = '350px'; // set the control width
  el("caption").appendChild(controlContainer);
  clearRtPts();
  
  //add topo
  map.addMapType(MYTOPO_MAP);
  //set dynamic logo
  document.getElementById('earthlogo').style.right='54%';
}

function getWindowHeight() { //alert(self.innerHeight);
   if (self.innerHeight)
   {
     // alert(self.innerHeight+"1");
	  return self.innerHeight;
   }
   if (document.documentElement && document.documentElement.clientHeight)
   {
      //alert(document.documentElement.clientHeight+"2");
	  return document.documentElement.clientHeight;
   }
   if (document.body)
   {
      //alert(document.body.clientHeight)
      return document.body.clientHeight;
   }
   return 0;
}

function getWindowWidth() {
   if (self.innerWidth) return self.innerWidth;
   if (document.documentElement && document.documentElement.clientWidth)
   return document.documentElement.clientWidth;
   if (document.body) return document.body.clientWidth;
			        return 0;

			    }

function resize() {  
			         
					hoffset = 50;
			        if (earthnc_getUrlVariable("em")){hoffset = 70;}
			        var mapc = document.getElementById("map"); 
					var sidepanel = document.getElementById("side_panel_id"); 
					var header = document.getElementById("menubar");
					var window_width = getWindowWidth();
					var window_hight = getWindowHeight();//alert(window_width);
					if(window_width<650)
					{
					  
					 
					   toggle_on();
					   hide('toggle');
					   if(window_width<571)
					   {
						   hide('search_top');
						 
						   
					    }
						else
						{
							show('search_top');
						}
					}
					else
					{
						toggle_off();
						show('toggle');
						
						
					}
					//alert(getWindowHeight());
					//alert(getWindowWidth());
				    
					if(!earthnc_getUrlVariable('em'))
					{
					 sidepanel.style.maxHeight = window_hight+ "px";
					  mapc.style.height = (window_hight-hoffset) + "px";
					}
			        //mapc.style.width = (getWindowWidth()-32) + "px";
				
					
                    //header.style.width = (getWindowWidth()-20) + "px";
			        //map.checkResize();
} 

			    
// new earthnc Marker function
function enc_showmarkers(){
lookupraster();
reloadExtern();
if (el('share_dsp').style.display=='block') updateLinks();
if (el('showmarkers').checked){  
    hide('navaids');show('navaids_on');
  manageMarkers('markersmap');
} 
else {  show('navaids');hide('navaids_on');
  for (var key in markersmap) {
    map.removeOverlay(markersmap[key]); 
  }
  markersmap = new Array();
  markersmapcount = 0;
}
}

function removeMarkers(marray){
  for (var key in window[marray]) {
    map.removeOverlay(window[marray][key]); 
  }
  window[marray] = new Array();
}

function manageMarkers(marray,mlimit,dicon){
  if (!mlimit) mlimit = 500;
  var bounds = map.getBounds();
  var bounds = Math.abs(bounds.getNorthEast().lng()-bounds.getSouthWest().lng());
  var z = map.getZoom();
  var sc = 1;
  if (z>=6 && z<8) sc =2;
  if (z>=8 && z<10) sc =3;
  if (z>=10 && z<12) sc =4;
  if (z>=12) sc = 5;
  var type = 'marker|tide|wxbuoy|milepost|wreck|bridge';
  var limit = 100;
  var latlon = map.getCenter().lat()+','+map.getCenter().lng();
  // clean up
  var mcount = window[marray+'count'];
  if (mcount>mlimit){
    var tcount = 0;
    var itir = window[marray+'count']-mlimit;
    for (var key in window[marray]){
    tcount++;
    window[marray+'count']--;
    map.removeOverlay(window[marray][key]);
    delete window[marray][key];
    if (tcount>itir) break;
    }
  }
  $.getJSON("./php/search.php",{ll: latlon, d: bounds, limit:limit, sc: sc,type: type, ajax: 'true'}, function(j){
  if (j.count>0){        
      for (var i = 0; i < j.results.length; i++) {
        var sname = j.results[i].name;
        var id = j.results[i].type+'-'+j.results[i].id;
        if (!window[marray][id]){
        window[marray+'count']++;
        var icon = j.results[i].icon;
        if (!icons[icon]){
              var ticon = new GIcon(G_DEFAULT_ICON);
              if (!dicon){
              ticon.image = "http://earthnc.com/files/icons/"+icon;
              } else {ticon.image = dicon;}
              ticon.iconAnchor = new GPoint(16, 16);
              icon.infoWindowAnchor = new GPoint(16, 0);
              ticon.iconSize = new GSize(32, 32);
              ticon.shadowSize = new GSize(0, 0);
              ticon.imageMap = [6,49,8,18,37,19,43,47];
              icons[icon] = ticon;   
        } else {ticon = icons[icon];}
        var tmp = new GMarker(new GLatLng(j.results[i].latitude,j.results[i].longitude),{icon:ticon});
        tmp.name = j.results[i].name;
        tmp.icon = j.results[i].icon;
        tmp.tname = type;
        tmp.did = id;
        map.addOverlay(tmp);
        window[marray][id]= tmp;
        }
      }
    }
});
}

function markerDetail(did,marray){  
  var type = did;
  var sname = window[marray][did].name;
  type = type.split('-');
  if (sname=="") sname=type[0];
  var icon = window[marray][did].icon;
  name = '<div class="esDTitle">'+sname+'</div><div class="esLatLon">Lat/Lon: '+formatll(lat,lon,'dm')+'</div>';
  var img = '<img class="micon" src="http://earthnc.com/files/icons/'+icon+'" />';
  var adspace = '<div id="windowAd"><a href="http://click.linksynergy.com/fs-bin/stat?id=jGjeQNcg9qY&offerid=146261&type=3&subid=0&tmpid=1826&RD_PARM1=http%253A%252F%252Fitunes.apple.com%252Fus%252Fapp%252Fmarine-charts%252Fid386584429%253Fmt%253D8%2526uo%253D4%2526partnerId%253D30&u1=ovpopup" target="itunes_store"><img src="http://earthnc.info/cvp/images/earthnc_mobile_ad.png" style="width:234px;height:60px;" /></a>';
  
  $.get('./php/'+type[0]+'.php?id='+type[1],function(data){
  window[marray][did].openInfoWindow('<div class="popUp">'+name+img+data+adspace+'</div>');
 });
}

function earthnc_routeload(){   

   //new edited
    hide("advert")//for hidibg advertise
   show('route_btn_on_id');
   hide('route_btn_id');
    //end
	
  if (routemakerloaded==0){
   //close_menus(); 
  document.getElementById("routemaker").style.display="block";
//   document.getElementById("link_route").className="selected_new_2";
  routemakerloaded=1;
   hide("link_route_open");
  show("link_route_close");
   }
  else
  { 
  /*close_menus();
  routemakerloaded=0;*/
  //close_menus(); 
  document.getElementById("routemaker").style.display="block";
  // document.getElementById("link_route").className="selected_new_2";
  routemakerloaded=1;
   hide("link_route_open");
  show("link_route_close");
  }
}



function earthnc_routehide(){ 
	
//close_menus();
//new edited
   hide('route_btn_on_id');
   show('route_btn_id');
    //end

hide("routemaker");
show("link_route_open");
hide("link_route_close");
finishLine();
routemakerloaded=0;
check_advert_status();//chech advert status
}

function earthnc_getUrlVariable(variable) {
  var url = document.location.href.split('?');
  if (url[1]){
  var vars = url[1].split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
    return pair[1];
    }
  }
  }
}

//Route Maker Functions
var line = null; 
    var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],
              ["blue", "#000080"], ["purple", "#800080"]];
    var options = {};
    var lineCounter_ = 0;
    var colorIndex_ = 0;
    var featureTable_;
    function select(buttonId) {
    document.getElementById(buttonId).className="selected";
    }
    function unselect(buttonId) {
    document.getElementById(buttonId).className="unselected";
    }

    function stopEditing() {
    document.getElementById("line_b").className="unselected";
    }

   function getColor(named) {
      return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
    }
   function startLine() { 
      select("line_b");
      var color = getColor(false);
      if (line!=null)
      {
      document.getElementById("line_b").className="unselected";
        return;
      /*
      var yes = confirm("Erase Current Route and Start Over?");
        if (!yes){
        document.getElementById("line_b").className="unselected";
        return;
        } else
        {clearRoute(1);
        document.getElementById("line_b").className="selected";
         }
         */
      }
      
      if (el("srlatd").value!='0'){
        var lat = parseFloat(el("srlatd").value)+parseFloat(el("srlatm").value)/60+parseFloat(el("srlats").value)/60;  
        if (el("srlath").value=="S") lat = -1*lat;
        var lon = parseFloat(el("srlond").value)+parseFloat(el("srlonm").value)/60+parseFloat(el("srlons").value)/60;  
        if (el("srlonh").value=="W") lon = -1*lon;
        var startp = new GLatLng(lat,lon); 
      // initialize custom start points
        if (el("erlatd").value!='0'){
        var elat = parseFloat(el("erlatd").value)+parseFloat(el("erlatm").value)/60+parseFloat(el("erlats").value)/60;  
        if (el("erlath").value=="S") elat = -1*elat;
        var elon = parseFloat(el("erlond").value)+parseFloat(el("erlonm").value)/60+parseFloat(el("erlons").value)/60;  
        if (el("erlonh").value=="W") elon = -1*elon;
        var endp = new GLatLng(elat,elon); 
        map.setCenter(startp);
        line = new GPolyline([startp,endp],color);
        map.addOverlay(line);
        len = line.getLength();
        var lenkm = (Math.round(len*.539956803 / 10) / 100) + "nm";
        document.getElementById("routedist").innerHTML = "Distance: "+lenkm;
        updateRtEnd(line);
        line.enableEditing({onEvent: "mouseover"});
        line.disableEditing({onEvent: "mouseout"});
        document.getElementById("line_b").className="unselected";
        var cells = document.getElementById("routedist");
        GEvent.bind(line, "lineupdated", cells.innerHTML, function() {
          var len = line.getLength();
          var lenkm = (Math.round((len*.539956803 / 10) / 100)) + "nm";
          document.getElementById("routedist").innerHTML = "Dist: "+lenkm;
          updateRtEnd(line);
        });
        GEvent.addListener(line, "click", function(latlng, index) {
        if (typeof index == "number") {
        poly.deleteVertex(index);
       } 
       });
        } else { 
        line = new GPolyline([startp],color);
        map.setCenter(startp);
        GEvent.addListener(line, "lineupdated", function() {
        len = line.getLength();
        var lenkm = (Math.round(len*.539956803 / 10) / 100) + "nm";
        document.getElementById("routedist").innerHTML = "Distance: "+lenkm;
        updateRtEnd(line);
        });

      startDrawing(line, "My Route", function() {
      var len = line.getLength();
      var lenkm = (Math.round((len*.539956803 / 10) / 100)) + "nm";
      document.getElementById("routedist").innerHTML = "Dist: "+lenkm;
      updateRtEnd(line);
      }, color);
      document.getElementById("routetext").innerHTML = "Double-Click  End Point To Finish Route";
      }      
      } else {
      // start with a blank line
      line = new GPolyline([], color);
      show("RtPts");
      GEvent.addListener(line, "lineupdated", function() {
        len = line.getLength();
        var lenkm = (Math.round(len*.539956803 / 10) / 100) + "nm";
        document.getElementById("routedist").innerHTML = "Distance: "+lenkm;
        updateRtEnd(line);
        });

      startDrawing(line, "My Route", function() {
      var len = line.getLength();
      var lenkm = (Math.round((len*.539956803 / 10) / 100)) + "nm";
      document.getElementById("routedist").innerHTML = "Dist: "+lenkm;   
      }, color);
      document.getElementById("routetext").innerHTML = "Start Drawing Route or <a href='javascript:enterRtPts()'>Enter Start/End Points</a>, Double-Click To Finish Route";
      }      

      document.getElementById("routename").style.display = "block";
      document.getElementById("routedist").style.display = "block";
      document.getElementById("routesave").style.display = "block";
      document.getElementById("routeclear").style.display = "block";
    }
    
    function enterRtPts(){
      show("RtPts");
      clearRoute(1);
      document.getElementById("line_b").className="unselected";
      document.getElementById("routetext").innerHTML = "Enter Start/End Points then Click Icon to Start Route";
    }

    function startDrawing(poly, name, onUpdate, color) {
      map.addOverlay(poly);
      poly.enableDrawing(options);
      poly.enableEditing({onEvent: "mouseover"});
      poly.disableEditing({onEvent: "mouseout"});

      GEvent.addListener(poly, "endline", function() {
        document.getElementById("line_b").className="unselected";
        var cells = document.getElementById("routedist");
        GEvent.bind(poly, "lineupdated", cells.innerHTML, onUpdate);
        GEvent.addListener(poly, "click", function(latlng, index) {
        if (typeof index == "number") {
        poly.deleteVertex(index);
      } 
    });
  });
}

function finishLine(){
  if (line!=null)
    line.disableEditing();
}

function clearRoute(force){
    if (force || confirm("Are You Sure You Want to Erase Your Route?")){
    document.getElementById("routedist").innerHTML = "Dist: 0nm";
    document.getElementById("line_b").className="unselected";
    if (line!=null){
    line.disableEditing();
    map.removeOverlay(line);
    line = null;
    }
    clearRtPts();
    document.getElementById("routetext").innerHTML = "Click Icon to Start Route or <a href='javascript:enterRtPts()'>Enter Start/End Points</a>";
    }
    }
    
function clearRtPts(){
//zero start/end points
    el("srlatd").value='0';
    el("srlatm").value='0';
    el("srlats").value='0';
    el("srlond").value='0';
    el("srlonm").value='0';
    el("srlons").value='0';
    el("erlatd").value='0';
    el("erlatm").value='0';
    el("erlats").value='0';
    el("erlond").value='0';
    el("erlonm").value='0';
    el("erlons").value='0';
}

function updateRtEnd(line){
var last = line.getVertexCount()-1;
      var lat = line.getVertex(last).lat();
      var deg = Math.floor(lat);
      var min = Math.abs((lat - deg))*60;
      var sec = (min-Math.floor(min))*60;
      el("erlatd").value=Math.abs(deg);
      el("erlatm").value=Math.floor(min);
      el("erlats").value=sec;
      if (lat<0) {el("erlath").value='S';} else {el("erlath").value='N';}
      var lon = line.getVertex(last).lng();
      var deg = Math.floor(lon);
      var min = Math.abs((lon - deg))*60;
      var sec = (min-Math.floor(min))*60;
      el("erlond").value=Math.abs(deg);
      el("erlonm").value=Math.floor(min);
      el("erlons").value=sec;
      if (lon<0) {el("erlonh").value='W';} else {el("erlonh").value='E';}
      
      // update the start point
      var lat = line.getVertex(0).lat();
      var deg = Math.floor(lat);
      var min = Math.abs((lat - deg))*60;
      var sec = (min-Math.floor(min))*60;
      el("srlatd").value=Math.abs(deg);
      el("srlatm").value=Math.floor(min);
      el("srlats").value=sec;
      if (lat<0) {el("srlath").value='S';} else {el("srlath").value='N';}
      var lon = line.getVertex(0).lng();
      var deg = Math.floor(lon);
      var min = Math.abs((lon - deg))*60;
      var sec = (min-Math.floor(min))*60;
      el("srlond").value=Math.abs(deg);
      el("srlonm").value=Math.floor(min);
      el("srlons").value=sec;
      if (lon<0) {el("srlonh").value='W';} else {el("srlonh").value='E';}
}
    
function saveRoute(format){
	earthnc_routehide();
    serializeRoute();
   // var queryString = $('#EarthNCRouteForm').formSerialize(); 
    var submit = 0;
    if (format=="kml"){
    document.getElementById("RouteFormat").value = 'kml';
    submit = 1;
    }
if (format=="gpx"){
    document.getElementById("RouteFormat").value = 'gpx';
    submit = 1;
    }
if (format=="pdf"){
    document.getElementById("RouteFormat").value = 'pdf';
    submit = 1;
    }
if (submit==1){
    window.open('',"newWin");
    var a = window.setTimeout("document.EarthNCRouteForm.submit();",500); 
    }
    }

function serializeRoute(){
    if (line!=null){
     var RouteText = '';
     var vertcount = line.getVertexCount(); var i=0;
     for (i=0;i<vertcount;++i){
     RouteText = RouteText +line.getVertex(i).lng()+','+line.getVertex(i).lat()+' ';
     }
    document.getElementById("RoutePoints").value = RouteText;
    }
    }
//raster map functions
function lookupraster(){
 if (el('chart_dsp').style.display=='block'){
 var latlon = map.getCenter().lat()+','+map.getCenter().lng();
 $.getJSON("./php/rnclookup.php",{ll: latlon, ajax: 'true'}, function(j){
 if (rastermaploaded==0){
 var options = '<option value="none">Select a Chart to View</option>';
} else { 
var options = '<option value="loaded"><b>Loaded: '+rasterloadedname+'</b></option>'; }
if (rchart!='onechart' || rastermaploaded==0){options += '<option value="onechart.c5.5.17"><b>\'OneChart\' View Click for Individual Charts</b></option>';}
for (var i = 0; i < j.length; i++) {
if (j[i].optionValue!=rasterloadednum){
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
}
$("#rastercharts").html(options);
});
}
}

//raster map functions
function lookupraster_single(chart){
 if (chart=="onechart"){
    rlevel = 'c5';
    rchart = 'onechart';
    zmin = 5;
    zmax = 17;
    loadLayer(zmin,zmax);
    rastermaploaded=1;
    if (!earthnc_getUrlVariable('em')) lookupraster();
    rasterloadednum = 'onechart';
    rasterloadedname='OneChart View - Click for Individual Charts';
 } else {
 $.getJSON("./php/rnclookup.php",{chart: chart, ajax: 'true'}, function(j){
 var options = '<option value="'+j[0].optionValue+'"><b>Loaded: '+j[0].optionDisplay+'</b></option>'; 
 var selchart = j[0].optionValue.split(".");
    rlevel = selchart[1];
    rchart = selchart[0];
    zmin = selchart[2];
    zmax = selchart[3];
    loadLayer(zmin,zmax);
    rastermaploaded=1;
    if (!earthnc_getUrlVariable('em')) lookupraster();
    rasterloadednum = selchart[0];
    rasterloadedname=j[0].optionDisplay;
 $("#rastercharts").html(options);
});
}
}

function loadraster(){
var rselect = document.getElementById("rastercharts");
var selchart = (rselect.options[rselect.selectedIndex].value).split(".");
if (selchart[0]!='none' && selchart[0]!='loaded' && selchart[0]!='hide'){
rlevel = selchart[1];
rchart = selchart[0];
zmin = selchart[2];
zmax = selchart[3];
loadLayer(zmin,zmax);
rastermaploaded=1;
rasterloadednum = rselect.options[rselect.selectedIndex].value;
rasterloadedname=rselect.options[rselect.selectedIndex].innerHTML;
 if (!earthnc_getUrlVariable('em')) lookupraster();
}

if (selchart[0]=='hide'){
removeLayer();
}
}

function loadraster_single(chart){
    lookupraster_single(chart);  
}

function loadLayer(zmin,zmax) { 
tilelayers = new GTileLayer(new GCopyrightCollection("EarthNC, Inc"),zmin,zmax);
                                tilelayers.getCopyright = function (a,b){return {prefix: "EarthNC, Inc"};}
                                           if (rchart=='onechart'){
                                               tilelayers.getTileUrl = function(tile,zoom) {
                                			              if ((zoom < zmin) || (zoom > zmax)) {
                                			                  return "http://earthnc.info/images/blank.png";
                                			              } 
                                			              var ymax = 1 << zoom;
                                			              var y = ymax - tile.y -1;
                                   		              
                                			              return "http://earthncseamless.s3.amazonaws.com/"+zoom+"/"+tile.x+"/"+y+".png";
                                  }
                                   } else {
                                			         tilelayers.getTileUrl = function(tile,zoom) {
                                			              if ((zoom < zmin) || (zoom > zmax)) {
                                			                  return "http://earthnc.info/images/blank.png";
                                			              } 
                                			              var ymax = 1 << zoom;
                                			              var y = ymax - tile.y -1;
                                			    
			              return "http://earthnc.info/tiles/"+rchart+"/"+zoom+"/"+tile.x+"/"+y;
			          }
 			          }
 tilelayers.getOpacity = function() {return opacity;}

var hybridlayer = [G_HYBRID_MAP.getTileLayers()[0],tilelayers,G_HYBRID_MAP.getTileLayers()[1]];
 if (rastermap){map.removeMapType(rastermap);}
 rastermap = new GMapType(hybridlayer, G_HYBRID_MAP.getProjection(), "Charts", {maxResolution:17,minResolution:2,errorMessage:"Outside of Chart Area, Select a Different Chart and Click Load or Clear to Remove"});
map.addMapType(rastermap);
map.setMapType(rastermap);
}

function setTileOpacity(){
//if (document.getElementById("chartopacity").checked){opacity=.5;} else {opacity=1;}
if (opacity==.5) {opacity=1; hide('trans_btn_id');show('trans_btn_on_id');} else {opacity=.5; show('trans_btn_id');hide('trans_btn_on_id');}
map.removeMapType(rastermap);
loadLayer(zmin,zmax);
}

function removeLayer(){
 rastermaploaded=0; 
 lookupraster();
 map.removeMapType(rastermap);
 map.setMapType(G_HYBRID_MAP);
}

function loadUrl(){  
       var tmpurl  = earthnc_getUrlVariable("url"); 
       if (tmpurl){
       var url = earthnc_getUrlVariable("url");
       url = url.replace(/%26/g,"&").replace(/%3F/g,"?").replace(/%3D/g,"=").replace(/%2F/g,'/');
       }
      if (earthnc_getUrlVariable("zmkml")){ 
      var geoXml = new GGeoXml(url, function() {
        zoomToGeoXML(geoXml);
      }); 
      } else
       { var geoXml = new GGeoXml(url); 
       }
       map.addOverlay(geoXml);
}

function hide(did){
document.getElementById(did).style.display='none';
}



function embed(){
show('embed');
getembedcode();
}

function cleanurl(url){
   url = url.replace(/&/g,"%26");
   url = url.replace(/=/g,"%3D");
   url = url.replace("?","%3F"); 
   url = url.replace("//","%2F%2F");
   url = url.replace("/","%2F");
   return url;
   }

function selectall(id){
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

function show(did){
document.getElementById(did).style.display='block';
}

function updatePosition(position) {
 lat =  position.latitude; 
 lon =  position.longitude;
 map.setCenter(new GLatLng(lat, lon));
 map.setZoom(12);
}

function updatePosition2(lat,lon,zoom) {
 map.setCenter(new GLatLng(lat, lon));
 map.setZoom(zoom);
}

function handleError(positionError) {
}

function zoomToGeoXML(geoXml) {
      var center = geoXml.getDefaultCenter();
      
      var span = geoXml.getDefaultSpan();
      var sw = new GLatLng(center.lat() - span.lat() / 2,
                       center.lng
      () - span.lng() / 2);
      var ne = new GLatLng(center.lat() + span.lat() / 2,
                       center.lng() + span.lng() / 2);
      var bounds = new GLatLngBounds(sw, ne);
      map.setCenter(center);
      var newZoom = map.getBoundsZoomLevel(bounds);
      if (newZoom==17) newZoom=7;
      map.setZoom(newZoom);
      
}



function partnerload(did){
   if (p_cruisersnet1){ map.removeOverlay(p_cruisersnet1);  p_cruisersnet1=null; document.getElementById("showcnetmarinas").checked=false;}
   if (p_cruisersnet2){ map.removeOverlay(p_cruisersnet2);  p_cruisersnet2=null; document.getElementById("showcnetbridges").checked=false;}
   if (p_cruisersnet3){ map.removeOverlay(p_cruisersnet3);  p_cruisersnet3=null; document.getElementById("showcnetanchorages").checked=false;}
   if (p_marinalife1) { map.removeOverlay(p_marinalife1);   p_marinalife1=null; document.getElementById("showmarinalifemarinas").checked=false;}
  // hide('marinalife'); hide('cruisersnet');
   show(did);
}


function el(did){
return document.getElementById(did);
}

function getPositionHtml(latlng){
var lat = latlng.lat();
var lon = latlng.lng();
var html = formatll(lat,lon,'dm');
html = 'Marker Position<br /> <b>'+html+'</b><br /><a href="javascript:closeMarker(\'mLoc\');" >Remove</a>';
return html;
}

function closeMarker(mid){
  map.removeOverlay(window[mid]);
}

function formatll(lat,lon,type){
if (lat>0){latl="N";} else {latl="S";}
if (lon>0){lonl="E";} else {lonl="W";}
if (type=="dms"){
      lat = Math.abs(lat);
      lon = Math.abs(lon);
      LatDeg = Math.floor(lat);
      LatMin = Math.floor((lat-LatDeg)*60);
      LatSec =  (Math.round((((lat - LatDeg) - (LatMin/60)) * 60 * 60) * 100) / 100 ) ;
      LonDeg = Math.floor(lon);
      LonMin = Math.floor((lon-LonDeg)*60);
      LonSec = (Math.round((((lon - LonDeg) - (LonMin / 60 )) * 60 * 60) * 100 ) / 100);
      latlonstr = LatDeg+"&deg; "+LatMin+"'"+LatSec+'" '+latl+', '+LonDeg+"&deg; "+LonMin+"'"+LonSec+'" '+lonl;
}
if (type=="dm"){
      lat = Math.abs(lat);
      lon = Math.abs(lon);
      LatDeg = Math.floor(lat);
      LatMin = (lat-LatDeg)*60;
      LatMin = Math.floor(LatMin)+Math.round((-Math.floor(LatMin)+LatMin)*1000)/1000; 
      LonDeg = Math.floor(lon);
      LonMin = (lon-LonDeg)*60;
      LonMin = Math.floor(LonMin)+Math.round((-Math.floor(LonMin)+LonMin)*1000)/1000;
      latlonstr = LatDeg+"&deg;"+LatMin+"'"+latl+','+LonDeg+"&deg;"+LonMin+"'"+lonl;
}
return latlonstr
}

//
function earthnc_chartload(){
	
    if (!earthnc_getUrlVariable('em')) 
	lookupraster();
    
    if (document.getElementById("showearthnc").checked)
	{
            
			var nlat= map.getCenter().lat();
		    var nlon= map.getCenter().lng();
		    var zoom = map.getZoom();
		    var time = new Date();
		    var now = time.getTime();
            var URL = earthnc_getKMLUrl(nlat,nlon);
		//	var URL = "http://earthnc.com/kml/gmapsd/30.25_86.75nearthncmarks.kmz";
            /*if (earthncmap != null)
			{
                map.removeOverlay(earthncmap);
            }*/
		
            earthncmap = new GGeoXml(URL);
            
		   
		   map.addOverlay(earthncmap); 
            //reset timer
            then = now; 
   }
   else
    {  
 
      map.removeOverlay(earthncmap);

  

  }

}
//function to set proper URL to EarthNC Navaid file

function earthnc_getKMLUrl(nlat,nlon){

//base path

	var URL = 'http://earthnc.com/kml/gmapsd/';
	var loni = Math.floor(Math.abs(nlon));
	var lond = Math.abs(nlon)-loni;
	var lati = Math.floor(Math.abs(nlat));
	var latd = Math.abs(nlat)-lati;
	if (latd>=.75){latd=.75;} 
	else if (latd<.75 && latd>=.5){latd=.5;} 
	else if (latd<.5 && latd>=.25){latd=.25;} 
	else if (latd<.25){latd=0;} 
	if (lond>=.75){lond=0; loni+=1;} 
	else if (lond<.75 && lond>=.5){lond=.75;}
	else if (lond<.5 && lond>=.25){lond=.5;}
	else if (lond<.25){lond=.25;}
	 nlon = loni+lond;
	 nlat = lati+latd;
	 URL = URL + nlat + '_' + nlon +'nearthncmarks.kmz';
	 lat = nlat;
	 lon = -nlon;
	 
	  return URL;

}




