//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 chartmap = null;
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;
var goverlays = [];
var gmarkers = [];
var htmls = [];
var movList = null;

if (google.gears) var geo = google.gears.factory.create('beta.geolocation');

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

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

resize();

//turn on ad if wide enough
//el('debug').innerHTML = getWindowWidth();
if (getWindowWidth()>630 && !earthnc_getUrlVariable("em")){
  el('horizontalBanner').style.display="block";
  if (getWindowWidth()>975) el('horizontalBanner').style.bottom="-60px";
}

function EarthNCLogoControl() {}
EarthNCLogoControl.prototype = new GControl();
EarthNCLogoControl.prototype.initialize = function(map) {
  var container=document.createElement("div");
  container.setAttribute("id","earthlogo");
  //container.setAttribute("style","width:250px");
  var zoomInDiv=document.createElement("div");this.setButtonStyle_(zoomInDiv);
  zoomInDiv.setAttribute("style","width:250px");
  container.appendChild(zoomInDiv);
   
  var img=document.createElement('img');
  img.setAttribute('src','images/map_logo.png');//old file is map_logo.jpg
  img.setAttribute('style','align:left');     
   zoomInDiv.appendChild(img);
   //zoomInDiv.innerHTML = '&copy;2010 EarthNC, Inc Terms of Use';
   GEvent.addDomListener(img,"click",function(){
   window.open('http://earthnc.com');
   });
   
   var cright = document.createElement('div');
   cright.innerHTML = 'Charts &copy;2010 EarthNC - Terms of Use';
   cright.setAttribute("style","position:relative;color:#fff;font-weight:bold;font-size:0.8em;");
   //zoomInDiv.appendChild(cright);
   GEvent.addDomListener(cright,"click",function(){
   window.open('http://earthnc.com/terms-and-conditions');
   });
    
  map.getContainer().appendChild(container);return container;}

EarthNCLogoControl.prototype.getDefaultPosition = function() {
	  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 7));//for embedde mode and hide left panel 
  }

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;
        map.addMapType(G_SATELLITE_3D_MAP);
        //add topo
        //map.addMapType(MYTOPO_MAP);
        } else {
          map.addControl(new GSmallMapControl()); var adcount=1;
          
          }        
        map.setCenter(new GLatLng(tlat, tlon), parseInt(zoom)); 
        map.removeMapType(G_SATELLITE_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();  //for disable advertize on the map
        

         //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;
        }
      }
      
      //marinalife demo
      if (earthnc_getUrlVariable("mld") && earthnc_getUrlVariable("mld")=="1"){
        
        el("lighted_bouys").checked='false';
        hide('marinas_id');
        show('marinas_on_id');

        el("showmarinalifemarinas").checked='true';
        marina_check('marinalife');
        earthnc_marinalifeload();
        
        //load template
        var MLgeoXml = new GGeoXml("http://earthnc.com/kml/FloridaKeysMarinalifeGmap2.kml"); 
        map.addOverlay(MLgeoXml);
      
      } else {
      show_navidas();
      }
      /*
      GEvent.addListener(map,"addoverlay",function(overlay) {
        // If this is a named overlay (e.g. not the GGeoXml itself, or the infowindow)
        if (overlay.name) {
          // check to see if we already know about this one
          if (overlay.Known) {
            // do nothing
          } else {
            // Add a sidebar entry
            document.getElementById("searchResults").innerHTML  += '<a href="javascript:myclick(' + goverlays.length + ')">' + overlay.name + '<\/a><br>';
            // Save a reference
            goverlays.push(overlay);
            // remember that we know about this one
            overlay.Known = true;
          }
        }
      }); 
	   */
    //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();
	earthnc_chartload_1();
  
  
    //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'
  movList = GEvent.addListener(map, "moveend", enc_showmarkers);  
  GEvent.addListener(map, "click", function(overlay, point) {
   if (overlay) {
     // disable the move listener while the overlay 'pops'
     GEvent.removeListener(movList);
     // 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();
     }
   //restore the move listener
   setTimeout(function(){
      movList = GEvent.addListener(map, "moveend", enc_showmarkers);
   },5000);   
   }
 });
 



