

var dlcloading = 0;
var lastzoom;
var idc =0;
var jdc =0;
var gdir;
var tooltip
var side_bar_html ="";
state_bar_html ="";
var map;
var infoTabs;
var directions = 0;
var campmarkers =[];
var campinfo =[];
var log;
var campIcon;
var attractionIcon;
var restareaIcon;
var servicesIcon;
var url = "http://www.maprvs.com/map/campmapsection2.php";
var detailLayer = new GTileLayer(new GCopyrightCollection(''));
var back = 0;

//Method to retrieve the URL of the tile
detailLayer.getTileUrl = function(tile, zoom){
    //pass the x and y position as wel as the zoom
    var tileURL = "http://www.maprvs.com/map/server.php?x="+tile.x+"&y="+tile.y+"&zoom="+zoom;
    return tileURL;   
};

detailLayer.isPng = function() {
    //The example uses GIF's
    return false;
}
function mapload() {
    if (GBrowserIsCompatible()) {
    	var myFx = new Fx.Style('dlcspinner', 'opacity').set(0);
        map = new GMap2(document.getElementById('map'));
        gdir = new GDirections(map, document.getElementById('details'));
         
               //add your tiles to the normal map projection
detailMapLayers = G_NORMAL_MAP.getTileLayers();
detailMapLayers.push(detailLayer);
//add your tiles to the satellite map projection
detailMapLayers = G_SATELLITE_MAP.getTileLayers();
detailMapLayers.push(detailLayer);
iconsize = 20;
         campIcon = MapIconMaker.createMarkerIcon({width: iconsize, height: iconsize, primaryColor: "#00ff00"});
        attractionIcon = MapIconMaker.createMarkerIcon({width: iconsize, height: iconsize, primaryColor: "#f3f60c"});
         restareaIcon = MapIconMaker.createMarkerIcon({width: iconsize, height: iconsize, primaryColor: "#0000ff"});     
         servicesIcon = MapIconMaker.createMarkerIcon({width: iconsize, height: iconsize, primaryColor: "#fc9e17"});
         iconsize = 50;
          campIconLRG = MapIconMaker.createMarkerIcon({width: iconsize, height: iconsize, primaryColor: "#00ff00"});
        attractionIconLRG = MapIconMaker.createMarkerIcon({width: iconsize, height: iconsize, primaryColor: "#f3f60c"});
         
         
var options = {
	suppressInitialResultSelection : true,
    resultList : document.getElementById("results")
  };
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
       map.addControl(new google.maps.LocalSearch(options));
        map.addControl(new GOverviewMapControl());
       var adsManager = new GAdsManager(map, "pub-6531079799923733");
        adsManager.enable();
        map.setCenter(new GLatLng(40.645,-95.14), 4);
        
         tooltip = document.createElement("div");
      map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
      tooltip.style.visibility="hidden";
      
    }  
    
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
    GEvent.addListener(map, "moveend", function() {
        getMarkers();
    });
     GEvent.addListener(map, "click", function(marker,point) {
      if(marker){
	//	 marker.openInfoWindowTabsHtml(infoTabs);
	}else{
	zoomin(point);	
	}
       
    });
    
}
/************************************************************\
*clearOverlays()
\************************************************************/
function getMarkers(){
 if(directions ==0){
campmarkers.length = 0;
zoomlevel = map.getZoom();

    if(zoomlevel >7 && !dlcloading){
  
    latlng = map.getBounds();
	nlat = latlng.getNorthEast().y;
    slat = latlng.getSouthWest().y;
    wlng = latlng.getSouthWest().x;
    elng = latlng.getNorthEast().x;
   // params = $H({sl:slat,nl:nlat,wl:wlng,el:elng}).toQueryString();
   params = Object.toQueryString({sl:slat,nl:nlat,wl:wlng,el:elng});
    
    
  var myFx = new Fx.Style('dlcspinner', 'opacity').start(0,1);
  dlcloading = 1;
    var myAjax = new Ajax(url, {method: 'get',data: params,onComplete:evalmarks});
myAjax.request();

   }else{
   	if(zoomlevel < lastzoom){
   	map.clearOverlays();
$("details").innerHTML = '&nbsp;';

   }
   } 
   }
   lastzoom = zoomlevel;
}

