//clientside functions, goodle maps, ajax calls, shortcode generator
    var side_bar_html = "";
    var gmarkers = [];
    var htmls = [];
    var i = 0;
    var map = null;
    var ajaxurl="http://gulfcoastgeocache.com/wp-admin/admin-ajax.php";
    var vectorID;
    var cacheID;
    var editFlag;
    var frmlat;
    var frmlng;
    var shortcodeOpts = null;
    
    
/*
* following is included from jsblockfade.
* TODO: replace with jquery
*/
    var TimeToFade = 800.0;
    
    function fade(el){
    
      var element = document.getElementById(el);
      if(element == null)
      return;
      
      if(element.FadeState == null){
      element.FadeState = -2;
      }
      
        if(element.FadeState == 1 || element.FadeState == -1){
        element.FadeState = element.FadeState == 1 ? -1 : 1;
        element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
        
        }else{
          element.FadeState = element.FadeState == 2 ? -1 : 1;
          element.FadeTimeLeft = TimeToFade;
          setTimeout("animateFade(" + new Date().getTime() + ",'" + el + "')", 33);
        }
    }
    
    function animateFade(lastTick, el){
    
      var curTick = new Date().getTime();
      var elapsedTicks = curTick - lastTick;
      
      var element = document.getElementById(el);
      
      if(element.FadeTimeLeft <= elapsedTicks){
        
        element.style.opacity = element.FadeState == 1 ? '1' : '0';
        element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
        element.FadeState = element.FadeState == 1 ? 2 : -2;
        
        return;
      }
      
      element.FadeTimeLeft -= elapsedTicks;
      var newOpVal = element.FadeTimeLeft/TimeToFade;
      if(element.FadeState == 1) newOpVal = 1 - newOpVal;
      
      element.style.opacity = newOpVal;
      element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
      
      setTimeout("animateFade(" + curTick + ",'" + el + "')", 33);
    }
 
