//Copyright 2009 EarthNC, Inc www.earthnc.com
//initialize clock for load timer
var earthnc_time = new Date();
var then = earthnc_time.getTime();
var earthncmap = null;
var rlevel = null;
var rchart = null;
var mapcontrol = null;
var tilelayers = null;   var map = null;
var rastermap = null; var opacity=1;
var zmin; var zmax;
var rastermaploaded = 1;
var highlight = null;
var rasterloadedname = "'OneChart' View - Click for Individual Charts"; var rasterloadednum = "onechart.c5.5.17";
var map; var marinamap=null; var bridgemap=null; var fuelmap=null; var anchoragemap=null; var alertmap=null; var problemmap=null; var mLoc=null;
if (google.gears) var geo = google.gears.factory.create('beta.geolocation');

google.load("maps", "2.c");
        google.load("elements", "1", {
        packages: ["localsearch"]
});

jQuery(document).ready(function($){
    //$("#menu > ul").tabs();
    load();
    });
   
function load() {
   if (!earthnc_getUrlVariable('em')){show('menubar');} else {
   document.getElementById('minimenu').innerHTML = "<font id='whitelink'><a id='whitelink' href='http://earthnc.com/chartviewer' target='_blank'>EarthNC</a> Easy ChartViewer - <a id='whitelink' href='"+window.location.href.replace('em=1','')+"' target='_blank'>View Full Screen</a> - Not for Navigation</font>";
   show('minimenu')
   }

   if (earthnc_getUrlVariable('ht')){document.getElementById('map').style.height=earthnc_getUrlVariable('ht');}
   if (earthnc_getUrlVariable('wd')){document.getElementById('map').style.width=earthnc_getUrlVariable('wd');}

   if (earthnc_getUrlVariable('ll')){
   lat = earthnc_getUrlVariable('ll').split(',')[0];
   lon = earthnc_getUrlVariable('ll').split(',')[1];
   } 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;
    zoom = 12;
    updatePosition2(lat,lon,zoom);
    }); 
    }
   	else if (google.loader.ClientLocation) {
      zoom = 12;
      lat = google.loader.ClientLocation.latitude;
      lon = google.loader.ClientLocation.longitude;
     }
    */
   }
   
   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(lat, lon), parseInt(zoom)); 
        
        // add highlight icon if called for
        if (earthnc_getUrlVariable('highlight')){
          var hicon = new GIcon(G_DEFAULT_ICON);
          hicon.iconAnchor = new GPoint(18, 68);
          hicon.iconSize = new GSize(37, 35);
          hicon.image = "http://cruisersnet.net/charts/icons/gpin.png";
          highlight = new GMarker(new GLatLng(lat,lon),{icon:hicon});
          map.addOverlay(highlight);
        }
        
        
        map.removeMapType(G_SATELLITE_MAP);
        map.setMapType(G_HYBRID_MAP);
        map.enableContinuousZoom();
			  map.enableScrollWheelZoom();
        resize(); 
        /* Metal Mode */
          // set up pins, use the metalset
          var pins = new Array();
          pins["kml"] = "metalblue";
          pins["local"] = "metalred";

          var labels = new Array();
          labels["kml"] = "metalblue";
          labels["local"] = "metalred";

          // then in options pass:
          // pins : pins, labels : labels
          /**/

          var options = {
            //listingTypes : google.elements.localSearch.TYPE_BLENDED_RESULTS,
            client : 'pub-7720029083570370',
            channel : '1964979155',
            searchFormHint : 'Search the Map',
            Xpins : pins,
            Xlabels : labels
          }
          var bottomLeft= new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(215, 8));
          map.addControl(new google.elements.LocalSearch(options),bottomLeft);

        var publisher_id = 'pub-7720029083570370'; // Replace 1234123412341234 with your Google AdSense publisher id.
        var adPos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 8)); // Set the anchor position and GSize offset to your desired values.
        
        adsManagerOptions = {
        maxAdsOnMap : adcount,
        style: 'adunit',
        channel: '1964979155', // 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();
        

        //callback to update chart overlay as users pan map when layer is 'on'
        GEvent.addListener(map, "moveend", earthnc_chartlookup);   
        GEvent.addListener(map, "zoomend", earthnc_zoomend); 
        
        GEvent.addListener(map, "click", function(overlay, point) {
        if (overlay){
        if (overlay.fpLink) {
        window.open("http://cruisersnet.net/"+overlay.fpLink);
        } else if (overlay.description) {
        overlay.openInfoWindowHtml(overlay.description);
       //close_menus();
        }
        }
        });
        
        // position finder
        
    //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);    
    });    

        //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;
        }
      }
      
    if (earthnc_getUrlVariable("chart")){
    loadraster_single(earthnc_getUrlVariable("chart"));
    } else {loadraster_single("onechart");}

    //comment next line if you do not wish to load the chart layer automatically
    map.setCenter(new GLatLng(lat, lon), parseInt(zoom)); 
    earthnc_chartload();
    earthnc_marinaload();
    //setTimeout(earthnc_bridgeload,5000);
    earthnc_bridgeload();
    //setTimeout(earthnc_anchorageload,9000);
    earthnc_anchorageload();
    earthnc_alertload();
    earthnc_problemload();
}

