// Copyright 2009 Google Inc.
// All Rights Reserved.

/**
 * @fileoverview adding a custom map, according to the map info
 * providing by _mapInfo array crate new maps.
 * @author frank2008cn@gmail.com (Xiaoxi Wu)
 */

(function() {

   // get maps max width to decide the container's width.
   var maxWidth = 0;
   var key = "ABQIAAAAec0uG9m_VSLs4ZXN8YGMoRTD9uafkkzDhLPecS9POo8mzN4tDBSpJpECPM0UCHhROxov8yyy5vwVSQ";;
   if (_mapInfo[0] != "undefined" &&  _mapInfo[0] != "") {
     key = _mapInfo[0];
   }

   if(typeof _mapInfo == "undefined" || _mapInfo.length <= 1
      || typeof($("map_content")) == "undefined") {
     return;
   } else {
     for(var i = 1; i < _mapInfo.length; i++) {
       if(maxWidth < _mapInfo[i].width) {
         maxWidth = _mapInfo[i].width;
       }
     }
       $("map_content").style.width = maxWidth + "px";
   }

   // namespace for globe access.
   var G = {

     /**
      * load maps api.
      */
     loadJs: function() {
       google.load("maps", "2", {"callback" : init, 'base_domain': 'ditu.google.cn'});
     },
     loadApp: function() {
       loadApp();
     }
   };

   /**
    * load google ajax api then call the callback function(loadJs).
    */
   function loadApp() {
     load(
       'http://www.google.com/jsapi?key=' + key + '&callback=_MpTemplate.loadJs'
     );
   }

   /**
    * load a static map when application start. when user click on the
    * static map load the normal map.
    */
   function loadStaticMap() {
     for (var i = 1; i < _mapInfo.length; ++i) {
       var cont = document.createElement("div");
       $("map_content").appendChild(cont);

       var type = _mapInfo[i].type;
       var itype = "roadmap";
       if(type == 1) {
         itype = "roadmap";
       } else if (type == 2) {
         itype = "satellite";
       } else if (type == 3) {
         itype = "terrain";
       }

       var markersStr = "";
       for (var j = 0; j < _mapInfo[i].markers.length; j++) {
         var markerInfo = _mapInfo[i].markers[j];
         if (j != 0 ) {
           markersStr += "|";
         }
         markersStr += markerInfo.lat + "," + markerInfo.lng + "," + markerInfo.color;
       }

       var src = 'http://ditu.google.cn/staticmap?center=' + _mapInfo[i].lat + ',' + _mapInfo[i].lng + '&maptype='
         + itype + '&zoom=' + _mapInfo[i].zoom + '&size=' + _mapInfo[i].width + 'x' + _mapInfo[i].height + '&key='
         + key + '&markers=' + markersStr + '&sensor=false';
       if (_mapInfo[i].title != "") {
         var title = document.createElement("h3");
         title.innerHTML = unescape(_mapInfo[i].title);
         var tcss = 'margin:0 0 5px 0;';
         if (i != 1) {
           tcss = 'margin:20px 0 5px 0;';
         }
         title.style.cssText = tcss + 'background:#E8ECF9;'
           + 'border-top:1px solid #AABEF3;border-bottom:1px solid #AABEF3;padding:1px 3px;';
         cont.appendChild(title);
       }

       var container = document.createElement("div");
       var mcontainer = document.createElement("div");
       container.id = "map_content_" + i;
       mcontainer.appendChild(container);
       if (_mapInfo[i].title == "" && i != 1) {
         mcontainer.style.marginTop = "20px";
       }
       container.style.cssText = "width:" + _mapInfo[i].width + "px;height:"
         + _mapInfo[i].height + "px;";
       cont.appendChild(mcontainer);
       if (_mapInfo[i].width > 640 || _mapInfo[i].height > 640) {
         loadApp();
       }
       else {
        container.innerHTML = "<img src='" + src + "' onmousedown='_MpTemplate.loadApp()'"
          + " style='cursor:pointer;'></img>";
       }
       var link = 'http://ditu.google.cn/maps?f=q&source=s_q&hl=zh-CN&geocode=&q='
         + unescape(_mapInfo[i].title) + '&sll=' + _mapInfo[i].lat + ',' + _mapInfo[i].lng + '&g='
         + unescape(_mapInfo[i].title) + '&ie=GBK&ll=' + _mapInfo[i].mlat +  ","
         + _mapInfo[i].mlng + '&z=' + _mapInfo[i].zoom;
       var alink = document.createElement("a");
       alink.style.cssText = "width:80px;display:block;height:22px;line-height:22px;";
       alink.target = "_blank";
       alink.href = link;
       alink.innerHTML = "查看大图";
       mcontainer.appendChild(alink);
     }
   }

   /**
    * load a single js file.
    * @param {string} url the js file url.
    * @param {function} callback the callback function while js file loaded.
    */
   function load(url, callback) {
     var script = document.createElement("script");
     if (typeof callback != "undefined") {
       script.onload = callback;
       script.onreadystatechange = callback;
     }
     script.src = url;
     script.type = "text/javascript";
     var hd = document.getElementsByTagName("head");
     if (hd == null || hd.length == 0) {
       hd = document.createElement("head");
       document.body.parentNode.appendChild(hd);
       hd = [hd];
     }
     hd[0].appendChild(script);
   }

   /**
    * when maps api loaded initialize the application.
    * show all the maps.
    */
   function init() {
     if (GBrowserIsCompatible()){
       for (var i = 1; i < _mapInfo.length; ++i) {
         var control = _mapInfo[i].control;
         var container = $("map_content_" + i);
         container.innerHTML = "";
         var map = new GMap2(container);
         var wid = _mapInfo[i].width;
         var hei = _mapInfo[i].height;
         map.addMapType(G_PHYSICAL_MAP);

         // decide which control should be showed.
         if (control.charAt(0) == "1") {
           if (hei < 200) {
             map.addControl(new GSmallZoomControl());
           } else if (hei < 300) {
             map.addControl(new GSmallMapControl());
           }
           else {
             map.addControl(new GLargeMapControl());
           }
         }
         if (control.charAt(1) == "1") {
           if (wid > 480) {
             map.addControl(new GMapTypeControl());
           } else {
             map.addControl(new GMenuMapTypeControl());
           }
         }
         if (control.charAt(3) == "1") {
           if (wid > 480 && hei > 200) {
             map.addControl(new GOverviewMapControl());
           }
         }

         map.setCenter(new GLatLng(_mapInfo[i].lat, _mapInfo[i].lng), _mapInfo[i].zoom);
         if (control.charAt(2) == "1") {
           map.enableGoogleBar();
         }

         // decide map type.
         if (_mapInfo[i].type == 1) {
           map.setMapType(G_NORMAL_MAP);
         } else if (_mapInfo[i].type == 2){
           map.setMapType(G_SATELLITE_MAP);
         } else {
           map.setMapType(G_PHYSICAL_MAP);
         }
         for (var j = 0; j < _mapInfo[i].markers.length; j++) {
           var markerInfo = _mapInfo[i].markers[j];
           var baseIcon = new GIcon(G_DEFAULT_ICON);
           baseIcon.shadow = "http://maps.google.com//intl/en_ALL/mapfiles/ms/micons/msmarker.shadow.png";
           baseIcon.iconSize = new GSize(32, 32);
           baseIcon.shadowSize = new GSize(37, 34);
           baseIcon.iconAnchor = new GPoint(16, 32);
           baseIcon.infoWindowAnchor = new GPoint(16, 2);
           var marker = new GMarker(new GLatLng(markerInfo.lat, markerInfo.lng), {title: markerInfo.title, icon: baseIcon});
           var info = unescape(markerInfo.info);
           if (info != "") {
             GEvent.addListener(marker, "click", openInfoFn(map, marker, info));
             if(_mapInfo[i].markers.length == 1) {
               map.openInfoWindowHtml(marker.getLatLng(), info);
             }
           }
           map.addOverlay(marker);
           marker.setImage('http://maps.google.com/intl/en_ALL/mapfiles/ms/micons/' + markerInfo.color + '-dot.png');
         }
       }
     }
   };

   function openInfoFn(map, marker, info) {
     return function() {
       map.openInfoWindowHtml(marker.getLatLng(), info);
     };
   }

   /**
    * get dom element by id
    * @param {string} element element id.
    * @return {object} dom object.
    */
   function $(element) {
     return document.getElementById(element);
   }

   // expose globe interface and init applicationi.
   window._MpTemplate = G ||  window._MpTemplate;
   loadStaticMap();
 })();

