var map = null;
var geocoder = null;
var marker;

/************************* brand map ***************************/
function initialize()
{
  if (GBrowserIsCompatible())
  {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addMapType(G_PHYSICAL_MAP);
    map.setCenter(new GLatLng(25.001689, 121.460809), 14);
    geocoder = new GClientGeocoder();
    showAddress(document.getElementById("address").value);
  }
}

function createMarker(point,title,html)
{
  var marker = new GMarker(point);

  GEvent.addListener(marker, "load", function()
      {
    marker.openInfoWindowHtml(
        html,
        {
          maxContent: html,
          maxTitle: title}
    );
      });

  GEvent.addListener(marker, "click", function(){
    marker.openInfoWindowHtml(
        html,
        {
          maxContent: html,
          maxTitle: title}
    );
  });
  return marker;
}

function showAddress(address)
{
  if (geocoder)
  {

    geocoder.getLatLng(
        address,
        function(point)
        {
          if (!point)
          {
            //alert(address + " not found");
          }
          else
          {
            if(marker)
            {
              map.removeOverlay(marker);
            }
            map.setCenter(point, 16);

            var title = "address";

            marker = createMarker(point,title,address);

            map.addOverlay(marker);

            marker.openInfoWindowHtml(
                address,
                {
                  maxContent: address,
                  maxTitle: title}
            );
          }
        }
    );
  }
}

/************************* index map ***************************/
var shopSize = 0;
var shopArray  = new Array();
function indexInit()
{
  var shopGrid = document.getElementById("shopGrid");
  if(shopGrid!=null && shopGrid!="undefined" && shopGrid.getElementsByTagName("tr")!=null && shopGrid.getElementsByTagName("tr").length>0){
    shopSize = shopGrid.getElementsByTagName("tr").length;
    for(var i = 0; i < shopSize; i++){
      if(document.getElementById("shopGrid:"+i)!=null){
        var shop = document.getElementById("shopGrid:"+i).innerHTML;
        shopArray.push(shop);
      }
    }
  }

  if (GBrowserIsCompatible())
  {
    map = new GMap2(document.getElementById("map"));
    map.addMapType(G_PHYSICAL_MAP);
    map.setCenter(new GLatLng(25.001689, 121.460809), 14);
    geocoder = new GClientGeocoder();

    shopRefresh();
  }
}

var searchNo;
function shopRefresh(){
  if(searchNo==null){
    var vNum = Math.random();
    vNum = Math.round(vNum*(shopSize-1));
    searchNo = vNum;
  }else{
    if(searchNo==(shopSize-1)){
      searchNo = 0;
    }else{
      searchNo++;
    }
  }
  if(shopSize==0){
    indexAddress("");
  }else{
    var data = shopArray[searchNo].split(";");
    var zipcode, address, brandId, brandName, logoId;
    if(data.length>0){
      zipcode = data[0];
    }
    if(data.length>1){
      address = data[1];
    }
    if(data.length>2){
      brandId = data[2];
    }
    if(data.length>3){
      brandName = data[3];
    }
    if(data.length>4){
      logoId = data[4];
    }

    indexAddress(zipcode, address, brandId, brandName, logoId);
  }

  setTimeout("shopRefresh()", 10000);
}

function indexCreateMarker(point,title,html)
{
  var marker = new GMarker(point);

  GEvent.addListener(marker, "load", function()
      {
    marker.openInfoWindowHtml(
        html,
        {
          maxContent: html,
          maxTitle: title}
    );
      });

  GEvent.addListener(marker, "click", function(){
    marker.openInfoWindowHtml(
        html,
        {
          maxContent: html,
          maxTitle: title}
    );
  });
  return marker;
}

