﻿// SNSMR Gas Stations - CB 2007
 //<![CDATA[
              
// global variables
      var map; 
         var tooltip;
      var gdir;
      var type;
      var brand;
      var zone; 
      var gmarkers = [];
      var geoXml;
      var  toggleState = 0;
     
             
//Setup the coloured icons     

// /snsmr/access/10507.htm
    var iconBlue = new GIcon(); 
    iconBlue.image = '/snsmr/img/icons/mm_20_blue.png';
    iconBlue.shadow = '/snsmr/img/icons/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(12, 20);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);

// /snsmr/access/10506.htm
    var iconRed = new GIcon(); 
    iconRed.image = '/snsmr/img/icons/mm_20_red.png';
    iconRed.shadow = '/snsmr/img/icons/mm_20_shadow.png';
    iconRed.iconSize = new GSize(12, 20);
    iconRed.shadowSize = new GSize(22, 20);
    iconRed.iconAnchor = new GPoint(6, 20);
    iconRed.infoWindowAnchor = new GPoint(5, 1);

// /snsmr/access/10505.htm
    var iconGreen = new GIcon(); 
    iconGreen.image = '/snsmr/img/icons/mm_20_green.png';
    iconGreen.shadow = '/snsmr/img/icons/mm_20_shadow.png';
    iconGreen.iconSize = new GSize(12, 20);
    iconGreen.shadowSize = new GSize(22, 20);
    iconGreen.iconAnchor = new GPoint(6, 20);
    iconGreen.infoWindowAnchor = new GPoint(5, 1);

    //Assign icon colours to service types 
    var customIcons = [];

///snsmr/access/10507.htm
    customIcons["Service aux pompes"] = iconBlue;

///snsmr/access/10506.htm
    customIcons["Service aux pompes et libre-service"] = iconRed;