searchControl = new google.search.SearchControl();
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
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){
		
	var Icon = new GIcon(G_DEFAULT_ICON);
    Icon.image = "images/coldmarker.png";
	Icon.shadow = "images/shadow.png";
	Icon.iconSize = new GSize(24,24);
	
	
   
	
	
	    // A function to create the marker and set up the event window
      function createMarker(i,point,name,html) {
        var marker = new GMarker(point,Icon);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
         
        // Switch icon on marker mouseover and mouseout
        GEvent.addListener(marker, "mouseover", function() {
          //marker.setImage("images/marker.png");
		  marker.setImage("images/pushpins/"+i+"_h.png");
		  mouseover_effect(name,'show',i,'google-'+i);
        });
		
        GEvent.addListener(marker, "mouseout", function() { 
          //marker.setImage("images/coldmarker.png");
		  marker.setImage("images/pushpins/"+i+".png");
		  mouseover_effect(name,'hide',i,'google-'+i);
        });
		
        //globaly defined
		gmarkers[i] = marker;
        htmls[i] = html;
	
       return marker;
      }
	   
    for (var i = 0; i < results.length; i++) {
    
      result_counter++;//increse result counter
      var result = results[i]; // Get the specific result
	 
	 var Icon = new GIcon(G_DEFAULT_ICON);
    Icon.image = "images/pushpins/"+result_counter+".png";
	//Icon.shadow = "images/shadow.png";
	Icon.iconSize = new GSize(24,24);
	 
	 
     
      //var marker = new google.maps.Marker(markerLatLng,tmpmarkerOptions); // Create the marker
	  
	 var lat =parseFloat(result.lat);
            var lng = parseFloat(result.lng);
            var point = new GLatLng(lat,lng);
            var html = result.html.innerHTML;
            var label = result.title;
            // create the marker
			
            var marker = createMarker(result_counter,point,label,html);
			
            map.addOverlay(marker);
	       window['gsearch']['google-'+result_counter]= marker;
	 
	 
	 
	  
	  
      // put in result list
      var tmp = document.createElement('div');
      tmp.setAttribute('id','google-'+result_counter);
      tmp.setAttribute('lat',parseFloat(result.lat));
      tmp.setAttribute('lon',parseFloat(result.lng));
	 tmp.setAttribute('onmouseover',"mouseover_effect('"+result.title+"','show',"+result_counter+",'google-"+result_counter+"')");
	  tmp.setAttribute('onmouseout',"mouseover_effect('"+result.title+"','hide',"+result_counter+",'google-"+result_counter+"')");
      tmp.setAttribute('class','esResult');
      tmp.google = result.html.innerHTML;
      tmp.innerHTML = '<table cellspacing="0" cellpadding="0" border="0" width="95%" style="#width:92%"><tr><td><div class="esRTitle"><table cellspacing="3" cellpadding="1" border="0" width="100%"><tr> <td style="padding-right:5px" valign="top" width="20"><img src="'+Icon.image+'"  id="image-'+result_counter+'"  height="24px" ></td><td align="left" ><a  href="javascript:searchDetail(\'google-'+result_counter+'\');searchGoto(\'google-'+result_counter+'\');" >'+result.title+'</a></td></tr></table></div></td></tr></table>';
	 
      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);
	searchChart('all:'+el('searchText').value);
    } 
	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();
  
  
  //set dynamic logo
  document.getElementById('earthlogo').style.right='49%';
}

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 (window.innerWidth) return window.innerWidth;
   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")){
    if (earthnc_getUrlVariable("em")==1){hoffset = 90;} else {hoffset=125;}
    } else {hoffset = 235;}
	var mapc = document.getElementById("map"); 
	
	var window_width = getWindowWidth();
	var window_hight = getWindowHeight();//alert(window_width);
	
	
	if(earthnc_getUrlVariable('em'))  //orignal condition is if(!earthnc_getUrlVariable('em')) i have modified it like if(earthnc_getUrlVariable('em'))
	{
	 var emt = earthnc_getUrlVariable('em');
	 //hide top banner ad and search bar
	 if (emt==1){
	 hide("round_left");
	 hide("social");
	 hide("help_btn_on_id");
	 hide("embed_open");
   hide("router_btn_id");
	 hide("advance_dropdown_on");
	 }
	 hide("banner_top"); 
	 show("fullscreen_btn_on_id");
	}
		mapc.style.height = (window_hight-hoffset) + "px";	        
} 
         
			    
// new earthnc Marker function
function enc_showmarkers(){
lookupraster();
reloadExtern();
//set up earthnc layers 
var types = new Array();

if (document.getElementById("lighted_bouys").checked){types.push("marker");}
if (document.getElementById("mile_markers").checked){types.push("milepost");}
if (document.getElementById("bridges").checked){types.push("bridge");}
if (document.getElementById("reefs").checked){types.push("wreck");}
if (document.getElementById("metar").checked){types.push("metar");}
if (document.getElementById("wxbuoys").checked){types.push("wxbuoy");}
if (document.getElementById("forecast").checked){types.push("marfor");}
if (document.getElementById("tides").checked){types.push("tide");}
if (document.getElementById("boat_ramps").checked){types.push("ramps");}
if (document.getElementById("cplaces").checked){types.push("seaArea");}

if (types.length>0){  
  //  hide('navaids');show('navaids_on');
  manageMarkers('markersmap',types);
} 
else {  //show('navaids');hide('navaids_on');
  for (var key in markersmap) {
    map.removeOverlay(markersmap[key]); 
  }
  markersmap = new Array();
  markersmapcount = 0;
}

//update KML layers
if (document.getElementById("showmarinalifemarinas").checked){
      if (p_marinalife1!=null) {
      map.removeOverlay(p_marinalife1);
      p_marinalife1=null;
      earthnc_marinalifeload();}
}
if (document.getElementById("showcnetmarinas").checked){
      if (p_cruisersnet1!=null) {
      map.removeOverlay(p_cruisersnet1);
      p_cruisersnet1=null;
      cnet_marinaload();}
}
if (document.getElementById("showcnetbridges").checked){
      if (p_cruisersnet2!=null) {
      map.removeOverlay(p_cruisersnet2);
      p_cruisersnet2=null;
      cnet_bridgeload();}
}
if (document.getElementById("showcnetanchorages").checked){
      if (p_cruisersnet3!=null) {
      map.removeOverlay(p_cruisersnet3);
      p_cruisersnet3=null;
      cnet_anchorageload();}
}
if (document.getElementById("showwwgmarina").checked){
      if (p_wwg1!=null) {
      map.removeOverlay(p_wwg1);
      p_wwg1=null;
      wwg_marinaload();}
}

if (document.getElementById("showwwganchorage").checked){
      if (p_wwg3!=null) {
      map.removeOverlay(p_wwg3);
      p_wwg3=null;
      wwg_anchorageload();}
}

if (document.getElementById("showwwgbridge").checked){
      if (p_wwg2!=null) {
      map.removeOverlay(p_wwg2);
      p_wwg2=null;
      wwg_bridgeload();}
}

}

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

  function createPoiMarker(i,point,Icon,name,result_counter_i,id) {
        var marker = new GMarker(point,Icon);
         
        // Switch icon on marker mouseover and mouseout
        GEvent.addListener(marker, "mouseover", function() {
          mouseover_effect(name,'show',result_counter_i,id);
		 });
		
        GEvent.addListener(marker, "mouseout", function() { 
           mouseover_effect(name,'hide',result_counter_i,id);
        });

       return marker;
}

