(function(){
  window.onload = function(){
  var Cookie = function(name, val, expires, path, domain, secure){
    path = path || null;
    domain = domain || null;
    secure = secure || false;
    function set(key, value){
      var str = key + "=" + escape(value);
      if(expires > 0){
        var date = new Date();
        var ms = expires * 60 * 1000;
        date.setTime(date.getTime() + ms);
        str += ";expires=" + date.toGMTString();
      }
      if(path) str += ";path=" + path;
      if(domain) str += ";domain=" + domain;
      if(secure) str += ";true";
      document.cookie = str;
      return str;
    }
    function get(key){
      key = key || name;
      var strArray = document.cookie.split(';');
      for(var i = 0; i < strArray.length; i++)
      {
        var tmp = strArray[i].split('=');
        if(trim(tmp[0]) == trim(key)){
          return unescape(tmp[1]);
        }
      }
      return "";
    }
    function remove(key){
      var date = new Date();
      var ms = 1000;
      date.setTime(date.getTime() - ms);
      var str = name + "=nothing;expires=" + date.toGMTString();
      document.cookie = str;
    }
    function setExt(key, value){
      switch(key){
        case 'path':
          path = value;
          break;
        case 'domain':
          domain = value;
          break;
        case 'secure':
          secure = value;
          break;
        case 'expires':
          expires = value;
          break;
        default:
          set(key, value);
          break;
      }
    }
    return {
      get: get,
      set: setExt,
      remove: remove
    }
  }
 




  var extractUrl = function(){
    var extra = null;
    if(window.location.href.indexOf('.html') != -1)
    {
      var a = /thread-(\d+)-(\d+)-(\d+)\.html/.test(window.location.href);
      if(a){
        tid = RegExp.$1;
        page = RegExp.$2;
        extra = 'tid=' + tid + "&extra=" + encodeURIComponent("page=" + page);
      } 
    }
    if(window.location.href.indexOf('.php') != -1)
    {
      var val = window.location.href.indexOf('?');
      var url = window.location.href;
      extra = url.substring(val + 1);
    }
    return extra;
  }
  var extra = extractUrl();
  if(!extra) return;
  var base = "plugin.php?identifier=GMap&module=gmap";
  var cyclicLatLngFetch = function(data, func){
    data = eval(data);
    var idx = 0;
    function onPostLatLng(point){
      if (!point) {
        point = new GLatLng(39.908173,116.397947 + 0.01 * idx);
      }
      data[idx].point = point;
      
      if(idx < data.length - 1){
        idx ++;
        igeo.getLatLng(data[idx].region, onPostLatLng);
      } else {
        func(data);
      }
    }
    var igeo = new GClientGeocoder();
    igeo.getLatLng(data[idx].region, onPostLatLng);
  }

  var postFunc = function(data)
  {
    var inPoly = [];
    var bounds = new GLatLngBounds();
    for(var i = 0; i < data.length; i++){
      var img = 'plugins/gmap/images/posts/'+ (i + 1) + '.png';
      var icon = new GIcon(G_DEFAULT_ICON, img);
      icon.iconSize = new GSize(27, 40);
      icon.iconAnchor = new GPoint(14, 40);
      var marker = new GMarker(data[i].point, {
        icon: icon,
        draggable: true
      });
      map.addOverlay(marker);
      inPoly.push(data[i].point);
      bounds.extend(data[i].point);
      var space = "space.php";
      var msg = data[i].message;
      var iconstr = "";
      if(data[i].iconid && data[i].iconid != "0"){
        var iconsrc = base + "&act=icon&id=" + data[i].iconid;
        iconstr = "<img alt=\"avatar\" src=\"" + iconsrc + "\"/>";
      }
      var html = "<p class='info0'>第" + (i + 1) + "条 共" + data.length + "条&nbsp;&nbsp;&nbsp;" + iconstr + "<a target=\"_blank\" href=\"" + space + "?username=" + data[i].author + "\"><span class='author'>" + data[i].author + "</span></a>在<span>" + data[i].date + "</span>之前发表了话题:</p>";
        var title = "<p  style=\"color: red;\">" + data[i].subject + "</p>";
      marker.msg = msg;
      marker.title = title;
      marker.html = html;
      html += "<div style=\"overflow:auto;width: 300px;height: " + height + "px;\">" + msg + "</div>";
      html = "<div>" + title + html + "</div>";
      GEvent.addListener(marker, 'mouseover', function(){
        this.openInfoWindowHtml("<div>" + this.title + this.html + "<div style=\"overflow:auto;width: 300px;height: " + height + "px;\">" + this.msg + "</div></div>");
      });

      var dom = document.getElementById("pid" + data[i].pid);
      dom.marker = marker;
      GEvent.addDomListener(dom, 'mouseover', function(){
        GEvent.trigger(this.marker, 'mouseover');
        this.formerColor = this.style.color;
        this.style.color = "#ccc";
      });
      GEvent.addDomListener(dom, 'mouseout', function(){
        this.style.color = this.formerColor;
      });
    }
    var polyline = new GPolyline(inPoly, "#ff0000", 4);
    map.addOverlay(polyline);
    if(!bounds.isEmpty()) {
      var level = map.getBoundsZoomLevel(bounds);
      if(level > 16) level = 14;
      map.setZoom(level);
      map.panTo(bounds.getCenter());
    }
  }


  var newFunc = function(data)
  {
    var inPoly = [];
    var bounds = new GLatLngBounds();
    for(var i = 0; i < data.length; i++){
      var img = 'plugins/gmap/images/posts/'+ (i + 1) + '.png';
      var icon = new GIcon(G_DEFAULT_ICON, img);
      icon.iconSize = new GSize(27, 40);
      icon.iconAnchor = new GPoint(14, 40);
      var marker = new GMarker(data[i].point, {
        icon: icon,
        draggable: true
      });
      map.addOverlay(marker);
      inPoly.push(data[i].point);
      bounds.extend(data[i].point);
      var space = "space.php";
      var viewpost = base + "viewthread.php";
      var msg = data[i].message;
      var iconstr = "";
      if(data[i].iconid && data[i].iconid != "0"){
        var icon = window.location + "&act=icon&id=" + data[i].iconid;
        iconstr = "<img alt=\"avatar\" src=\"" + icon + "\"/>";
      }
      var html = "<p class='info0'>第" + (i + 1) + "条 共" + data.length + "条&nbsp;&nbsp;&nbsp;" + iconstr + "<a target=\"_blank\" href=\"" + space + "?username=" + data[i].author + "\"><span class='author'>" + data[i].author + "</span></a>在<span>" + data[i].date + "</span>之前发表了话题:</p>";
      html += "<div class=\"msg\">" + msg + "</div>";
      var dom = document.createElement('div');
      dom.className = "info";
      dom.innerHTML = html;

      var str = "<div class=\"info\">" + html + "</div>";
      html = str;
      marker.html = html;
        var title = "<a target=\"_blank\"   style=\"color: red;\" href=\"" + viewpost + "?tid=" + data[i].tid + "\">" + data[i].subject + "</a>";
      marker.title = title;
      GEvent.addListener(marker, 'click', function(){
        var html = "<h1>" + this.title + "</h1>" + this.html;
        this.openInfoWindowHtml(html);
      });
    }
    var polyline = new GPolyline(inPoly, "#ff0000", 4);
    map.addOverlay(polyline);
    if(!bounds.isEmpty()) {
      var level = map.getBoundsZoomLevel(bounds);
      if(level > 16) level = 14;
      map.setZoom(level);
      map.panTo(bounds.getCenter());
    }
  }

  var getPostList = function(url){
    GDownloadUrl(url, function(data){
      try{
        data = eval(data);
        if(data && data.length > 0)
        {
          cyclicLatLngFetch(data, postFunc);
        }
      } catch(e) {
        alert(e);
      }
    });
  }

  var getNewList = function(url){
    GDownloadUrl(url, function(data){
      try{
        data = eval(data);
        if(data && data.length > 0)
        {
          cyclicLatLngFetch(data, newFunc);
        }
      } catch(e) {
        alert(e);
      }
    });
  }



  function showMap(){
    mapNode.style.display = "";
    map = new GMap2(document.getElementById(id));
    if (!latlng && google.loader.ClientLocation) {
      latlng = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
    } else if(!latlng){
      latlng = new GLatLng(39.908173, 116.397947);
    }
    map.setCenter(latlng, zoom);
    map.enableScrollWheelZoom();
    map.addControl(new GMapTypeControl());
    var url = base + "&act=post&" + extra;
    getPostList(url);
    var cur = $('gmap_current');
    GEvent.addDomListener(cur, 'click', function(){
      map.clearOverlays();
      url = base + "&act=post&" + extra;
      getPostList(url);
    });
    var newpost = $('gmap_newpost');
    GEvent.addDomListener(newpost, 'click', function(){
      map.clearOverlays();
      url = base + "&act=newPost";
      getNewList(url);
    });
  }

  var zoom = 10;
  var id = 'gmap_map';
  var latlng = null;
  var height = 100;
  var width = 300;
  var cookieName = 'gmap_post_display';
  var cookie = Cookie(cookieName, 1);
  var init = false;
  var mapNode = document.getElementById(id);
  var hide = document.getElementById('gmap_hide');
  var show = document.getElementById('gmap_show');
  var x1 = document.getElementById('gmap_x1');
  var x2 = document.getElementById('gmap_x2');
  var map = null;
  hide.onclick = function(){
    mapNode.style.display = "none";
    hide.style.display = "none";
    show.style.display = "";
    cookie.set(cookieName, 1);
  }
  show.onclick = function(){
    mapNode.style.display = "";
    this.style.display = "none";
    hide.style.display = "";
    if(!init){
      google.load('maps', '2'
      , {
        'callback': showMap,
        'language': 'zh_CN',
        'other_params': ''
      });
      init = true;
    }
    cookie.remove(cookieName);
  }
  x1.onclick = function(){
    mapNode.style.height = "250px";
    height = 100;
    map.checkResize();
  }
  x2.onclick = function(){
    mapNode.style.height = "500px";
    height = 200;
    map.checkResize();
  }
  if(cookie.get(cookieName)){
    mapNode.style.display = "none";
    hide.style.display = "none";
    show.style.display = "";
  } else {
    google.load('maps', '2'
    , {
      'callback': showMap,
      'language': 'zh_CN',
      'other_params': ''
    });
  
    init = true;
    }
  }
})();