function indexAddress(zipcode, address, brandId, brandName, logoId)
{
  if (geocoder)
  {
    geocoder.getLocations(address,
        function addAddressToMap(response) {

      map.clearOverlays();

      if (!response || response.Status.code != 200) {

        //alert("查無資料！");

      } // if
      else {

        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
            place.Point.coordinates[0]);
        var title = brandName+" 地址";
        var html;
        if(logoId!=null){
          html="<table><tr>"+
          "<td><img src=\""+logoId+"\"/></td>"+
          "<td><div><a href=\"/pub/store.seam?brandId="+brandId+"\" target=\"_top\">"+brandName+"</a></div>"+zipcode+":"+address+"</td>"+
          "</tr></table>"
        }else{
          html="<table><tr>"+
          "<td><div><a href=\"/pub/store.seam?brandId="+brandId+"\" target=\"_top\">"+brandName+"</a></div>"+zipcode+":"+address+"</td>"+
          "</tr></table>"
        }
        map.setCenter(point, 14);
        marker = indexCreateMarker(point,title,html);

        map.addOverlay(marker);
        marker.openInfoWindowHtml(
            html,
            {
              maxContent: address,
              maxTitle: title}
        );
      } // else
    }
    );

  }
}

/***************************** shop edit  ***********************************/
function shopInit()
{
  if (GBrowserIsCompatible())
  {
    geocoder = new GClientGeocoder();
    if(document.getElementById("shopEdit:addressDecoration:address")!=null &&
        document.getElementById("shopEdit:addressDecoration:address").value!=null &&
        document.getElementById("shopEdit:addressDecoration:address").value.length>0){
      address(document.getElementById("shopEdit:addressDecoration:address").value, true);
    }
  }
}

function address(address, isShop) {
  if (geocoder) {

    geocoder.getLocations(address, function(response){

      if (!response || response.Status.code != 200) {
        alert("查詢不到此地址！");

      } else {
        place = response.Placemark[0];
        if(place!=null){
          var lat, lon, postalCode;

          if(place.Point!=null){
            lat = place.Point.coordinates[1];
            lon = place.Point.coordinates[0];

            if(isShop){
              var point = new GLatLng(lat,lon);
              if(marker){
                map.removeOverlay(marker);
              }
              map.setCenter(point, 14);
              marker = new GMarker(point, {draggable: true});
              placeMarker(isShop);
            }

          }
          if(isShop){
            if(place.AddressDetails!=null && place.AddressDetails.AdministrativeArea!=null
                && place.AddressDetails.AdministrativeArea.Locality!=null && place.AddressDetails.AdministrativeArea.Locality.PostalCode!=null){
              postalCode = place.AddressDetails.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
            }

            if(document.getElementById("shopEdit:addressDecoration:zipcode")!=null){
              if(postalCode!=null){
                document.getElementById("shopEdit:addressDecoration:zipcode").value = postalCode;
              }else{
                document.getElementById("shopEdit:addressDecoration:zipcode").value = "";
              }
            }
          }else if(!isShop && lat!=null && lon!=null){
            map.clearOverlays();
            setGeoAreaValue("center",lat, lon, true);
            setGeoAreaValue("ul",lat+0.001, lon-0.001, false);
            setGeoAreaValue("br",lat-0.001, lon+0.001, false);
          }
        }
      }
    });
  }
}

function placeMarker(isShop) {
  map.addOverlay(marker);

  updateMarker(marker, isShop, "center");
  GEvent.addListener(marker, "dragend", function() {
    updateMarker(marker, isShop, "center");
  });
  GEvent.addListener(marker, "click", function() {
    updateMarker(marker, isShop, "center");
  });
}

function editPlaceMarker() {
  var latElementId = "shopEdit:latlonDecoration:centerLat";
  var lonElementId = "shopEdit:latlonDecoration:centerLon";
  if(document.getElementById(latElementId)!=null && document.getElementById(latElementId).value!=null && document.getElementById(latElementId).value.length>0 &&
      document.getElementById(lonElementId)!=null  && document.getElementById(lonElementId).value!=null && document.getElementById(lonElementId).value.length>0){
    var point = new GLatLng(document.getElementById(latElementId).value, document.getElementById(lonElementId).value);
    marker = new GMarker(point, {draggable: true});
    map.setCenter(point, 14);
    map.addOverlay(marker);
    updateMarker(marker, true, "center");
    GEvent.addListener(marker, "dragend", function() {
      updateMarker(marker, true, "center");
    });
    GEvent.addListener(marker, "click", function() {
      updateMarker(marker, true, "center");
    });
  }else{
    map.setCenter(new GLatLng(25.001689, 121.460809), 14);
  }
}

