// Based on JavaScript provided by Peter Curtis at www.pcurtis.com
var newwindow = '';
var okToGo = false; //gets set to true in getGoogleMap() if map called from a valid host

function popWin(url) {
  if (!newwindow.closed && newwindow.location) {
    newwindow.location.href = url;
    newwindow.focus(); 
  } else {
    newwindow=window.open(url,'htmlname','width=660,height=378,resizable=1'); //imgSize + 20w,28h
  }
}

function tidy() {
  if (!newwindow.closed && newwindow.location) {
    newwindow.close(); 
  }
}



function doCleanupChores() {
  tidy(); //close popup image window
  GUnload(); //reduce memory leaks (new with gmap API v2)
}


/////////////////////////////


var map = '';

// arrays to hold copies of the markers and html used by the menus
// because the function closure trick doesnt work there
var gmarkers = [];
var htmls = [];

var Duluth_html = '';      
var TwoHrbrs_html = '';  
var SilverBay_html = '';
var Schroeder_html = '';
var GrdMarais_html = '';


/*
<li><a href="javaScript:resizeAndMoveTo(Duluth_PT,Duluth_ZM);" rel="Duluth">Duluth</a></li>
<li><a href="javaScript:resizeAndMoveTo(TwoHrbrs_PT,TwoHrbrs_ZM);" rel="TwoHrbrs">Two Harbors</a></li>
<li><a href="javaScript:resizeAndMoveTo(SilverBay_PT,SilverBay_ZM);" rel="SilverBay">Silver Bay</a></li>
<li><a href="javaScript:resizeAndMoveTo(Schroeder_PT,Schroeder_ZM);" rel="Schroeder">Schroeder</a></li>
<li><a href="javaScript:resizeAndMoveTo(GrdMarais_PT,GrdMarais_ZM);" rel="GrdMarais">Grand Marais</a></li>
*/ 



//create and set up the map
function createAndFillMap(xmlFileName) { 

   //create the map
   map = new GMap2(document.getElementById("map")); // v2?

   map.addMapType(G_PHYSICAL_MAP); 


   map.addControl(new GLargeMapControl());
   map.addControl(new GMapTypeControl());
   map.setCenter(START_PT, START_ZOOM, DEFAULT_MAP_TYPE); //v2
         //v2
         GEvent.addListener(map, "click", function() {
          map.getInfoWindow().hide(); //v2
         });

   //read the data from the xml file
   var request = GXmlHttp.create();
   request.open("GET", xmlFileName, true);
   request.onreadystatechange = function() {
     if (request.readyState == 4) {
         var xmlDoc = request.responseXML;
         
         //add the title
         var mapHdg = xmlDoc.documentElement.getElementsByTagName("mapHeading")[0].firstChild.nodeValue; 
         document.getElementById("mapTitle").innerHTML = mapHdg;       
         
         //obtain the array of markers and loop through it
         var markers = xmlDoc.documentElement.getElementsByTagName("marker");
         for (var i = 0; i < markers.length; i++) {
            //obtain the attribues of each marker
            var label = markers[i].getAttribute("label");
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var mnuName = markers[i].getAttribute("mnuName");
            var iconColor = markers[i].getAttribute("mrkr");

            //var html = markers[i].getAttribute("html");
            // FF 1.5 fix ??
            var html = '<div style="white-space:nowrap;">' + markers[i].getAttribute("html") + '</div>';
            
            var point = new GLatLng(lat,lng);
            
            // create the marker (and set menus)
            var marker = createMarker(i,point,label,mnuName,html,iconColor);
            map.addOverlay(marker);
         }
      }
   }
   request.send(null);     
} //createAndFillMap



//create the marker and set up the event window
function createMarker(i,point,name,mnuName,html,iconColor) {

  var myIcon = new GIcon(baseIcon);
  myIcon.image = "./mrkrs/"+ iconColor + ".png";
	//add tooltip here  -- new in APIv2
	var markerOptions = { title:name, icon:myIcon };
	var marker = new GMarker(point, markerOptions);	

  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
  });
  // save the info we need to use later for the sidebar
  gmarkers[i] = marker;
  htmls[i] = html;
  // add a line to the dropdown menu
  document.getElementById(mnuName).innerHTML += '<a href="javascript:myclick(' + i + ')">' + name + '</a>';

  return marker;
}


//pick up the click and opens the corresponding info window
function myclick(i) {
  gmarkers[i].openInfoWindowHtml(htmls[i]);
}

function resizeAndMoveTo(newLoc, zoomLevel) {
        map.getInfoWindow().hide(); //v2
        map.setCenter(newLoc, zoomLevel);
}

function zoomAll() {
  resizeAndMoveTo(START_PT, START_ZOOM);
} 


function goToRegion(){
  // Get the values back
  var args = getArgs(); //Get the arguments
  if (args.region){ //the starting region is specified in the URL -- zoom to it
    var str = args.region.toLowerCase();
    if (str == "duluth"){
      resizeAndMoveTo(Duluth_PT,Duluth_ZM);
      }else if (str == "twohrbrs"){
      resizeAndMoveTo(TwoHrbrs_PT,TwoHrbrs_ZM);  
      }else if (str == "silverbay"){
      resizeAndMoveTo(SilverBay_PT,SilverBay_ZM);
      }else if (str == "schroeder"){
      resizeAndMoveTo(Schroeder_PT,Schroeder_ZM);
      }else if (str == "grdmarais"){
      resizeAndMoveTo(GrdMarais_PT,GrdMarais_ZM);
    } // else ignore -- already at all
  } //else ignore -- future expansion
}


/*
* This function parses comma separated name=value 
* argument pairs from the query string of the URL. 
* It stores the name=value pairs in 
* properties of an object and then returns that object
* 
* From Orielly JSB pp 244
*/
function getArgs() {
  var args = new Object();
  // Get Query String
  var query = location.search.substring(1); 
  // Split query at the comma
  var pairs = query.split("&"); 

  // Begin loop through the querystring
  for(var i = 0; i < pairs.length; i++) {
    
    // Look for "name=value"
    var pos = pairs[i].indexOf('='); 
    // if not found, skip to next
    if (pos == -1) continue; 
    // Extract the name
    var argname = pairs[i].substring(0,pos); 
    
    // Extract the value
    var value = pairs[i].substring(pos+1); 
    // Store as a property
    args[argname] = unescape(value); 
  }
  return args; // Return the Object
}


/*
* Need to use the correct google API key -- depending on if coming from mnbeaches.org or minnesotabeaches.org 
* This function writes the appropriate line...
*/
function getGoogleMap() {
  var theRef = (window.location.href).toLowerCase(); //force lowercase
  
  if ((theRef.indexOf("mnbeaches.org") > -1 ) || (theRef.indexOf("file://") > -1 )){ //NRW 1/23/09 -- now Google lets locally hosted files run gmap
    okToGo = true;
    writeScript("http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAP7OZbLICtyy2TDitZ6VrEhSn0fzWEerSLTVGdzdoVWMAUwKRBRQaxf7zRt3EFVUg3t-N7EgzU2sThA");
  } else if( theRef.indexOf("minnesotabeaches.org") > -1 ){
    okToGo = true;
    writeScript("http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAP7OZbLICtyy2TDitZ6VrEhQxusTgL0x2RhgFmDDHuyWSFPYwuRT55suJV62MpRFU5R4bIojPIMhy8A");
  } else{
     //called from invalid URL
    okToGo = false;
  }    
}


function writeScript(src){
  var ret='<'+'script src="'+src+'"'+'type="text/javascript"><'+'/script>';
  document.write(ret);
} 
  
