/***
Google Maps Script
***/

//declaring common variables that will be used in the various Google Maps functions
var map = null;
//list of the markers displayed on the map
var markers = new Array();
var markerKeys = new Array();
//list of the content displayed when one clicked on a marker
var windowHtmls = new Array();
//current address marker
var currentAddressMarker = null;

function RetrieveListOfOptician() {
  markers = new Array();

  var imgLoading = document.getElementById(loadingPictureId);
  imgLoading.style.display = '';
  if (!GBrowserIsCompatible()) {
    alert("browser aint compatible");
    imgLoading.style.display = 'none';
    return;
  }

  //retrieving the value of the elements of the form
  var url = providerUrl;
  var addressElement = document.getElementById(addressId);
  addressElement.style.width = "132px"; //IE6 loses the styling, and width must be adjusted again.
  var zipElement = document.getElementById(zipId);
  var townElement = document.getElementById(townId);
  var groupsElement = (typeof groupsId != "undefined" ? document.getElementById(groupsId) : undefined);

  if (addressElement == undefined || addressElement == null
        || zipElement == undefined || zipElement == null
        || townElement == undefined || townElement == null) {
    imgLoading.style.display = 'none';
    return;
  }
  else {
    var addressValue = addressElement.value;
    var zipValue = zipElement.value;
    var townValue = townElement.value;
    var groupsValue = (groupsElement != undefined ? groupsElement.value : "");

    if (zipValue.length == 0 && townValue.length == 0 && groupsValue.length == 0) {
      imgLoading.style.display = 'none';
      addressElement.disabled = false;
      zipElement.disabled = false;
      townElement.disabled = false;
      return;
    }

    if (addressValue != "")
      url += "address=" + addressValue + "&";
    if (zipValue != "")
      url += "zip=" + zipValue + "&";
    if (townValue != "")
      url += "town=" + townValue + "&";
    if (groupsValue != "")
      url += "groups=" + groupsValue + "&";
    url += "key=" + googleKey;
    if (typeof VersionCustom != "undefined")
      url += "&VersionCustom=" + VersionCustom;
    document.getElementById('MapAndResultsPanel').style.display = '';
    addressElement.disabled = true;
    zipElement.disabled = true;
    townElement.disabled = true;
  }

  GDownloadUrl(encodeURI(url), function(data, responseCode) {

    if (responseCode == 200) {

      var xml = GXml.parse(data);

      if (xml.documentElement.getElementsByTagName("error").length > 0) {
        alert("Error occured");
        imgLoading.style.display = 'none';
        addressElement.disabled = false;
        zipElement.disabled = false;
        townElement.disabled = false;
        return;
      }

      var results = document.getElementById(resultsId);

      var opticianTable = document.createElement('table');
      opticianTable.className = "OpticianLocatorStoreList";
      //adding caption
      var opticianTableCaption = document.createElement('caption');
      opticianTableCaption.appendChild(document.createTextNode(OpticianTableCaptionText));
      var opticianTBody = document.createElement('tbody');
      opticianTable.appendChild(opticianTBody);

      //creating header
      var Opticians = xml.documentElement.getElementsByTagName("Optician");
      if (Opticians.length != 0) {
        var header = document.createElement('tr');
        opticianTBody.appendChild(header);
        var storeNameHeader = document.createElement('th');
        storeNameHeader.appendChild(document.createTextNode(StoreNameHeaderText));
        header.appendChild(storeNameHeader);
        var addressHeader = document.createElement('th');
        addressHeader.appendChild(document.createTextNode(AddressHeaderText));
        header.appendChild(addressHeader);
        var zipCodeHeader = document.createElement('th');
        zipCodeHeader.appendChild(document.createTextNode(ZipHeaderText));
        header.appendChild(zipCodeHeader);
        var cityHeader = document.createElement('th');
        cityHeader.appendChild(document.createTextNode(CityHeaderText));
        header.appendChild(cityHeader);
        var phoneNumberHeader = document.createElement('th');
        phoneNumberHeader.appendChild(document.createTextNode(PhoneHeaderText));
        header.appendChild(phoneNumberHeader);
        var faxHeader = document.createElement('th');
        faxHeader.appendChild(document.createTextNode(FaxHeaderText));
        header.appendChild(faxHeader);
        var mailHeader = document.createElement('th');
        mailHeader.appendChild(document.createTextNode(EMailHeaderText));
        header.appendChild(mailHeader);
        var websiteHeader = document.createElement('th');
        websiteHeader.appendChild(document.createTextNode(WebSiteHeaderText));
        header.appendChild(websiteHeader);

      }
      else if (Opticians.length == 0) {
        var header = document.createElement('tr');
        opticianTBody.appendChild(header);
        var ItemNotFound = document.createElement('th');
        ItemNotFound.appendChild(document.createTextNode("Items not Found !"));
        header.appendChild(ItemNotFound);
      }
      //loading the map with the parameters in the form
      map = createOpticianStoreLocatorMap(mapId);
      if (map != null) {
        var CurrentAddresses = xml.documentElement.getElementsByTagName("CurrentAddress");
        var httpStatus = "";
        if (CurrentAddresses != null)
          httpStatus = CurrentAddresses[0].getElementsByTagName('HttpStatus')[0].firstChild.nodeValue;
        else
          httpStatus = "0";

        if (httpStatus == "200") {
          var latitude = CurrentAddresses[0].getElementsByTagName('GeoLat')[0].firstChild.nodeValue;
          var longitude = CurrentAddresses[0].getElementsByTagName('GeoLng')[0].firstChild.nodeValue; ;
          var point = new GLatLng(parseFloat(latitude), parseFloat(longitude));
          map.setCenter(point, 13);
        }
        else {
          alert("Unable to locate the specified address.");
          imgLoading.style.display = 'none';
          addressElement.disabled = false;
          zipElement.disabled = false;
          townElement.disabled = false;
          return;
        }
      }
      else {
        imgLoading.style.display = 'none';
        addressElement.disabled = false;
        zipElement.disabled = false;
        townElement.disabled = false;
        //alert("if map !null");
        return;
      }

      //building the list of opticians as well as the markers
      if (Opticians == null || Opticians == undefined) {
        imgLoading.style.display = 'none';
        addressElement.disabled = false;
        zipElement.disabled = false;
        townElement.disabled = false;
        return;
      }

      // Mark the first optician in the map
      if (Opticians.length > 0) {
        var latitude = Opticians[0].getElementsByTagName('GeoLat')[0].firstChild.nodeValue;
        var longitude = Opticians[0].getElementsByTagName('GeoLng')[0].firstChild.nodeValue;
        var point = new GLatLng(parseFloat(latitude), parseFloat(longitude));
        //map.setCenter(point, 13); Previous line commented.
        var bounds = new GLatLngBounds();
        var i = 0;
        var optLength = 0;

        optLength = Opticians.length;
        while (i < optLength) {
          latitude = Opticians[i].getElementsByTagName('GeoLat')[0].firstChild.nodeValue;
          longitude = Opticians[i].getElementsByTagName('GeoLng')[0].firstChild.nodeValue;
          point = new GLatLng(parseFloat(latitude), parseFloat(longitude));

          bounds.extend(point);

          i++;
        }

        var vZoomLevel = map.getBoundsZoomLevel(bounds);
        if (vZoomLevel >= 20) {
          map.setCenter(bounds.getCenter(), 13);
        }
        else {
          map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        }
      }

      for (var i = 0; i < Opticians.length; i++) {
        var stamp = "";
        var latitude = "";
        var longitude = "";
        var title = "";
        var address = "";
        var zipcode = "";
        var city = "";
        var telephone = "";
        var fax = "";

        var row = document.createElement('tr');
        var storeNameCell = document.createElement('td');
        storeNameCell.setAttribute("style", "border-spacing:10px");
        row.appendChild(storeNameCell);
        var addressCell = document.createElement('td');
        row.appendChild(addressCell);
        var zipCodeCell = document.createElement('td');
        row.appendChild(zipCodeCell);
        var cityCell = document.createElement('td');
        row.appendChild(cityCell);
        var phoneNumberCell = document.createElement('td');
        row.appendChild(phoneNumberCell);
        var faxCell = document.createElement('td');
        row.appendChild(faxCell);
        var mailCell = document.createElement('td');
        row.appendChild(mailCell);
        var websiteCell = document.createElement('td');
        row.appendChild(websiteCell);

        stamp = Opticians[i].getElementsByTagName('CustomerNumber')[0].firstChild.nodeValue;

        for (var j = 0; j < Opticians[i].childNodes.length; j++) {
          var cellContent = Opticians[i].childNodes[j].firstChild.nodeValue + " ";
          switch (Opticians[i].childNodes[j].nodeName) {
            case 'StoreName':
              title = cellContent;
              var link = document.createElement('a');
              link.appendChild(document.createTextNode(cellContent));
              link.setAttribute("href", "javascript:markerFocus('" + stamp + "')")
              storeNameCell.appendChild(link);
              break;
            case 'StreetAddress':
              address = cellContent;
              addressCell.appendChild(document.createTextNode(cellContent));
              break;
            case 'ZipCode':
              zipcode = cellContent;
              zipCodeCell.appendChild(document.createTextNode(cellContent));
              break;
            case 'City':
              city = cellContent;
              cityCell.appendChild(document.createTextNode(cellContent));
              break;
            case 'PhoneNumber':
              telephone = cellContent;
              var nobrcell = phoneNumberCell.appendChild(document.createElement('nobr'));
              nobrcell.appendChild(document.createTextNode(cellContent));
              break;
            case 'FaxNumber':
              fax = cellContent;
              var nobrcell2 = faxCell.appendChild(document.createElement('nobr'));
              nobrcell2.appendChild(document.createTextNode(cellContent));
              break;
            case 'EmailAddress':
              var mailto = document.createTextNode(cellContent);
              if (cellContent.trim() != "") {
                mailto = document.createElement("a");
                mailto.setAttribute("href", "mailto:" + cellContent);
                var img = document.createElement("img");
                img.setAttribute("src", "/Style Library/EssilorVariluxCore/images/divers/mail.gif");
                img.setAttribute("style", "border:\"0\"");
                mailto.appendChild(img);
              }
              mailCell.appendChild(mailto);
              break;
            case 'WebSite':
              var website = document.createTextNode(cellContent);
              if (cellContent.trim() != "") {
                website = document.createElement("a");
                website.setAttribute("href", "http://" + cellContent);
                website.setAttribute("target", "_blank");
                website.appendChild(document.createTextNode("www"));
              }
              websiteCell.appendChild(website);
            case 'GeoLat':
              latitude = cellContent;
              break;
            case 'GeoLng':
              longitude = cellContent;
              break;
            default:
              break;
          }
          ;
        }

        //adding the point to the list of markers
        var marker = null;
        var point = null;
        if (stamp != "" && latitude != "" && longitude != "") {
          point = new GLatLng(parseFloat(latitude), parseFloat(longitude));
          var icon = new GIcon();
          icon.image = MarkerIconUrl;
          icon.iconSize = new GSize(28, 29);
          icon.iconAnchor = new GPoint(14, 15);
          icon.infoWindowAnchor = new GPoint(5, 1);
          marker = new GMarker(point, icon);

          var htmlContent = "<div style=\"color:#000000\"><span style=\"font-weight:bold;\">" + title + "</span><br/>";
          if (address != "") {
            htmlContent += address + " ";
          }
          if (zipcode != "") {
            htmlContent += "<br/>" + zipcode + ", ";
          }
          if (city != "") {
            htmlContent += city;
          }
          if (telephone != "") {
            htmlContent += "<br/>Tel : " + telephone;
          }
          if (fax != "") {
            htmlContent += "<br/>Fax : " + fax;
          }
          htmlContent += "</div>";
          map.addOverlay(marker);
          markerKeys.push(stamp);
          markers[stamp] = marker;
          eval("GEvent.addListener(markers[stamp] , \"click\", function(){markers['" + stamp + "'].openInfoWindowHtml(windowHtmls['" + stamp + "']);});");
          windowHtmls[stamp] = htmlContent;
          opticianTBody.appendChild(row);
        }
      }
      if (results.hasChildNodes()) {
        results.removeChild(results.firstChild);
      }
      results.appendChild(opticianTable);
    }
    else if (responseCode == -1) {
      alert("Data request timed out. Please try later.");
    }
    else {
      alert("Request resulted in error. Check XML file is retrievable.");
    }
    imgLoading.style.display = 'none';
    addressElement.disabled = false;
    zipElement.disabled = false;
    townElement.disabled = false;
  });
}