function updateMarker(marker, isShop, position) {
  var latlng = marker.getPoint();
  lat = latlng.lat();
  lon = latlng.lng();

  var elementId;
  if(isShop){
    elementId = "shopEdit:latlonDecoration:"+position;
  }else{
    elementId = "geoAreaEdit:latlonDecoration:"+position;
  }
  if(document.getElementById(elementId+"Lat")!=null){
    if(lat!=null){
      document.getElementById(elementId+"Lat").value = lat;
    }else{
      document.getElementById(elementId+"Lat").value = "";
    }
  }
  if(document.getElementById(elementId+"Lon")!=null){
    if(lon!=null){
      document.getElementById(elementId+"Lon").value = lon;
    }else{
      document.getElementById(elementId+"Lon").value = "";
    }
  }
}

/***************************** geoArea edit  ***********************************/
var setId;
var centermarker, ulmarker, brmarker;
function initGeoAreaEdit(){
  addGMarker("center", true);
  addGMarker("ul", false);
  addGMarker("br", false);
}

function addGMarker(elementId, center){
  var latElementId;
  var lonElementId;
  latElementId = "geoAreaEdit:latlonDecoration:"+elementId+"Lat";
  lonElementId = "geoAreaEdit:latlonDecoration:"+elementId+"Lon";
  if(document.getElementById(latElementId)!=null && document.getElementById(latElementId).value!=null && document.getElementById(latElementId).value.length>0 &&
      document.getElementById(lonElementId)!=null  && document.getElementById(lonElementId).value!=null && document.getElementById(lonElementId).value.length>0){
    var point = new GLatLng(document.getElementById(latElementId).value, document.getElementById(lonElementId).value);

    if(center){
      map.setCenter(point, 14);
      if(centermarker==null){
        markerAddListener(centermarker, elementId, point, true);
      }
    }else{

      if("ul" == elementId && ulmarker == null){
        markerAddListener(ulmarker, elementId, point, false);

      }else if(brmarker == null){
        markerAddListener(brmarker, elementId, point, false);
      }
    }

  }

}

function markerAddListener(oldmarker, elementId, point, center){
  if(center){
    oldmarker = new GMarker(point, {draggable: true});
  }else{
    oldmarker = new GMarker(point, {icon: getIcon(), draggable: true});
  }
  map.addOverlay(oldmarker);
  GEvent.addListener(oldmarker, "dragend", function() {
    updateMarker(oldmarker, false, elementId);
  });
  GEvent.addListener(oldmarker, "click", function() {
    updateMarker(oldmarker, false, elementId);
  });
}

function setGeoAreaValue(elementId, lat, lon, isCenter){
  var latElementId;
  var lonElementId;
  latElementId = "geoAreaEdit:latlonDecoration:"+elementId+"Lat";
  lonElementId = "geoAreaEdit:latlonDecoration:"+elementId+"Lon";
  if(document.getElementById(latElementId)!=null){
    document.getElementById(latElementId).value = lat;
  }
  if(document.getElementById(lonElementId)!=null){
    document.getElementById(lonElementId).value = lon;
  }

  addGMarker(elementId, isCenter);
}


function geoAreaPlaceMarker(id) {
  setId = id;
  var listener = GEvent.addListener(map, "click", function(overlay, latlng) {
    if (latlng) {
      GEvent.removeListener(listener);
      var color = "orange";
      var marker = new GMarker(latlng, {icon: getIcon(), draggable: true});
      map.addOverlay(marker);
      updateMarker(marker, false, setId);
      GEvent.addListener(marker, "dragend", function() {
        updateMarker(marker, false, setId);
      });
      GEvent.addListener(marker, "click", function() {
        updateMarker(marker, false, setId);
      });
    }
  });
}