function manageMarkers(marray,types,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;
  //create the type string
  var type = ""
  
  var tlen = types.length;
  if (tlen>1){
    type = types[0];
    for (var i=1; i<tlen; i++){
      type = type + '|' + types[i];
    }
  } else {type = types[0];}
  
  //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 point = new GLatLng(j.results[i].latitude,j.results[i].longitude);
        var tmp = createPoiMarker(i,point,ticon,sname,-1,id);
        
        //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;
  var lat = window[marray][did].getLatLng().lat();
  var lon = window[marray][did].getLatLng().lng();
  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://earthnc.com/iphone-marine-charts" target="_blank"><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"});

       //for showing route popup box on clicking on route.
	   GEvent.addListener(poly, "click", function() {
												  show('route');
												  show('router_btn_on_id');
												  hide('router_btn_id');
												  earthnc_routeload();
												  startLine();
												  });

      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 = 2;
    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 = "onechart.c5.5.17";//document.getElementById("rastercharts");  //set default value coz now v dont have selection box in chart box 
//var selchart = (rselect.options[rselect.selectedIndex].value).split(".");
var selchart = rselect.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(), "Hybrid Charts", {maxResolution:17,minResolution:2,errorMessage:"Outside of Chart Area, Select a Different Chart and Click Load or Clear to Remove"});



tilelayers2 = new GTileLayer(new GCopyrightCollection("EarthNC, Inc"),zmin,zmax);
                                tilelayers2.getCopyright = function (a,b){return {prefix: "EarthNC, Inc"};}
                                               if (rchart=='onechart'){
                                               tilelayers2.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 {
                                			         tilelayers2.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;
			          }
 			          }
 tilelayers2.getOpacity = function() {return 1;}

var hybridlayer2 = [tilelayers2];
 if (chartmap){map.removeMapType(chartmap);}
 chartmap = new GMapType(hybridlayer2, 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"});

if (!earthnc_getUrlVariable('em')){
map.addMapType(chartmap);
}
map.addMapType(rastermap);
map.setMapType(rastermap);
}

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

function removeLayer(){ 
 rastermaploaded=0; 
 //lookupraster();  removing this because now we don't have chart box.
 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;

}