function createOpticianStoreLocatorMap(mapContainerId) {
  var mapToReturn = new GMap2(document.getElementById(mapContainerId));

  mapToReturn.addControl(new GLargeMapControl());
  mapToReturn.addControl(new GMapTypeControl());

  //    var menuItem1 = document.createElement('a');
  //    menuItem1.setAttribute('href', 'javascript:map.setCenter(currentAddressMarker.getPoint(), 13);');
  //    menuItem1.className = 'OpticianLocatorVariluxSpecialist';
  //    var menuImage1 = document.createElement('img');
  //    menuImage1.setAttribute('src', CurrentAddressMarkerIconUrl);
  //    menuImage1.setAttribute('alt', 'Current address marker icon');
  //    menuItem1.appendChild(menuImage1);
  //    menuItem1.appendChild(document.createTextNode('Your location'));

  var menuItem2 = document.createElement('a');
  menuItem2.setAttribute('href', 'javascript:showHideMarkers();');
  menuItem2.className = 'OpticianLocatorVariluxSpecialist';
  var menuImage2 = document.createElement('img');
  menuImage2.setAttribute('src', MarkerIconUrl);
  menuImage2.setAttribute('alt', 'Marker icon');
  menuItem2.appendChild(menuImage2);
  menuItem2.appendChild(document.createTextNode('Optician stores'));

  //    storeLocatorMenuControl = new StoreLocatorMenuControl('storeLocatorMenu');
  //	  storeLocatorMenuControl.appendMenuItem(menuItem1, 'YourAddress');
  //    storeLocatorMenuControl.appendMenuItem(menuItem2, 'VariluxSpecialist');
  //    mapToReturn.addControl(storeLocatorMenuControl);

  return mapToReturn;
}