function evalmarks(response){


var marks = evalResponse(response);
for (var i = 0; i < marks.length; i++) {
                ov = dlccreateMarker(marks[i],i);
                map.addOverlay(ov);
             }
			 var myFx = new Fx.Style('dlcspinner', 'opacity').start(1,0);
dlcloading = 0;	
}

/************************************************************\
*
\************************************************************/
function makesidebartwo(marks){
	side_bar_html = "";
	 singlehtml ='';          
	  multihtml='';
	        	   if(marks[9].length>0){ 
		                first = 0;    
			            multihold = '';
		                multihtml='<div class="detailsdiv">';
			                 for(dca=0;dca<marks[9].length;dca++){
			                  multihold2 = marks[9][dca][0];
		   	                       if(multihold != multihold2){
			                              if(first==0){first =1}else{multihtml += "<br />"}
				   	                       multihtml += "<span class=\"lead\">"+marks[9][dca][0]+"</span>&nbsp;";				 			
			                        }
			                        multihtml += ""+marks[9][dca][1]+"&nbsp;&nbsp;";
			                        multihold = marks[9][dca][0];	
			                 }
		                     multihtml += "</div>";
                     }   
		          if(marks[8].length>0){
			      singlehtml='<div>';
			            for(dcz=0;dcz<marks[8].length;dcz++){
			                singlehtml += "<span class=\"lead\">"+marks[8][dcz][0]+"</span> "+marks[8][dcz][1]+"<br>";	
			            }
		                singlehtml += "</div>"
		           }
	side_bar_html +='<div><h3>' + marks[0] + '</h3><div><div class="campadd"> '+marks[4]+'<br>'+marks[5]+','+marks[6]+'<br>'+marks[7]+'<br></div>'+singlehtml+multihtml+'<br><div>'+marks[10]+'</div></div></div><div id="googad"></div>'; 
	
$("details").innerHTML = side_bar_html;	
}
/************************************************************\
*
\************************************************************/
function dlccreateMarker(marks,index) {
    var pnt = new GLatLng(marks[2],marks[3]);
    //dlccreateMarker(point, marks[i][0],marks[i][1],marks[i][4],marks[i][5],marks[i][6],marks[i][7],marks[i][8],marks[i][9],marks[i][10],marks[11])
                       //array(title,  url,        street,       city,      region,     phone,     single,      multi,     weather   pin   );
    linkinsert = "";
    dirhtml = '<form action="#" onsubmit="setDirections(this.from.value, this.to.value); return false">';
    dirhtml += 'From:&nbsp;<input type="text" size="25" id="fromAddress" name="from" value="Enter address"/><br>';
    dirhtml += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To:&nbsp;<input type="text" size="25" id="toAddress" name="to" value="'+marks[4]+' '+marks[5]+','+marks[6]+'" />';
    dirhtml += '<br /><br /><input name="submit" type="submit" value="Get Directions!" style="align:center;" /></form>';
    var camparray = new Array();
    var pin = marks[12];
    pin = parseInt(pin);
    if(pin==1){
	var marker = new GMarker(pnt, campIconLRG);	
	}else{
	var marker = new GMarker(pnt,attractionIconLRG);	
	}
	
    switch(pin)
{
case 1:
 // var marker = new GMarker(pnt, iconcampground);
  
        var marker = new GMarker(pnt, campIcon); 
  break;    
case 2:
 var marker = new GMarker(pnt,attractionIcon);
  break;
case 3:
 var marker = new GMarker(pnt,servicesIcon);
  break;
case 4:
 var marker = new GMarker(pnt,restareaIcon);
  break;    
default:
 var marker = new GMarker(pnt, campIcon);
}
    //var marker = new GMarker(pnt, iconred);
    marker.tooltip = '<div class="tooltip" style="background:white;font-size:16px;" ><nobr>'+marks[0]+'</nobr><p>'+marks[5]+','+marks[6]+'</p></div>';
    var infoTabs = [new GInfoWindowTab("EQ","<div style=\"background-color:white;width:250px;height:200px;\" id=\"infoone\"><br><dl><dd> <a href=\""+marks[1]+"\" target=\"_blank\">" + marks[0] + "</a></dd><dd> "+marks[4]+"</dd><dd> "+marks[5]+","+marks[6]+"</dd><dd> "+marks[7]+"</dd></dl> "+dirhtml+" </div>")
    ];
    
    GEvent.addListener(marker, "click", function() { 	
        marker.openInfoWindowTabsHtml(infoTabs);   
    });
  
    GEvent.addListener(marker, "click", function() { 	
    makesidebartwo(marks);  
    });
    GEvent.addListener(marker,"mouseover", function() {
          showTooltip(marker);
        });        
        GEvent.addListener(marker,"mouseout", function() {
		tooltip.style.visibility="hidden"
        });
    campmarkers[index] = marker;
    return marker;
}
/************************************************************\
*
\************************************************************/
function zoomin(point){
 zoom = map.getZoom();
    map.closeInfoWindow();
    map.setCenter(point,zoom);
    map.zoomIn();  
}
/************************************************************\
*
\************************************************************/
function myclick(gdc) {
    GEvent.trigger(statemarkers[gdc], "click");
}
/************************************************************\
*
\************************************************************/
function mycampclick(gdc) {
    GEvent.trigger(campmarkers[gdc], "click");
} 
/************************************************************\
*
\************************************************************/

