/**
 * @fileoverview A demo for canvas tools of google maps.
 * @author frank2008cn@gmail.com (Xiaoxi Wu)
 */

(function() {

   var map = null;
   var teams = null;
   var schedule = null;
   var teamSchedule = null;
   var tip = null;
   var stadiums = {};
   var playing = false;
   var curMatch = null;

   function $(element) {
     return document.getElementById(element);
   }

   function $n(tag, className, styles) {
     var ele = document.createElement(tag);
     if (className) {
       ele.className = className;
     }
     if (styles) {
       ele.style.cssText = styles;
     }
     return ele;
   }

   function $a(parent, child) {
     parent.appendChild(child);
   }

   var G = {
     init: function() {
       map = new GMap2($("map_content"));
       map.setCenter(new GLatLng(39.91, 116.38), 2);
       map.addControl(new GLargeMapControl());
       tip = new SToolTip();
       map.addOverlay(tip);
       GDownloadUrl('/sports/data/nba-teams.json', G.gotTeam);
     },
     gotTeam: function(data) {
       data = eval(data);
       var eastern = data[0].sub[0];
       var western = data[0].sub[1];
       teams = [];
       for (var i = 0; i < eastern.sub.length; ++i) {
         var tms = eastern.sub[i].sub;
         for (var j = 0; j < tms.length; ++j) {
           teams.push(tms[j]);
         }
       }
       for (i = 0; i < western.sub.length; ++i) {
         var tms = western.sub[i].sub;
         for (var j = 0; j < tms.length; ++j) {
           teams.push(tms[j]);
         }
       }
       for (i = 0; i < teams.length; ++i) {
         var opt = $n('option');
         opt.value = teams[i].cn;
         opt.text = teams[i].name;
         $('teamlist').options.add(opt);
       }
       GEvent.addDomListener($('teamlist'), 'change', G.changeTeam);
       $('match-month').value = 'nba200803';
       GEvent.addDomListener($('match-month'), 'change', G.requestSchedule);
       GDownloadUrl('/sports/data/nba200903.json', G.gotSchedule);
     },
     requestSchedule: function() {
       var month = $('match-month').value;
       GDownloadUrl('/sports/data/' + month + '.json', G.gotSchedule);
     },
     gotSchedule: function(data) {
       data = eval(data);
       schedule = data;
       map.clearOverlays();
       map.addOverlay(tip);
       stadiums = {};
       GEvent.addDomListener($('match-play'), 'click', G.play);
       GEvent.addDomListener($('match-next'), 'click', G.showMatchFn('next'));
       GEvent.addDomListener($('match-previous'), 'click', G.showMatchFn('previous'));
       teamSchedule = G.getTeamSchedule($('teamlist').value);
       G.showSchedule(teamSchedule);
     },
     getTeamSchedule: function(team) {
       var result = [];
       for (var i = 0; i < schedule.length; ++i) {
         if (schedule[i].home == team || schedule[i].away == team) {
           result.push(schedule[i]);
         }
       }
       return result;
     },
     play: function() {
       if (playing == true) {
         G.changeTeam();
         return;
       }
       $('control-buttons').style.display = '';
       this.value = info.stop;
       map.clearOverlays();
       map.addOverlay(tip);
       stadiums = null;
       var cur = teamSchedule[0];
       curMatch = 0;
       playing = true;
       var markers = [];
       for (var i = 0; i < teams.length; ++i) {
         if (cur.home == teams[i].cn) {
           if (teams[i].coor) {
             var latlng = teams[i].coor.split(',');
             latlng = new GLatLng(latlng[1], latlng[0]);
             var marker = new SMarker(latlng, '', teams[i].stadium, tip, [50, 50], '/sports/img/team50x50/' + teams[i].micon + '.gif');
             map.addOverlay(marker);
             markers.push(marker);
             var clickEvt = G.singleMatch(cur, teams[i], latlng);
             GEvent.addListener(marker, 'click', clickEvt);
             clickEvt();
             break;
           }
         }
       }
       G.resetMap(markers);
     },
     showMatchFn: function(type) {
       return function() {
         G.showMatch(type);
       };
     },
     showMatch: function(type) {
       if (type == 'next') {
         curMatch++;
         if (curMatch == teamSchedule.length) {
           curMatch --;
           return;
         }
       } else {
         curMatch--;
         if (curMatch < 0) {
           curMatch = 0;
           return;
         }
       }
       map.clearOverlays();
       map.addOverlay(tip);
       var pre = curMatch - 1;
       if (pre < 0) {
         pre = null;
       } else {
         pre = teamSchedule[pre];
       }
       var next = curMatch + 1;
       if (next == teamSchedule.length) {
         next = null;
       } else {
         next = teamSchedule[next];
       }
       var cur = teamSchedule[curMatch];

       var preMatch = pre ? G.getTeamByNick(pre.home) : null;
       var curMat = cur ? G.getTeamByNick(cur.home) : null;
       var nextMatch = next ? G.getTeamByNick(next.home) : null;
       var curLatLng = curMat.coor.split(',');
       curLatLng = new GLatLng(curLatLng[1], curLatLng[0]);
       var markers = [];
       var marker = new SMarker(curLatLng, '', curMat.stadium, tip, [50, 50], '/sports/img/team50x50/' + curMat.micon + '.gif');

       var arrow = null;

       markers.push(marker);
       map.addOverlay(marker);
       if (preMatch != null && preMatch != curMat) {
         if(preMatch.coor) {
           var latlng = preMatch.coor.split(',');
           latlng = new GLatLng(latlng[1], latlng[0]);
           var preMarker = new SMarker(latlng, '', preMatch.stadium, tip, [50, 50], '/sports/img/team50x50/' + preMatch.micon + '.gif');
           GEvent.addListener(preMarker, 'click', G.showMatchFn('previous'));
           map.addOverlay(preMarker);
           arrow = new _CArrow(latlng, curLatLng, null, null, {opacity: 0.5, margin: 30, angle: 20, color: '#FF0000', editColor: '#0000FF'});
           map.addOverlay(arrow);
           markers.push(preMarker);
         }
       }
       var clickEvt = G.singleMatch(cur, curMat, curLatLng, arrow);
       GEvent.addListener(marker, 'click', clickEvt);
/*       if (nextMatch != null && nextMatch != curMat) {
         if(nextMatch.coor) {
           var latlng = nextMatch.coor.split(',');
           latlng = new GLatLng(latlng[1], latlng[0]);
           marker = new SMarker(latlng, '', nextMatch.stadium, tip, [50, 50], '/sports/img/team50x50/' + nextMatch.micon + '.gif');
           map.addOverlay(marker);
           var arrow = new _CArrow(curLatLng, latlng, null, null, {opacity: 0.5, margin: 30, angle: 20, color: '#FF0000', editColor: '#0000FF'});
           map.addOverlay(arrow);
           markers.push(marker);
         }
       }*/
       G.resetMap(markers);
       clickEvt();
     },
     singleMatch: function(match, stadium, latlng, arrow) {
       return function() {
         var div = $n('div', '', 'line-height:18px;');
         var cont = $n('div', '', '');
         var htm = '<div style="font-size:1.2em;font-weight:bold;margin-bottom:5px;">' + match.date + '</div>';
         htm += '<div style="font-size: 1.1em;margin-bottom:5px;">' + match.home + '&nbsp;(' + info.home + ')&nbsp;';
         htm += '<span style="color:red;font-weight:bold;font-size:0.8em;">&nbsp;VS&nbsp;</span>';
         htm += match.away + '</div>';
         htm += '<b>' + info.bscore + '</b>&nbsp;' + match.boxscore + '<br/>';
         htm += '<b>' + info.hpoints + '</b>&nbsp;' + match.hpoints + '<br/>';
         htm += '<b>' + info.hrebounds + '</b>&nbsp;' + match.hrebounds + '<br/>';
         htm += '<b>' + info.hassists + '</b>&nbsp;' + match.hassists + '<br/>';
         htm += '<b>' + info.stadium + '</b>&nbsp;' + '<span style="color:#0000cc">' + stadium.stadium + '</span><br/><br/>';
         cont.innerHTML = htm;
         var inpPre = $n('input');
         inpPre.value = info.previous;
         inpPre.type = 'button';
         GEvent.addDomListener(inpPre, 'click', G.showMatchFn('previous'));
         var inpNext = $n('input', '', 'margin-left:10px;');
         inpNext.value = info.next;
         inpNext.type = 'button';
         GEvent.addDomListener(inpNext, 'click', G.showMatchFn('next'));
         $a(div, cont);
         if (curMatch > 0) {
           $a(div, inpPre);
           $('match-previous').style.display = '';
         } else {
           $('match-previous').style.display = 'none';
         }
         if (curMatch < teamSchedule.length - 1) {
           $a(div, inpNext);
           $('match-next').style.display = '';
         } else {
           $('match-next').style.display = 'none';
         }

         if (arrow != null) {
           var edit = $n('input', '', 'margin-top:5px;');
           edit.type = 'button';
           if (arrow.isEditable()){
             edit.value = info.nedit;
           } else {
             edit.value = info.edit;
           }
           GEvent.addDomListener(edit, 'click', G.editEnableFn(arrow));
           $a(div, $n('br'));
           $a(div, edit);
         }
         map.openInfoWindow(latlng, div);
       };
     },
     editEnableFn: function(arrow) {
       return function() {
         if (arrow.isEditable()) {
           arrow.disableEdit();
           this.value = info.edit;
         } else {
           arrow.enableEdit();
           this.value = info.nedit;
         }
       };
     },
     getTeamByNick: function(nick) {
       for (var i = 0; i < teams.length; ++i) {
         if (teams[i].cn == nick){
           return teams[i];
         }
       }
       return null;
     },
     changeTeam: function() {
       var team = $('teamlist').value;
       playing = false;
       $('match-play').value = info.play;
       $('control-buttons').style.display = 'none';
       map.clearOverlays();
       map.addOverlay(tip);
       stadiums = {};
       teamSchedule = G.getTeamSchedule(team);
       G.showSchedule(teamSchedule);
     },
     showSchedule: function(scs) {
       var markers = [];
       var lastStadium = null;
       var count = 0;
       for (var i = 0; i < scs.length; ++i) {
         var sc = scs[i];
         var home = sc.home;
         var sta = home;
         for (var j = 0; j < teams.length; ++j) {
           if (sc.home == teams[j].cn) {
             home = teams[j];
           }
         }
         if (!home.coor) {
           continue;
         }
         var marker = null;
         var latlng = home.coor.split(',');
         latlng = new GLatLng(latlng[1], latlng[0]);
         if (stadiums[sta]) {
           marker = stadiums[sta];
         } else {
           marker = new SMarker(latlng, '', home.stadium, tip, [50, 50], '/sports/img/team50x50/' + home.micon + '.gif');
           stadiums[sta] = marker;
           map.addOverlay(marker);
           markers.push(marker);
         }
         if (lastStadium != null && latlng.lat() != lastStadium.lat() && latlng.lng() != lastStadium.lng()) {
           //       var arrow = new _CArrow(pointFrom, pointTo, null, null, {'enableEdit': true, color: '#FF0000', opacity: 0.5});
           //       map.addOverlay(arrow);
           var arrow = new _CArrow(lastStadium, latlng, null, null, {opacity: 0.5, margin: 30, angle: 20, color: '#FF0000', editColor: '#0000FF'});
           map.addOverlay(arrow);
           GEvent.addListener(marker, 'click', G.showStadiumSchedule(arrow));
         }
         lastStadium = latlng;
       }
       G.resetMap(markers);
     },
     resetMap: function(markers) {
       if (markers.length == 1) {
         map.panTo(markers[0].getLatLng());
         return;
       }
       var bounds = new GLatLngBounds();
       for (var i = 0; i < markers.length; ++i) {
         var latlng = markers[i].getLatLng();
         bounds.extend(latlng);
       }
       map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds) - 1);
     },
     showStadiumSchedule: function(arrow) {
       return function() {
         if (arrow.isEditable()) {
           arrow.disableEdit();
         } else {
           arrow.enableEdit();
         }
       };
     }
   };

   var SToolTip = function() {};
   SToolTip.prototype.initialize = function(map) {
    this.div_ = $n('div', '', 'display:none;position:absolute;background:url(/gaokao/img/t_r.png) no-repeat right top;padding-right:18px;white-space:nowrap;z-index:11;');
    this.span_ = $n('span', '', 'display:block;background:url(/gaokao/img/t_l.png) no-repeat;padding:18px 0 18px 18px;color:#333333;font-size:1em');
    this.span_.innerHTML = 'tooltip';
    $a(this.div_, this.span_);
    $a(map.getPane(G_MAP_MARKER_PANE), this.div_);
    this.map_ = map;
  };

  SToolTip.prototype.show = function(tip, latlng) {
    this.span_.innerHTML = tip;
    this.div_.style.display = '';
    if (this.timer_) {
      clearTimeout(this.timer_);
    }
    if (this.timerD_) {
      clearTimeout(this.timerD_);
    }
    var xy = this.map_.fromLatLngToDivPixel(latlng);
    this.div_.style.left = (xy.x - 7) + 'px';
    this.div_.style.top = (xy.y + 11) + 'px';
    this.div_.style.opacity = '0';
    this.div_.style.filter = 'alpha(opacity=0)';
    this.opa_ = 0;
    this.timer_ = setTimeout(GEvent.callback(this, this.gradualAppear), 500);
    this.timerD_ = setTimeout(GEvent.callback(this, this.gradualDisappear), 5000);
  };

  SToolTip.prototype.hide = function() {
    this.div_.style.display = 'none';
    clearTimeout(this.timer_);
    clearTimeout(this.timerD_);
  };

  SToolTip.prototype.redraw = function() {

  };

  SToolTip.prototype.remove = function() {
    this.div_.parentNode.removeChild(this.div_);
  };

  SToolTip.prototype.gradualAppear = function() {
    if (this.opa_ < 1) {
      this.opa_ += 0.1;
      this.div_.style.opacity = this.opa_;
      this.div_.style.filter = 'alpha(opacity=' + parseInt(this.opa_ * 100, 10) + ')';
      this.timer_ = setTimeout(GEvent.callback(this, this.gradualAppear), 30);
    }
  };

  SToolTip.prototype.gradualDisappear = function() {
    if (this.opa_ > 0) {
      this.opa_ -= 0.1;
      this.div_.style.opacity = this.opa_;
      this.div_.style.filter = 'alpha(opacity=' + parseInt(this.opa_ * 100, 10) + ')';
      this.timerD_ = setTimeout(GEvent.callback(this, this.gradualDisappear), 30);
    }
  };

  var SMarker = function(latlng, index, title, tip, size, img) {
    this.latlng_ = latlng;
    this.index_ = index;
    this.title_ = title;
    this.tip_ = tip;
    this.clickable_ = true;
    this.size_ = size;
    this.image_ = img;
  };

  SMarker.prototype = new GOverlay();

  SMarker.prototype.initialize = function(map) {
    var div = null;
    if (this.size_) {
      div = $n('div', '', 'text-align:center;font-size:0.8em;font-weight:bold;cursor:pointer;line-height:' + this.size_[1] + 'px;width:' + this.size_[0] + 'px;height:' + this.size_[1] + 'px;color:#ffffff;background:url(' + this.image_ + ');position:absolute;');
      div.style.zIndex = 1;
    } else {
      div = $n('div', '', 'text-align:center;font-size:0.8em;font-weight:bold;cursor:pointer;line-height:23px;width:23px;height:23px;color:#ffffff;background:url(/gaokao/img/marker_b.png);position:absolute;');
      div.style.zIndex = 2;
    }
    div.innerHTML = this.index_;
    map.getPane(G_MAP_MARKER_PANE).appendChild(div);
    this.map_ = map;
    this.div_ = div;
    GEvent.addDomListener(this.div_, 'mouseover', GEvent.callback(this, this.mouseOverFn_()));
    GEvent.addDomListener(this.div_, 'mouseout', GEvent.callback(this, this.mouseOutFn_()));

    var evts = ['click', 'mouseover', 'mouseout'];
    for (var i = 0; i < evts.length; ++i) {
      GEvent.addDomListener(div, evts[i], GEvent.callback(GEvent, GEvent.trigger, this, evts[i], this.getLatLng()));
    }
  };

  SMarker.prototype.mouseOverFn_ = function() {
    return function() {
      if (!this.map_.getBounds().containsLatLng(this.latlng_)) {
//        this.map_.panTo(this.latlng_);
      }
      if (this.div_) {
        if (!this.size_) {
          this.div_.style.background = 'url(/gaokao/img/marker_r.png)';
        }
        this.div_.style.zIndex = 10;
      }
      this.tip_.show(this.title_, this.latlng_);
    };
  };

  SMarker.prototype.mouseOutFn_ = function() {
    return function() {
      if (this.div_) {
        if (!this.size_) {
          this.div_.style.background = 'url(/gaokao/img/marker_b.png)';
          this.div_.style.zIndex = 2;
        } else {
          this.div_.style.zIndex = 1;
        }
      }
      this.tip_.hide();
    };
  };

  SMarker.prototype.hide = function() {
    this.div_.style.display = 'none';
  };

  SMarker.prototype.show = function() {
    this.div_.style.display = '';
  };

  SMarker.prototype.remove = function(map) {
    this.div_.parentNode.removeChild(this.div_);
  };

  SMarker.prototype.copy = function() {

  };

  SMarker.prototype.redraw = function(force) {
    if (!force) {
      return;
    }
    var xy = this.map_.fromLatLngToDivPixel(this.latlng_);
    var dx = 12;
    var dy = 12;
    if (this.size_) {
      dx = parseInt(this.size_[0] / 2, 10);
      dy = parseInt(this.size_[1] / 2, 10);
    }
    this.div_.style.left = (xy.x - dx) + 'px';
    this.div_.style.top = (xy.y - dy) + 'px';
  };

  SMarker.prototype.getElement = function() {
    return this.div_;
  };

  SMarker.prototype.getLatLng = function() {
    return this.latlng_;
  };

   window._CanvasDemo = G || window._CanvasDemo;
 })();