/*
* end jsblockfade
*/

    
    
    defaultHandler=function(defaults,params) {
      //merge parms list ontop of default list
      var i;
      for (i in params) {
          defaults[i]=params[i];
      }
      return defaults;
    }
    
    
    //TODO: use jquery
    function toggleAdvancedOptions(coords){
      var dispState = document.getElementById("AdvancedOptions").style.display;
      var theCoords = coords.split(',');
      if (dispState  == "none") {
          document.getElementById("AdvancedOptions").style.display = "block"
         // alert("lat: " + theCoords[0] + " lng: " + theCoords[1] + " zm: " + theCoords[2]);

          loadHelperMap("2",theCoords[0],theCoords[1],theCoords[2]); 
      }else{
          GUnload();
          helperMap=null;
          document.getElementById("AdvancedOptions").style.display="none";
      }
    }
    
    function genShortcode(id){
      var theform = document.gcgcPublishForm;
      var theValue;
      var scode = '[GCGCMap id='+id;
      
      for (i=0;i<theform.gcgc_publish_to.length;i++) {
      	if (theform.gcgc_publish_to[i].checked) {
      	 if (theform.gcgc_publish_to[i].value == "widget"){
      	   scode += ' widget=1' ;
      	 }
      	}
      }
      
      for (i=0;i<theform.gcgc_publish_as.length;i++) {
      	if (theform.gcgc_publish_as[i].checked) {
      		scode += ' render=' + theform.gcgc_publish_as[i].value;
      	}
      }
      
      theValue = theform.gcgc_publish_map_size.value;
      if (!theValue == ''){
        scode += ' mapsize=' + theValue;
      }
      
      theValue = theform.gcgc_publish_infowidth.value;
      if (!theValue == ''){
        scode += ' iwin=' + theValue;
      }

      
      theValue = theform.gcgc_publish_map_zoom.value;
      if (!theValue == ''){
        scode += ' mapzoom=' + theValue;
      }
      
     // theValue = theform.gcgc_auto_fit.value;
      if (theform.gcgc_auto_fit.checked){
        scode += ' autofit=true';
      }else{
        scode += ' autofit=false';
      }
      
      for (i=0;i<theform.gcgc_publish_map_float.length;i++) {
      	if (theform.gcgc_publish_map_float[i].checked) {
      		scode += ' float=' + theform.gcgc_publish_map_float[i].value;
      	}
      }

      for (i=0;i<theform.gcgc_publish_mapsidebar.length;i++) {
      	if (theform.gcgc_publish_mapsidebar[i].checked) {
      	 if (theform.gcgc_publish_mapsidebar[i].value == "yes"){
      		scode += ' sb=' + theform.gcgc_publish_mapsidebar[i].value;
      	 }
      	}
      }

      for (i=0;i<theform.gcgc_publish_maptype.length;i++) {
      	if (theform.gcgc_publish_maptype[i].checked) {
      		scode += ' maptype=' + theform.gcgc_publish_maptype[i].value;
      	}
      }
      
      for (i=0;i<theform.gcgc_publish_maptypecontrol.length;i++) {
      	if (theform.gcgc_publish_maptypecontrol[i].checked){
          if (!theValue == ''){
            scode += ' maptypecontrol=' + theform.gcgc_publish_maptypecontrol[i].value;
          }
        }
      }
      
      for (i=0;i<theform.gcgc_publish_mapcontrol.length;i++) {
      	if (theform.gcgc_publish_mapcontrol[i].checked) {
      	  scode += ' mapcontrol=' + theform.gcgc_publish_mapcontrol[i].value;
      	}
      }
      
      scode += ']';
     theform.gcgc_shortcode.value = scode;
     return false;
    }
             
    function doVectorMapShortcode(opts){
      shortcodeOpts = opts;
      var div = shortcodeOpts['div'];
      vectorID = shortcodeOpts['id'];
      var mapcount = shortcodeOpts['count'];
      window['mapobj' + mapcount] = getMap(div);
      readMapData(vectorID, window['mapobj' + mapcount]);
      smallPause(1000);
    }
    
    function addLoadEvent(func) {
    //I think jquery handles the function chaining. Put your function in a  $ on ready event
    //and this functions isn't necessary
  	  var oldonload = window.onload; 
  	  if (typeof window.onload != 'function') {
    	    window.onload = func; 
    	 }else{
          window.onload = function() {
             if (oldonload) {
               oldonload();
               }
           func();
          }
	     }
  	}
    
    function ajaxRefreshCacheTable(id){
      //alert ('ajaxRefreshcachetable->'+id)
      var usack = new sack(ajaxurl);
      usack.execute = 0;
      usack.method = 'POST';
      usack.setVar('action', 'refreshCacheTable');
      usack.setVar('id', id);
      usack.element = 'gcgc-cache-table';
      //usack.onCompletion  = function() { alert(usack.response);   }
      usack.onError = function() { alert('Ajax error in retrieving data from server. '); };
      usack.runAJAX();
      return ;       
    }
    
    
    function ajaxLoadCacheForm(id){
      var mySack = new sack(ajaxurl);
      mySack.execute = 0;
      mySack.setVar('action', 'loadCacheTable');
      mySack.setVar('id', id);
      mySack.element = 'gcgc-cache-table';
      mySack.onCompletion  = function() { 
          //alert(mySack.response); 
          }
      mySackonError = function() { alert('Ajax error in retrieving data from server. '); };
      mySack.runAJAX();
      return ;  
    }
    
    function ajaxPostCacheForm(event, id){
    //id will be empty on Insert
      var mysack = new sack(ajaxurl);
      tinyMCE.triggerSave(false, false);
      var cform = document.getElementById('cacheForm');
      for(i=0; i<cform.elements.length; i++){
        if( cform.elements[i].type == "radio"){
           if(cform.elements[i].checked == true ){
               mysack.setVar(cform.elements[i].name, cform.elements[i].value );
           }
        }else{
          mysack.setVar(cform.elements[i].name, cform.elements[i].value );
        }
      }

      mysack.execute = 0;
      mysack.method = 'POST';
      mysack.setVar('action', 'postCacheForm');
      mysack.setVar('event',event);
      mysack.onCompletion  = function() { 
          alert('The Geocache data has been saved. '); 
        //alert (mysack.response);
          }
      mysack.onError = function() { alert('Ajax error in saving form data to server. '); };
      mysack.runAJAX();
      return ;    
    }
    
    function ajaxDoCacheUpdate(event, id){
      ajaxPostCacheForm(event, id);
      ajaxRefreshCacheTable(id);
      if (event == 'insert'){pvFlag = "1";}
        loadHelperMap(pvFlag, pvclat, pvclng, pvzm); 
      return ;
    }
    
     
    function getMap (mapContainer){
      if (GBrowserIsCompatible()) {
        var newmap = new GMap2(document.getElementById(mapContainer));
          if (shortcodeOpts != null){
            if (shortcodeOpts['mapzoom']){
              // newmap.setZoom(shortcodeOpts['mapzoom']);
             }
           
            if (shortcodeOpts['maptype']){  
              switch (shortcodeOpts['maptype']){
               case 'G_NORMAL_MAP':   newmap.setMapType(G_NORMAL_MAP); break;
               case 'G_SATELLITE_MAP': newmap.setMapType(G_SATELLITE_MAP); break;
               case 'G_HYBRID_MAP':   newmap.setMapType(G_HYBRID_MAP); break;
               case 'G_PHYSICAL_MAP':   newmap.setMapType(G_PHYSICAL_MAP); break;       
               }
            }
            
            if (shortcodeOpts['maptypecontrol'] == 'Yes'){
               newmap.addControl(new GMapTypeControl());
             }
                   
            if (shortcodeOpts['mapcontrol']){
              switch (shortcodeOpts['mapcontrol']){
               case 'GLargeMapControl':   newmap.addControl(new GLargeMapControl()); break;
               case 'GLargeMapControl3D': newmap.addControl(new GLargeMapControl3D()); break;
               case 'GSmallMapControl':   newmap.addControl(new GSmallMapControl()); break;
               case 'GSmallZoomControl3D': newmap.addControl(new GSmallZoomControl3D()); break;
               case 'GSmallZoomControl': newmap.addControl(new GSmallZoomControl()); break;
               case 'GSmallMapControl':   newmap.addControl(new GSmallMapControl()); break;
               case 'NoControl' : break;
               }
             }
             if (shortcodeOpts['minwin']){
              newmap.minwin = true;
             }
             if (shortcodeOpts['autofit']){
              newmap.autofit = true;
             }
            shortcodeOpts = null;
          
          }else{
              //Need handle to php gcgcoptions array 
              newmap.setMapType(G_SATELLITE_MAP);
              newmap.addControl(new GLargeMapControl());
              newmap.addControl(new GMapTypeControl());
          }
          
      // Create an EWindow
     // ew = new EWindow(newmap, E_STYLE_7);      
      //newmap.addOverlay(ew);
      
      //GEvent.addListener(newmap, "click", function(overlay,point) {
      //  if (!overlay) {
        //  ew.hide();
       // }
     // });

        return newmap;
      }else{
        alert("Sorry, the Google Maps API is not compatible with this browser");
      }
    }
     
    function closeMap(m){
    //close map object and clean up map related stuff. 
      fade("vector-map-display");
      setTimeout('document.getElementById("static-map-display").style.display="block"',1000);
      setTimeout('document.getElementById("vector-map-display").style.display="none"',1000);      
      m.getInfoWindow().hide();
      m.clearOverlays();
      GUnload();
      map=null;
      m=null; //??This is setting the global map object to null not the map obj passed into the function? Whats up?
                //Response: I dunno. Setting m=null wasn't freeing the resource. Need to figure out. reference problem?
      if (document.getElementById("gcgc_markerXML")){
        document.getElementById("gcgc_markerXML").innerHTML=""; 
        document.getElementById("vector-map").innerHTML="";
      }   
     }
     
    if (document.getElementById("side_bar")){
      document.getElementById("side_bar").innerHTML = '';
    }
      
    
     
    // create the marker and set up the event window
    function createMarker(map, point,name,html, helper) {
      var htmlSized = "<span class='iwstyle'>" + html + "</span>";
      
      if (!typeof shortcodeOpts == 'undefined') {
        var width = shortcodeOpts['iwin'];
      }
      
      if (helper){ //make marker draggable and add listener to add coords to form.
      
        var marker = new GMarker(point, {draggable:true});
        GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml(html);
              // ew.openOnMarker(marker,html);
              /*   marker.openExtInfoWindow(
                  map,
                  "simple_example_window",
                  "I'm some HTML content that will go in the simple example's ExtInfoWindow.",
                  {beakOffset: 3}
                ); 
                */

              }
          )
            
        marker.enableDragging();
      
        GEvent.addListener(marker, "drag", function(){
            frmlat.value=marker.getPoint().lat();
            frmlng.value=marker.getPoint().lng();
           }
          );
      }else{  //load a normal marker
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
                    marker.openInfoWindowHtml(html);
                   // ew.openOnMarker(marker,html);
                  /*    marker.openExtInfoWindow(
                        map,
                        "gcgcPopup",
                        "I'm some HTML content that will go in the simple example's ExtInfoWindow.",
                        {beakOffset: 3}
                      ); */
                      

          });          
       }

      gmarkers[i] = marker;
      htmls[i] = html;
      side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a>';
      if (editFlag){
          side_bar_html += "<span style='text-decoration:none;'> - </span>";
          side_bar_html += "<a href='/wp-admin/admin.php?page=gcgc_admin&panel=cache-admin";
          side_bar_html += "&action=edit_cache&id=" + cacheID +"'>(Edit)</a>";
        }
      
      side_bar_html += '<br>';
      i++;
      return marker;
    }

    function myclick(i) {
      // opens info window for clicked marker
      gmarkers[i].openInfoWindowHtml(htmls[i]);
    }
    
    function computeMapBounds(m){
      //given a map with markers, computes boundary that contains all markers.
      var bnds = new GLatLngBounds();
      
      for (var i = 0; i < m.length; i++) {
        // obtain the attribues of each marker
        var lat = parseFloat(m[i].getAttribute("lat"));
        var lng = parseFloat(m[i].getAttribute("lng"));
        var point = new GLatLng(lat,lng);
        bnds.extend(point);
      }
      return bnds;
    }
    
    function saveMapMeta(vid, bnds, zm){
      var mysack = new sack(ajaxurl);
      //alert ('saving map meta'); 
      mysack.execute = 0;
      mysack.method = 'POST';
      mysack.setVar('action', 'saveMapMeta');
      mysack.setVar('id', vid);
      mysack.setVar('bounds_sw', bnds.getSouthWest());
      mysack.setVar('bounds_ne', bnds.getNorthEast());
      mysack.setVar('clat', bnds.getCenter().lat());
      mysack.setVar('clng', bnds.getCenter().lng());
      mysack.setVar('zm', zm);
      //mysack.onCompletion  = function {};
      mysack.onError = function() { alert('Ajax error in saving Map Meta to vector. '); };
      mysack.runAJAX();
      return true;
    }
      
    function genMarkerInfo(infoText, name,  pt) {
      //TODO: read height, width from options or better compute as % of map div size
      var width = '100';
      var height = '90px';
     //  var bubbleText = "<div style='width: " + width + "; max-height: " + height + "; overflow-y:auto;'>" ;   
     var  bubbleText = "<div class='iwstyle'>" + name + "<hr>Lat: " + pt.lat() + "<br />";
      bubbleText += "Lng: " + pt.lng() + "<br />";
      bubbleText += "<hr>" + infoText + "</div>";
 //     bubbleText += infoText;

      //alert (bubbleText);
     return bubbleText;
    }
    
    //Use this function to return minimum html for small infowindows on small maps
    function genMarkerInfoMin(name,  pt) {
      var width = '250px';
      var height = '85px';
      var bubbleText = "<span class='iwstylemin'>" + name + "<hr>Lat: " + pt.lat() + "<br />";
      bubbleText += "Lng: " + pt.lng() + "<br />";
      bubbleText += "<hr></span>";
      //alert (bubbleText);
      return bubbleText;
    }    
    
    function getXMLText(arg){
      //function to return the xml map data as text for user to copy and paste 
      //TODO: build wrappers to make compliant with different GPS devices. 
      var tsack = new sack(ajaxurl);
      tsack.setVar('action', 'getVectorMarkersText');
      tsack.execute = 0;
      tsack.method = 'POST';
      tsack.setVar('id', arg);
      tsack.element = 'gcgc_markerXML';
      tsack.onError = function() { alert('Ajax error in retrieving xmlText from server. '); };
      tsack.runAJAX();
      return true;          
    }
    
    function getIcon(imageLoc){
      var i = new GIcon();
      i.image = imageLoc;
      i.shadow = "http://www.google.com/mapfiles/shadow50.png";
      i.iconSize = new GSize(20, 34);
      i.shadowSize = new GSize(37, 34);
      i.iconAnchor = new GPoint(9, 34);
      i.infoWindowAnchor = new GPoint(9, 2);
      i.infoShadowAnchor = new GPoint(18, 25);
      i.transparent = "http://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";
      return i;
    }
    
    function readMapData(mapID,m) {
      mysack = new sack(ajaxurl);
      mysack.setVar('action', 'getVectorMarkers');
      mysack.execute = 0;
      mysack.method = 'POST';
      mysack.setVar('id', mapID);
      mysack.onCompletion  = function() {loadOverlay(m);};
      mysack.onError = function() { alert('Ajax error in retrieving data from server. '); };
      mysack.runAJAX();
      return true;          
    } 
    
    
    function loadOverlay(map){   
      //callback function for map sack request onreadystatechange
      function initMapSideBar(title){
        side_bar_head = "<strong>"+title+"</strong><br/><hr />";
        side_bar_html = '';
        gmarkers = [];
        htmls = [];
        i = 0;     
      }
      
      var vName = '';
      var bounds = new GLatLngBounds();
      var side_bar_head = '';
      var side_bar ='';
      var editBtn = '';
      var closeBtn = '';

      var xmlDoc = mysack.responseXML;
      //getXMLText(vectorID); //formatted for display in browser
        
      var vectorName = xmlDoc.documentElement.getElementsByTagName("vectorName");
      if (!vectorName[0]){
        vName = "Error Reading Vector Name";
      }else{
        vName = vectorName[0].getAttribute("vname");
      }
      
      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
        
      //Set a center point     
      //TODO: need to read bounds from vector in case user customized them 
      if (markers.length > 0 && map.autofit){
        bounds = computeMapBounds(markers); 
        map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
        saveMapMeta(vectorID, bounds, map.getBoundsZoomLevel(bounds));
      }else{ 
        var centerPoint = xmlDoc.documentElement.getElementsByTagName("centerPoint");
        var clat = parseFloat(centerPoint[0].getAttribute("clat"));
        var clng = parseFloat(centerPoint[0].getAttribute("clng"));
        var zm = parseInt(centerPoint[0].getAttribute("zoom"));
        var cpoint = new GLatLng(clat, clng);
        //alert ('clat: ' + clat + '  clng: ' + clng);
        map.setCenter(cpoint, zm);
      }


      // reset map and side_bar
      initMapSideBar(vName);
      map.getInfoWindow().hide(); // hide the info window in case still open from prev overlay
      map.clearOverlays();

      //load each marker retrieved from geocache db 
      for (var i = 0; i < markers.length; i++) {
        cacheID = markers[i].getAttribute("id")
        var lat = parseFloat(markers[i].getAttribute("lat"));
        var lng = parseFloat(markers[i].getAttribute("lng"));
        var point = new GLatLng(lat,lng);
        var label = markers[i].getAttribute("label");
        if (map.minwin){
          var html = genMarkerInfoMin(label, point);
        }else{
          var html = genMarkerInfo(markers[i].getAttribute("html"), label, point);
        }
    //    var icon = getIcon(markers[i].getAttribute("icon")); 
        var marker = createMarker(map, point,label,html, false);
        map.addOverlay(marker);
        //bounds.extend(point); //i dont think this is needed with the above 'computeMapBounds' function
      }
      
      // put the assembled side_bar_html contents into the side_bar div
      if (side_bar_html==""){
        side_bar_html="No Geocaches are currently assigned to this vector.<br/>";
      }else{
        var genBtn = "<p /><input type='button' value='Autogen Map Coords' onClick='saveMapMeta(vectorID, bounds, map.getBoundsZoomLevel(bounds));'><br />";        
        //side_bar_html += genBtn;
      }
      
      var side_bar = side_bar_head + side_bar_html;
      
      if (document.getElementById("gcgc_cache_lat")){   //only exists on cache admin panel
        myEventListener = GEvent.addListener(map, "click", handleClicks);
      }else{  //we dont want close btn on cache admin map
        closeBtn = "<p /><input type='button' value='Close Map' onClick='closeMap(map);'><br />";
        if (editFlag){
          editBtn = "<p /><input type='button' value='Edit Map' onClick='editMap(vectorID);'><br />";
        }
        side_bar +=  closeBtn + editBtn;
      }
      if (document.getElementById("side_bar"))
        document.getElementById("side_bar").innerHTML = side_bar;
    } //end function loadOverlay()

    

    function doVectorMap(id, view, uid){  //TODO remove uid  parm... no longer needed.
       //if the map is called from the widget in the side bar, we need to be sure the 
      //plugin's map display page is loaded. If not, redirect to it, then load the map
 
     
      if (view == 'widget' && !document.getElementById('gcgc_markerXML')){        
        var url = window.location.protocol + "//" + window.location.host +  '/geocache';
        window.location=url;
        addLoadEvent(function() { 
          doVectorMap(id, '', '');
          });
        return;
      }
     
      vectorID = id; 
      
      document.getElementById("static-map-display").style.display="none"; 
      fade("vector-map-display");
      var dispState = document.getElementById("vector-map-display").style.display;

      if (dispState  == "none") {
          document.getElementById("vector-map-display").style.display = "block"
          }
  
      if (map == null) {
            map = getMap("vector-map");
            readMapData(id,map);
        } else {
           smallPause(500); //wait for fade effect
           readMapData(id,map);
           setTimeout("fade('vector-map-display')",1000);
        }
      getXMLText(vectorID); //formatted for display in browser
    }
    
    
    function doCacheVectorMap(id){
        //this is the same func as doVectorMap without the fade
        vectorID = id;
        editFlag = true;
        
        if (map == null) {
          map = getMap("vector-map");
        } 
        readMapData(id, map);
     }
    
    function getMapTypeName(m){
      var mtname;
      switch (m.getCurrentMapType()) {
          case G_NORMAL_MAP :
            mtname =  'G_NORMAL_MAP';
          break;
          
          case G_SATELLITE_MAP :
            mtname = 'G_SATELLITE_MAP';
          break;
          
           mtname = 'G_NORMAL_MAP';          
          case G_HYBRID_MAP :
           mtname = 'G_HYBRID_MAP';
          break;
          
          case G_PHYSICAL_MAP :
           mtname = 'G_PHYSICAL_MAP';
          break;
      
      }
      return mtname;
    }
    
    function updateAdvancedFields(){
      var bnds = helperMap.getBounds();
      var sw = bnds.getSouthWest();
      var ne = bnds.getNorthEast();
      var mtfld = document.vectorform.gcgc_maptype; 
      var mtname = getMapTypeName(helperMap);
      document.vectorform.gcgc_bound_sw.value = sw;
      document.vectorform.gcgc_bound_ne.value = ne;
      document.vectorform.gcgc_clat.value = helperMap.getCenter().lat();
      document.vectorform.gcgc_clng.value = helperMap.getCenter().lng();
      document.vectorform.gcgc_map_zoom.value = helperMap.getZoom();
      for (var i = 0; i < mtfld.length; i++) {
         if (mtfld[i].value == mtname){
            mtfld[i].checked = true;
          }else{
            mtfld[i].checked = false;                      
        }
      }


    }
    
    function loadHelperMap(flag, clat, clng, zm) {
    //render a map to help load the center, zoom and bounds coords into a form
    //flag indicates from where the function was called so maps can have different behavior 
    //and style according to where its being rendered. 
    
      //we need to preserve the values of the params so we can update the map after an ajax update call
      //I'll us 'pv' to denote a page variable. They need to be global so they can be accessed elsewhere
      pvFlag = flag;
      pvclat = clat;
      pvclng = clng;
      pvzm = zm;
      
   //   alert ('flag->'+pvFlag + ' clat->'+ pvclat + ' clng->' + pvclng + ' zm->' + pvzm );
      var point;
      if (GBrowserIsCompatible()) {
        frmlat = document.getElementById("gcgc_cache_lat");
        frmlng = document.getElementById("gcgc_cache_long");
      // zoom = document.getElementById("gcgc_map_zoom");
      // info = document.getElementById("info");
    
        helperMap = getMap("vector-map");
        
        switch(flag) {
          case "1":  //Helper map on ther Edit GeoCache form
            vlat = parseFloat(frmlat.value);
            vlng = parseFloat(frmlng.value);
            point = new GLatLng(vlat,vlng);
            helperMap.setCenter(point, 15);
            label = document.getElementById("gcgc_cache_name").value;
      //load up the options 
            html = "<div style='width:250px;'>";
            html += genMarkerInfo(document.getElementById('gcgc_balloon_html').value, label, point);
            html += "</div>";
            helperMap.addControl(new GLargeMapControl());
            helperMap.addControl(new GMapTypeControl());
            marker = createMarker(point,label,html, true);
            helperMap.clearOverlays();
            helperMap.addOverlay(marker);
            
            //make marker draggable with update to coords
            marker.enableDragging();

            GEvent.addListener(marker, "drag", function(){
                frmlat.value=marker.getPoint().lat();
                frmlng.value=marker.getPoint().lng();
               }
              );
            break;
            
            
          case "2" :  //Helper map on the Add/Edit Vector form
            point = new GLatLng(parseFloat(clat),parseFloat(clng));
           // point = new GLatLng(29.121460999999996,-95.32657599999999);
           // alert("point.lat->" + point.lat());
           // alert("point.lng->" + point.lng());   
           //alert("zoom->" + zm);         
            helperMap.setCenter(point, parseInt(zm));
            helperMap.addControl(new GLargeMapControl());
            helperMap.addControl(new GMapTypeControl());  
            GEvent.addListener(helperMap, "drag", function(){
                  updateAdvancedFields();
              })
              
            GEvent.addListener(helperMap, "moveend", function(){
                  updateAdvancedFields();
              })
              
            GEvent.addListener(helperMap, "maptypechanged", function() {
                  var mtfld = document.vectorform.gcgc_maptype; 
                  var mtname = getMapTypeName(helperMap);
                  for (var i = 0; i < mtfld.length; i++) {
                     if (mtfld[i].value == mtname){
                        mtfld[i].checked = true;
                      }else{
                        mtfld[i].checked = false;                      
                    }}
              }); 

            break;           
            

          default:
            if (!clat==""){
              helperMap.setCenter(new GLatLng(clat, clng), zm);
            }else{
              helperMap.setCenter(new GLatLng(29.120806, -95.331848), 15);
            }
            helperMap.addControl(new GLargeMapControl());
            helperMap.addControl(new GMapTypeControl());   
         }
     
        //GEvent.addListener(helperMap, "click", insertLatLng);
      }
    }
    
    

    function handleClicks(marker, point){
      if (!frmlat){
        frmlat = document.getElementById("gcgc_cache_lat");
        frmlng = document.getElementById("gcgc_cache_long");
      }
      
      if (frmlat){
        frmlat.value=point.lat();
        frmlng.value=point.lng();
      }
      
      //Add a draggable marker w/ distinguished icon
      //TODO: distinguished icon not working
      var icon = new GIcon();
      icon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
      icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
      icon.iconSize = new GSize(12, 20);
      icon.shadowSize = new GSize(22, 20);

      
      //var point = new GLatLng(point);
      //var markerD = new GMarker(point, {icon:icon, draggable: true});
      var markerD = new GMarker(point, {draggable: true});  
      map.addOverlay(markerD);
      
      markerD.enableDragging();
      
      GEvent.addListener(markerD, "drag", function(){
                frmlat.value=markerD.getPoint().lat();
                frmlng.value=markerD.getPoint().lng();
               }
          );      
      GEvent.removeListener(myEventListener); // this will prevent a new helper marker from being created on map click
    }
    
    function insertLatLng(marker, point){
      //fill in form input fields 
      frmlat.value=point.lat();
      frmlng.value=point.lng();
    }    
  
    function smallPause(milli){
      //used to time a back-to-back fade in / fade out sequence
      var date = new Date();
      var curDate = null;
      
      do { curDate = new Date(); }
      while(curDate-date < milli);
      }
      
    function showVectorForm(){
      var url = window.location.protocol + "//" + window.location.host + window.location.pathname + "?page=gcgc_admin&panel=vector-admin&action=create_vector";
      window.location=url;
    /*
      document.getElementById("static-map-display").style.display="none" ;
      document.getElementById("vector-map-display").style.display="none" ;
      document.getElementById("vector-form-display").style.display='block';
    */
    }
    
    function closeVectorForm(){
      var url = window.location.protocol + "//" + window.location.host + window.location.pathname + "?page=gcgc_admin";
      window.location=url;
      
    }
    
    function reloadCacheAdmin(id){
      //used to cancel an edit
      var url = window.location.protocol + "//" + window.location.host + window.location.pathname + "?page=gcgc_admin&panel=cache-admin&id=" + id;
      window.location=url;
    }
    
    function editMap(id){
      var url = window.location.protocol + "//" + window.location.host + window.location.pathname + "?page=gcgc_admin&panel=vector-admin&action=edit_vector&id=" + id;
      window.location=url;
    }
    
    function clearAdvancedSettings(){
      //alert(document.vectorform.gcgc_bound_ne.value);
      document.vectorform.gcgc_bound_ne.value='';
      document.vectorform.gcgc_bound_sw.value='';
      document.vectorform.gcgc_clat.value='';
      document.vectorform.gcgc_clng.value='';
      document.vectorform.gcgc_map_zoom.value='';
 
      var mt = document.vectorform.gcgc_maptype;
      for (var i = 0; i < mt.length; i++) {
         mt[i].checked = false;
      }
    }

    //import a Google Maps map
    function importGoogleMap(){
      //set the URL from form value, Have option for virtual display or save the data to db.
      var url = document.gcgcGoogleMap.gcgcGoogleMapURL.value + "&output=kml";
      var id = document.gcgcGoogleMap.gcgcVectorId.value ;
      myMapSack = new sack(ajaxurl);
      myMapSack.setVar('action', 'getMyMapKML');
      myMapSack.execute = 0;
      myMapSack.method = 'POST';
      myMapSack.setVar('url', url);
      myMapSack.setVar('id', id);
      myMapSack.onCompletion  = function() { alert(myMapSack.response); };
     // myMapSack.onCompletion  = function() { alert('Placemarks successfully imported.'); };
      myMapSack.onError = function() { alert('Ajax error in retrieving MyMap KML. '); };
      myMapSack.runAJAX();
      return true;   
    }
    

//EOF