function getWindowHeight() {
			        if (self.innerHeight) return self.innerHeight;
			        if (document.documentElement && document.documentElement.clientHeight)
			            return document.documentElement.clientHeight;
			        if (document.body) 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 = 60;
              woffset = 120;
			        if (earthnc_getUrlVariable("em")){hoffset = 70;}
			        var mapc = document.getElementById("map");  
			        var header = document.getElementById("menubar"); 
              var height = (getWindowHeight()-hoffset);
              var width =  (getWindowWidth()-woffset);
              if (height<500) height=500;
              if (width<500) width = 500;
              if (width>900) width = 1000;
			        mapc.style.height = height + "px";
			        mapc.style.width =  width+ "px";
			        header.style.width = (getWindowWidth()-woffset) + "px";
			        map.checkResize();
			    } 

 //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;
}

function earthnc_chartlookup(){
    lookupraster();
    var nlat= map.getCenter().lat();
    var nlon= map.getCenter().lng();
    var zoom = map.getZoom();
    var time = new Date();
    var now = time.getTime();
   
    //test for movement magnitude and timeout
    if ((Math.abs(nlat-lat)>.5 || Math.abs(nlon-lon)>.5) && nlon<-45 && nlat>16 && zoom>=5 && (now-then)>12){
      earthnc_zoomend();
      if (document.getElementById("showearthnc").checked){
      var URL = earthnc_getKMLUrl(nlat,nlon);
      if (earthncmap != null){
      map.removeOverlay(earthncmap);
      }
      earthncmap = new GGeoXml(earthnc_getKMLUrl(nlat,nlon));
      map.addOverlay(earthncmap); 
      }
      else {  if (earthncmap!=null) map.removeOverlay(earthncmap); }
      //reset timer
      then = now;
  }
  earthnc_dfuelload();
  earthnc_fuelload();
}

function earthnc_zoomend(){
if (document.getElementById("showmarinas").checked){
      if (marinamap!=null) {
      map.removeOverlay(marinamap);
      earthnc_marinaload();}
}
if (document.getElementById("showbridges").checked){
      if (bridgemap!=null) {
      map.removeOverlay(bridgemap);
      earthnc_bridgeload();}
}
if (document.getElementById("showanchorages").checked){
      if (anchoragemap!=null) {
      map.removeOverlay(anchoragemap);
      earthnc_anchorageload();}
}
if (document.getElementById("showalerts").checked){
      if (alertmap!=null) {
      map.removeOverlay(alertmap);
      earthnc_alertload();}
}
if (document.getElementById("showproblems").checked){
      if (problememap!=null) {
      map.removeOverlay(problememap);
      earthnc_problemload();}
}
}

function earthnc_marinaload(){
if (document.getElementById("showmarinas").checked){
      var bounds = map.getBounds();
      var BBOX = bounds.getSouthWest().lng()+','+bounds.getSouthWest().lat()+','+bounds.getNorthEast().lng()+','+bounds.getNorthEast().lat();
      marinamap = new GGeoXml("http://cruisersnet.net/charts/marinakml_gmap.php?BBOX="+BBOX);
      
      //marinamap = new GGeoXml("http://cruisersnet.net/charts/marina_gmap_nl_c.kml");
      map.addOverlay(marinamap);
      }
      else {if (marinamap!=null) map.removeOverlay(marinamap); marinamap=null;}
}

function earthnc_bridgeload(){
if (document.getElementById("showbridges").checked){
      var bounds = map.getBounds();
      var BBOX = bounds.getSouthWest().lng()+','+bounds.getSouthWest().lat()+','+bounds.getNorthEast().lng()+','+bounds.getNorthEast().lat();
      
      bridgemap = new GGeoXml("http://cruisersnet.net/charts/bridgekml_gmap.php?BBOX="+BBOX);
      map.addOverlay(bridgemap);
      }
      else {if (bridgemap!=null) map.removeOverlay(bridgemap); bridgemap=null;}
}