//set center on the marker and open its window
function markerFocus(stamp) {
  map.setCenter(markers[stamp].getPoint(), 13);
  markers[stamp].openInfoWindowHtml(windowHtmls[stamp]);
}

// StoreLocatorMenuControl
// Building a control for the Crizal store locator map menu
function StoreLocatorMenuControl(id) {
  this.menuid = id;

  var menu = document.createElement("ul");
  menu.setAttribute("id", this.menuid);
  //menu.style.display = "none";
  this.list = menu;
}

StoreLocatorMenuControl.prototype = new GControl();

StoreLocatorMenuControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  container.className = "OpticianLocatorStoreMapOptions";
  container.setAttribute("id", "OpticianLocatorStoreMapOptions");

  var showHideMenuDiv = document.createElement("a");
  showHideMenuDiv.setAttribute("href", "javascript:ReverseDisplay('" + this.menuid + "');");
  showHideMenuDiv.className = "OpticianLocatorStoreMapOptionsHider";

  container.appendChild(showHideMenuDiv);
  showHideMenuDiv.appendChild(document.createTextNode("Map options"));
  container.appendChild(this.list);

  map.getContainer().appendChild(container);
  return container;
}

StoreLocatorMenuControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 30));
}

//Add an item in the menu			
StoreLocatorMenuControl.prototype.appendMenuItem = function(node, cssClass) {
  var menuItem = document.createElement("li");
  menuItem.className = cssClass;
  this.list.appendChild(menuItem);
  menuItem.appendChild(node);
}
//end of StoreLocatorMenuControl

//Altern display style of the html element corresponding to the id specified
function ReverseDisplay(id) {
  var element = document.getElementById(id);
  if (element != null) {
    if (element.style.display == 'none')
      element.style.display = 'block';
    else
      element.style.display = 'none';
  }
}

//show or hide markers
function showHideMarkers() {
  for (var i = 0; i < markerKeys.length; i++) {
    try {
      if (markers[markerKeys[i]].isHidden()) {
        markers[markerKeys[i]].show();
      }
      else {
        markers[markerKeys[i]].hide();
      }
    }
    catch (error) {
      markers[markerKeys[i]].hide();
    }
  }
}

//Used for searching opticians by 'Enter' key press
function FireDefaultSearchButton(event) {
  if (event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea"))) {
    RetrieveListOfOptician();

    return false;
  }
}

String.prototype.trim = function() {
  return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