///snsmr/access/10505.htm
    customIcons["Libre-service"] = iconGreen;

    
    
 //Main function to load the map, setup controls, define viewable area etc.
    function load() {
      if (GBrowserIsCompatible()) {
           //Variable to hold the zones overlay file
           //FYI-Doesnt work if files on Dev server.
          geoXml = new GGeoXml("http://www.gov.ns.ca/snsmr/xml/zones.txt");
      // display the loading message
        var om = new OverlayMessage(document.getElementById('map'));      
        om.Set('<h2>Chargement des donn&eacute;es, veuillez patienter... </h2>');
      
      
      //create the map
        map = new GMap2(document.getElementById("map"));
        var customUI = map.getDefaultUI();
        customUI.controls.maptypecontrol = false;
        customUI.controls.menumaptypecontrol = true;
        customUI.zoom.scrollwheel = false;
        map.setUI(customUI);    
       
      //center the map at this lat/lng and give it a zoom level of 7
        map.setCenter(new GLatLng( 45.33284,-62.935181), 7);
          
        
         
       
      //create a GDirections Object used in displaying directions 
      gdir=new GDirections(map, document.getElementById("directions"));
      
      // Array for decoding the failure codes in directions
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Adresse manquante : L'adresse est manquante ou le champ ne contient aucune valeur.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Adresse inconnue : Aucun emplacement g&eacute;ographique correspondant n'a &eacute;t&eacute; trouv&eacute; pour cette adresse.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= " Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = " Bad Key: The API key is either invalid or does not match the domain for which it was given.";
      reasons[G_GEO_TOO_MANY_QUERIES]   = " Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = " Server Error: The geocoding request could not be successfully processed.";
      reasons[G_GEO_BAD_REQUEST]        = " A directions request could not be successfully parsed.";
      reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
      reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Adresse manquante : L'adresse est manquante ou le champ ne contient aucune valeur.";
      // catch Directions errors 
      GEvent.addListener(gdir, "error", function() {
        var code = gdir.getStatus().code;
        var reason="Code "+code;
        if (reasons[code]) {
          reason = reasons[code]
        } 
        alert("Impossible d'obtenir les directives -  - "+reason);
      });
      
      
        // === create the right-click menu div ===
      contextmenu = document.createElement("div");
      contextmenu.style.visibility="hidden";
      contextmenu.style.background="#ffffff";
      contextmenu.style.padding="5px";
      contextmenu.style.border="1px solid #8888FF";
      contextmenu.innerHTML = '<a href="javascript:zoomIn()"><div class="context">Zoom avant</div></a>'
                            + '<a href="javascript:zoomOut()"><div class="context">Zoom arri&egrave;re</div></a>'
                            + '<a href="javascript:centreMapHere()"><div class="context">Recentrer ici</div></a>';
      map.getContainer().appendChild(contextmenu);
      // === listen for singlerightclick ===
      GEvent.addListener(map,"singlerightclick",function(pixel,tile) {
        // store the "pixel" info in case we need it later
        // adjust the context menu location if near an egde
        // create a GControlPosition
        // apply it to the context menu, and make the context menu visible
        clickedPixel = pixel;
        var x=pixel.x;
        var y=pixel.y;
        if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
        if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
        pos.apply(contextmenu);
        contextmenu.style.visibility = "visible";
      });
// ====== Restricting the map range and zoom levels =====
      // Get the list of map types      
      var mt = map.getMapTypes();
      // Overwrite the getMinimumResolution() and getMaximumResolution() methods
      for (var i=0; i<mt.length; i++) {
        mt[i].getMinimumResolution = function() {return 7;} //restrict min zoom level to 7, users can't zoom out past this level
        mt[i].getMaximumResolution = function() {return 17;}//restrict max zoom level to 17
      }
     
    //Create the tooltip div
          tooltip = document.createElement("div");
          map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
          tooltip.style.visibility="hidden";
 //Add a move listener to restrict the map range
      GEvent.addListener(map, "move", function() {
        checkBounds();
      });
      
         // === If the user clicks on the map, close the context menu ===
      GEvent.addListener(map, "click", function() {
        contextmenu.style.visibility="hidden";
      });
      // The allowed region which the whole map must be within
      var allowedBounds = new GLatLngBounds(new GLatLng(42.873951,-66.714478), new GLatLng(48.868328,-58.112183));
               
      // Function to check if the map position is out of range, move it back
      function checkBounds() {
        // Perform the check and return if OK
        if (allowedBounds.contains(map.getCenter())) {
          return;
        }
        // It`s not OK, so find the nearest allowed point and move there
        var C = map.getCenter();
        var X = C.lng();
        var Y = C.lat();
        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();
        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        //alert ("Restricting "+Y+" "+X);
        map.setCenter(new GLatLng(Y,X));
      }
//=====End restrict map range and zoom======//
         
        //Read marker values from the XML, assign variables to each <marker> attribute from the file      
        GDownloadUrl("/snsmr/xml/gas-stations-fr.xml", function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
            brand = markers[i].getAttribute("brand"); //global variable used in filter function
            var location = markers[i].getAttribute("location");
            var phone = markers[i].getAttribute("phone");
            var county = markers[i].getAttribute("county");
             type = markers[i].getAttribute("type"); //global variable used in filter function
            var diesel = markers[i].getAttribute("diesel");
            zone = markers[i].getAttribute("zone"); //global variable used in filter function
            var lat = markers[i].getAttribute("lat");
            var lng = markers[i].getAttribute("lng");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
            var marker = createTabbedMarker(point, name, address, brand, location, diesel, phone, zone, county, type, lat, lng);
            map.addOverlay(marker);      
          }
          om.Clear(); // Clear the loading message
          $('p.clearDirections').hide();
        });        
      }
    }
    
 //Function to filter markers from dropdown
    function toggleGroup(opt) {
    //close any open infoWindows and clear all directions
    map.closeInfoWindow();
    gdir.clear();
    $('p.clearDirections').hide();
        //loop through all the markers and see if type, brand or zone match the value passed from the dropdown
        for (var i=0;i<gmarkers.length;i++) {
          //if it matches service type, show markers
         if (gmarkers[i].type == opt) {
            gmarkers[i].show();  
            }
            //if it matches brand, show markers
        else if (gmarkers[i].brand == opt)
        {
        gmarkers[i].show();
        }
        //if it matches zone, show markers
        else if (gmarkers[i].zone == opt)
        {
        gmarkers[i].show();
                  } else {
                      //otherwise hide markers
                 gmarkers[i].hide();
                  }
        }
      }