/*
function earthnc_fuelload(){
if (document.getElementById("showfuelprices").checked){
      fuelmap = new GGeoXml("http://cruisersnet.net/charts/marina_gmap_nl_fuel.kml");
      map.addOverlay(fuelmap);
      }
      else {if (fuelmap!=null) map.removeOverlay(fuelmap); fuelmap=null;}
}
*/

function earthnc_anchorageload(){
if (document.getElementById("showanchorages").checked){
      var bounds = map.getBounds();
      var BBOX = bounds.getSouthWest().lng()+','+bounds.getSouthWest().lat()+','+bounds.getNorthEast().lng()+','+bounds.getNorthEast().lat();
      //anchoragemap = new GGeoXml("http://cruisersnet.net/charts/anchoragekml_gmap.php?BBOX="+BBOX);      
      anchoragemap = new GGeoXml("http://cruisersnet.net/charts/anchoragekml_gmap.php?BBOX="+BBOX);
      map.addOverlay(anchoragemap);
      }
      else {if (anchoragemap!=null) map.removeOverlay(anchoragemap); anchoragemap=null;}
}

function earthnc_alertload(){
if (document.getElementById("showalerts").checked){
      
      var bounds = map.getBounds();
      var BBOX = bounds.getSouthWest().lng()+','+bounds.getSouthWest().lat()+','+bounds.getNorthEast().lng()+','+bounds.getNorthEast().lat();
      alertmap = new GGeoXml("http://cruisersnet.net/charts/alertkml_gmap.php?BBOX="+BBOX);
      //alertmap = new GGeoXml("http://cruisersnet.net/charts/alert_gmap_nl_c.kml");
      map.addOverlay(alertmap);
      }
      else {if (alertmap!=null) map.removeOverlay(alertmap); alertmap=null;}
}

function earthnc_problemload(){
if (document.getElementById("showproblems").checked){
      var bounds = map.getBounds();
      var BBOX = bounds.getSouthWest().lng()+','+bounds.getSouthWest().lat()+','+bounds.getNorthEast().lng()+','+bounds.getNorthEast().lat();
      problemmap = new GGeoXml("http://cruisersnet.net/charts/problemkml_gmap.php?BBOX="+BBOX);
      
      //problemmap = new GGeoXml("http://cruisersnet.net/charts/problem_gmap_nl_c.kml");
      map.addOverlay(problemmap);
      }
      else {if (problemmap!=null) map.removeOverlay(problemmap); problemmap=null;}
}

function earthnc_chartload(){
//  lookupraster();
    var nlat= map.getCenter().lat();
    var nlon= map.getCenter().lng();
    var zoom = map.getZoom();
    var time = new Date();
    var now = time.getTime();
  if (document.getElementById("showearthnc").checked){
    var URL = earthnc_getKMLUrl(nlat,nlon);
    earthncmap = new GGeoXml(earthnc_getKMLUrl(nlat,nlon));
    map.addOverlay(earthncmap); 
  } else {if (earthncmap!=null) map.removeOverlay(earthncmap);}
      //reset timer
      then = now; 
}


function earthnc_routeload(){
  if (document.getElementById("showroutemaker").checked){
  document.getElementById("routemaker").style.display="block";
   }
  else
  {
  document.getElementById("routemaker").style.display="none";
  }
}