function setGeoArea() {
  geocoder = new GClientGeocoder();
  if(document.getElementById("geoAreaEdit:addressDecoration:address")!=null &&
      document.getElementById("geoAreaEdit:addressDecoration:address").value!=null &&
      document.getElementById("geoAreaEdit:addressDecoration:address").value.length>0){
    address(document.getElementById("geoAreaEdit:addressDecoration:address").value, false);
  }
}


function getIcon() {
  var icon = new GIcon();
  icon.image = "http://google.com/mapfiles/ms/micons/orange.png";
  icon.iconSize = new GSize(32, 32);
  icon.iconAnchor = new GPoint(15, 32);
  return icon;
}

/****************************** shop test ********************************/
var shopErrorArray;
function shopTestInit()
{

  shopErrorArray = new Array();
  var shopGrid = document.getElementById("shopTest:shopGrids");
  if(shopGrid!=null && shopGrid!="undefined"){
    var shopTestSize = document.getElementById("shopTest:shopSize").innerHTML;
    for(var i = 0; i < shopTestSize; i++){
      var shopName, address;
      if(document.getElementById("shopTest:shopGrids:"+i+":shopName")!=null){
        shopName = document.getElementById("shopTest:shopGrids:"+i+":shopName").innerHTML;
      }
      if(document.getElementById("shopTest:shopGrids:"+i+":addressDecoration:address")!=null
          && document.getElementById("shopTest:shopGrids:"+i+":addressDecoration:address").value.length>0){
        address = document.getElementById("shopTest:shopGrids:"+i+":addressDecoration:address").value;
      }

      if (GBrowserIsCompatible())
      {
        /*map = new GMap2(document.getElementById("map"+i));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(25.001689, 121.460809), 14);*/
        geocoder = new GClientGeocoder();
      }
      shopTestAddress(shopName, address, i);

      if(i == shopTestSize-1 && shopErrorArray.length>0){
        var errorMessages;
        for ( var index = 0; index < shopErrorArray.length; index++) {
          var shopError = shopErrorArray[index];
          errorMessages += shopError +", ";
        }
        alert(errorMessages);
      }
    }
  }
}

function shopUpdateAddress(shopName, index){
  if(document.getElementById("shopTest:shopGrids:"+index+":addressDecoration:address")!=null
      && document.getElementById("shopTest:shopGrids:"+index+":addressDecoration:address").value.length>0){
    var address = document.getElementById("shopTest:shopGrids:"+index+":addressDecoration:address").value;
    shopTestAddress(shopName, address, index);
  }
}

function shopTestAddress(shopName, address, index) {
  if (geocoder)
  {
    geocoder.getLocations(address,
        function addAddressToMap(response) {

      //map.clearOverlays();

      if (!response || response.Status.code != 200) {

        var errorMessage = "分店："+shopName;
        shopErrorArray.push(errorMessage);
      } // if
      else {

        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        //marker = new GMarker(point, {draggable: true});
        updateTestMarker(point, index);
        /*map.setCenter(point, 14);
        map.addOverlay(marker);
        updateTestMarker(marker, index);
        GEvent.addListener(marker, "dragend", function() {
          updateTestMarker(marker, index);
        });
        GEvent.addListener(marker, "click", function() {
          updateTestMarker(marker, index);
        });*/

      } // else
    }
    );

  }
}

function updateTestMarker(point, index) {
  var latlng = point;
  lat = latlng.lat();
  lon = latlng.lng();

  var elementId = "shopTest:shopGrids:"+index+":latlonDecoration:center";

  if(document.getElementById(elementId+"Lat")!=null){
    if(lat!=null){
      document.getElementById(elementId+"Lat").value = lat;
    }else{
      document.getElementById(elementId+"Lat").value = "";
    }
  }
  if(document.getElementById(elementId+"Lon")!=null){
    if(lon!=null){
      document.getElementById(elementId+"Lon").value = lon;
    }else{
      document.getElementById(elementId+"Lon").value = "";
    }
  }
}