//function to clear directions and refresh map w/all stations
function refreshMap() {
    map.closeInfoWindow();
    gdir.clear();
    //remove zones overlay if showing, reset button text
    map.removeOverlay(geoXml);
    toggleState = 0;
    document.getElementById("toggle").value = "Afficher les zones";
     for (var i=0;i<gmarkers.length;i++) {    
            gmarkers[i].show();  
            }
     map.setCenter(new GLatLng( 45.33284,-62.935181), 7);
    document.getElementById("service-type").selectedIndex = 0;
}
//Function to show/hide zones overlay
function toggleZones() {
  if (toggleState == 1) {
    map.removeOverlay(geoXml);
    toggleState = 0;
    document.getElementById("toggle").value = "Afficher les zones";
  } else {
    map.addOverlay(geoXml);
    toggleState = 1;
    document.getElementById("toggle").value = "Masquer les zones";
  }
}
//function to clear directions and recenter map, used in infoWindow
function recenterMap() {
    map.closeInfoWindow();
    gdir.clear();
    map.setCenter(new GLatLng( 45.33284,-62.935181), 7);    
}
//Chained select box functions
 function dynamicSelect(id1, id2) {
     if (document.getElementById && document.getElementsByTagName) {
         var sel1 = document.getElementById(id1);
         var sel2 = document.getElementById(id2);
         var clone = sel2.cloneNode(true);
       var clonedOptions = clone.getElementsByTagName("option");
        refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
         sel1.onchange = function() {
            refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
         };
    }
 }
 function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) {
    while (sel2.options.length) {
         sel2.remove(0);
    }
     var pattern1 = /( |^)(select)( |$)/;
    var pattern2 = new RegExp("( |^)(" +
          sel1.options[sel1.selectedIndex].value + ")( |$)");
    for (var i = 0; i < clonedOptions.length; i++) {
         if (clonedOptions[i].className.match(pattern1) ||
              clonedOptions[i].className.match(pattern2)) {
            sel2.appendChild(clonedOptions[i].cloneNode(true));
        }
     }
}
//Functions to create tooltips when markers are hovered over
function mymouseover(i) {
      showTooltip(gmarkers[i])
    }
    function mymouseout() {
      tooltip.style.visibility="hidden";
    }
    
    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";
    }
    
    // Request directions
      function getDirections() {
        var saddr = document.getElementById("saddr").value
        var daddr = document.getElementById("daddr").value
        


                    gdir.load("from: "+saddr+" to: "+daddr, { "locale": "fr" });
               
        


        map.closeInfoWindow();
        //hide all other station markers 
         for (var i=0;i<gmarkers.length;i++) {
        gmarkers[i].hide();
         }
      }
      
      // === functions that perform the context menu options ===
      function zoomIn() {
        // perform the requested operation
        map.zoomIn();
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }      
      function zoomOut() {
        // perform the requested operation
        map.zoomOut();
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }      
          
      function centreMapHere() {
        // perform the requested operation
        var point = map.fromContainerPixelToLatLng(clickedPixel)
        map.setCenter(point);
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }
    //main function to create the markers and contents within the infoWindow
    function createTabbedMarker(point, name, address, brand, location, diesel, phone, zone, county, type, lat, lng) {
   var marker = new GMarker(point, customIcons[type]);
   //put markers into groups for filtering
   marker.type = type;                                 
   marker.brand = brand;
   marker.zone = zone;                                 
   gmarkers.push(marker);
  //The main information tab
      var html = "<div class='infoWindow'><h3>" + name + "</h3><strong>Marque :</strong>&nbsp;" + brand  +  "<br/> <strong>Adresse :</strong>&nbsp;" + address + "<br/> <strong>Lieu :</strong>&nbsp;" + location  + "<br/> <strong>Comt&eacute; :</strong>&nbsp;" + county + "<br/> <strong>Zone :</strong>&nbsp;" + zone  + "<br/><strong>T&eacute;l&eacute;phone :</strong>&nbsp;" + phone + "<br/> <strong>Type de service :</strong>&nbsp;" + type +  "<br/> <strong>Diesel :</strong>&nbsp;" + diesel + "<br/><strong>Prix :</strong>&nbsp;<a href='http://www.nsuarb.ca' title='Prix actuels des zones'>Prix actuels des zones</a><p class='zoom'><a href='#zoominlink' onclick='javascript:map.setZoom(15); return false;'><strong>Zoom avant</strong></a>&nbsp;&nbsp; |&nbsp;&nbsp;" +
"<a href='#recenterMap' onclick='javascript:recenterMap(); return false;'><strong>Restaurer la carte</strong></a></p></div>";
     //The Directions tab
         var tabLabel = "Directives";
         var tabHtml = '<div class="infoWindow">'+'<h3 class="location" >' + name +'</a></h3><br />'+
         '<p>Comment se rendre &agrave; cette station-service.</p>' +
           '<p class="directions"><strong>Inscrire votre adresse de d&eacute;part :</strong><br /><em style="color:#666;">par ex. &laquo; 1505 Barrington St., Halifax, NS &raquo;</em></p><form action="javascript:getDirections()">' +
           '<input type="text" size="40" maxlength="40" name="saddr" id="saddr" value="" /><br>' +
           '<input value="Obtenir les directives" type="submit" onclick="javascript:$(\'p.clearDirections\').show();">' +
           '<input type="hidden" id="daddr" value="'+name+ " - "+address+ ", "+location+"@"+ point.lat() + ',' + point.lng() +
           '"/><p class="disclaimer"><strong>Cet itin&eacute;raire vous est propos&eacute; uniquement &agrave; titre indicatif.</strong><br />Cet itin&eacute;raire vous est propos&eacute; uniquement &agrave; titre indicatif.</p>' +
            "<p class='zoom'><a href='#zoominlink' onclick='javascript:map.setZoom(15); return false;'><strong>Zoom avant</strong></a>&nbsp;&nbsp; |&nbsp;&nbsp;" +
"<a href='#recenterMap' onclick='javascript:recenterMap(); return false;'><strong>Restaurer la carte</strong></a></p></div>";
    
      GEvent.addListener(marker, 'click', function() {
       marker.openInfoWindowTabsHtml([new GInfoWindowTab("Information",html), new GInfoWindowTab(tabLabel,tabHtml)]);
      });
      
      //add the tooltip to each marker, display the brand name when hovered
        marker.tooltip = "<div class='tooltip' style='overflow: visible'>"+brand+"<\/div>";
            GEvent.addListener(marker,"mouseover", function() {
              showTooltip(marker);
            });
            GEvent.addListener(marker,"mouseout", function() {
              tooltip.style.visibility="hidden"
            });
      return marker;
    }
    
    //]]>