evalResponse = function(request) {
    try {
        return eval('('+request+')');
    } catch (e) {}
}
/************************************************************\
*
\************************************************************/
function setDirections(fromAddress, toAddress) {
 directions = 1;
 map.clearOverlays();
 document.getElementById("details").innerHTML = '';
 gdir = new GDirections(map, document.getElementById("details"));
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": 'en' });
                map.savePosition();
                //new Insertion.Bottom("details","<a href=\"javascript:returnToOZ()\">Return to Map</a>");
                var snap = document.getElementById("details").innerHTML;
                document.getElementById("details").innerHTML = snap +"<a href=\"javascript:returnToOZ()\">Return to Map</a>";
    }
    
/************************************************************\
*
\************************************************************/    
function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}
	
	
	function onGDirectionsLoad(){ 
          // Use this function to access information about the latest load()
          // results.

          // e.g.
	  // document.getElementById("details").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
	function returnToOZ(){
		$("details").innerHTML = '';	
		directions = 0;
		map.clearOverlays();
		map.returnToSavedPosition(); 
		getMarkers();
		
	}
	function showTooltip(marker) {
      	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
      }
      
var MapIconMaker={};
MapIconMaker.createMarkerIcon=function(a){var b=a.width||32;var c=a.height||32;var d=a.primaryColor||"#ff0000";var e=a.strokeColor||"#000000";var f=a.cornerColor||"#ffffff";var g="http://chart.apis.google.com/chart?cht=mm";var h=g+"&chs="+b+"x"+c+"&chco="+f.replace("#","")+","+d.replace("#","")+","+e.replace("#","")+"&ext=.png";var j=new GIcon(G_DEFAULT_ICON);j.image=h;j.iconSize=new GSize(b,c);j.shadowSize=new GSize(Math.floor(b*1.6),c);j.iconAnchor=new GPoint(b/2,c);j.infoWindowAnchor=new GPoint(b/2,Math.floor(c/12));j.printImage=h+"&chof=gif";j.mozPrintImage=h+"&chf=bg,s,ECECD8"+"&chof=gif";var h=g+"&chs="+b+"x"+c+"&chco="+f.replace("#","")+","+d.replace("#","")+","+e.replace("#","");j.transparent=h+"&chf=a,s,ffffff11&ext=.png";j.imageMap=[b/2,c,(7/16)*b,(5/8)*c,(5/16)*b,(7/16)*c,(7/32)*b,(5/16)*c,(5/16)*b,(1/8)*c,(1/2)*b,0,(11/16)*b,(1/8)*c,(25/32)*b,(5/16)*c,(11/16)*b,(7/16)*c,(9/16)*b,(5/8)*c];for(var i=0;i<j.imageMap.length;i++){j.imageMap[i]=parseInt(j.imageMap[i])}return j}
	