function earthnc_routehide(){
document.getElementById("routemaker").style.display="none";
document.getElementById("showroutemaker").checked=false;
}

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 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)

      {

      var yes = confirm("Erase Current Route and Start Over?");

        if (!yes){

        document.getElementById("line_b").className="unselected";

        return;

        } else

        {clearRoute();

        document.getElementById("line_b").className="selected";

         }

      }

      line = new GPolyline([], color);

      GEvent.addListener(line, "lineupdated", function() {

        len = line.getLength();

        var lenkm = (Math.round(len*.539956803 / 10) / 100) + "nm";

        document.getElementById("routedist").innerHTML = "Distance: "+lenkm;

        });

      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 = "Draw Route on Map, Double-Click When Finished";

      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 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 clearRoute(){

    document.getElementById("routedist").innerHTML = "Dist: 0nm";

    document.getElementById("line_b").className="unselected";

    if (line!=null){

    map.removeOverlay(line);

    line = null;

    }

    //startLine();

    document.getElementById("routetext").innerHTML = "Click Icon to Start Route";

    }

    function saveRoute(format){
    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.getElementById('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(){

 var latlon = map.getCenter().lat()+','+map.getCenter().lng();

 jQuery.getJSON("http://cruisersnet.net/charts/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>';

}

}

jQuery("#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;

    lookupraster();

    rasterloadednum = 'onechart';

    rasterloadedname='OneChart View - Click for Individual Charts';

 } else {

 jQuery.getJSON("http://cruisersnet.net/charts/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;

    lookupraster();

    rasterloadednum = selchart[0];

    rasterloadedname=j[0].optionDisplay;

 jQuery("#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;

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"};}

var mercator = new GMercatorProjection(zmax+1);

               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;

			              var tileBounds = new GLatLngBounds(

			                  mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),

			                  mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )

			              );

			              

			              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:zmax,minResolution:zmin,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;}

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 bookmark(){

var url = document.location.href;

var url = url.split("?");

var params = '';

var cent = map.getCenter();

params += '?ll=' + cent.lat() +','+cent.lng();

params += '&z=' + map.getZoom();

  if (earthnc_getUrlVariable('url')){

    params += '&url=' + earthnc_getUrlVariable('url'); 

  }

  if (rastermaploaded==1){

  var tmp  = rasterloadednum.split('.');

  params += '&chart='+tmp[0];

  }

document.getElementById('bmark').value=url[0]+params;

show('bookmark');

selectall('bmark');

//document.location.href=url[0]+params;

}



function getembedcode(){

var url = document.location.href;

var url = url.split("?");

var params = '';

var cent = map.getCenter();

params += '?em=1&ll=' + cent.lat() +','+cent.lng();

params += '&z=' + map.getZoom();

  if (earthnc_getUrlVariable('url') && document.getElementById('embedkml').value!='KML Link'){

    params += '&url=' + earthnc_getUrlVariable('url'); 

  }

  if (document.getElementById('embedkml').value!='KML Link'){

    params += '&url=' + cleanurl(document.getElementById('embedkml').value);

  }

  

  if (rastermaploaded==1){

  var tmp  = rasterloadednum.split('.');

  params += '&chart='+tmp[0];

  }

document.getElementById('embedc').value='<iframe src="'+url[0]+params+'" width="100%" height="600px"></iframe>';

show('embedoutput');

selectall('embedc');

}



function embed(){

show('embed');

}



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 earthnc_openmenu(flag){
if (flag==0){hide('menubar'); show('openmenubar');}
if (flag==1){show('menubar'); hide('openmenubar');}
}

function earthnc_help(){
show('help');
}

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);
      
}

var fuelpricearray = new Array(); var fuel_toggle_flag=false; var fuelpricearraycount=0;
var icons = new Array();

function earthnc_fuelload(){
  if (document.getElementById('showfuelprices').checked){  
  manageExternMarkers('fuelpricearray','fuelprices','all');
  fuel_toggle_flag=true;
} 
else {  
  for (var key in fuelpricearray) {
    map.removeOverlay(fuelpricearray[key]); 
  }
  fuelpricearray = new Array();
  fuelpricearraycount = 0;
  //p_argus=null;
  fuel_toggle_flag=false;
}
}

var dfuelpricearray = new Array(); var dfuel_toggle_flag=false; var dfuelpricearraycount=0;

function earthnc_dfuelload(){
  if (document.getElementById('showfuelpricesd').checked){  
  manageExternMarkers('dfuelpricearray','dfuelprices','all');
  fuel_toggle_flag=true;
} 
else {  
  for (var key in dfuelpricearray) {
    map.removeOverlay(dfuelpricearray[key]); 
  }
  dfuelpricearray = new Array();
  dfuelpricearraycount = 0;
  //p_argus=null;
  dfuel_toggle_flag=false;
}
}

var alertsarray = new Array(); var alerts_toggle_flag=false; var alertsarraycount=0;

function earthnc_nalertload(){
  if (document.getElementById('showalerts').checked){  
  manageExternMarkers('alertsarray','search','alert');
  alerts_toggle_flag=true;
} 
else {  
  for (var key in alertsarray) {
    map.removeOverlay(alertsarray[key]); 
  }
  alertsarray = new Array();
  alertsarraycount = 0;
  //p_argus=null;
  alerts_toggle_flag=false;
}
}

function manageExternMarkers(marray,url,type,mlimit,dicon){
  if (!mlimit) mlimit = 100;
  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 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("http://cruisersnet.net/charts/php/"+url+".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 = icon;
              } else {ticon.image = dicon;}
              ticon.iconAnchor = new GPoint(40, j.results[i].offset);
              icon.infoWindowAnchor = new GPoint(16, 0);
              ticon.iconSize = new GSize(100, 24);
              ticon.shadowSize = new GSize(0, 0);
              ticon.imageMap = [1,1,99,1,99,23,1,23];
              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;
        tmp.extern = url;
        tmp.fpLink = j.results[i].fpLink;
        tmp.description = j.results[i].description;
        map.addOverlay(tmp);
        window[marray][id]= tmp;
        }
      }
    }
});
}


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
}
