var iconURL = [];
iconURL[245] = 'speedcam.png';
iconURL[246] = iconURL[247] = 'radar.png';

function RunMap() {
  var myMapOptions = {
    mapModeName: 'drag',
    useCookie: false,
    autoSize: false,
    modArguments: {
      "modFindRoute":{"disabled":false},
      "modImpendings":{"disabled":false},
      "modZoomControl":{"visible":true,"showSlider":true,"showScale":true},
      "modSearch":{"visible":false},
      "modLinkTo":{"disabled":true, "visible":false},
      "modToolbar":{
        "visible":true,
        "modeEnable":["zoom-min","|","drag","zoom-selection","|","search-form"]
      }
    }
  };
  myMap = new TargeoMap('map-container', myMapOptions);
  connect(myMap, 'onInit', function(){
    $('map-container').style.border = 'none';
    var el = DIV({'id':'poi-by-miplo'},A({'href':'http://www.miplo.pl','target':'_blank'},DIV('')));
    appendChildNodes(myMap.elementMap, el);
  });
  Targeo.ContextMenuManager.prototype.showContextMenu = function(){};
  myMap.initialize();
  myPOIs = new MapPOIs(myMap);
  myPOIs.refresh();
}

MapPOIs = function (Map) {
  this.Map = Map;
  this.djson = new Targeo.DJSON();
  this.djson.setCallback(this.onDJSONComplete, this);
  this.POIs = {};
  this.refreshButton = $('refreshButton');
  this.requestFrom = 0;
  bindMethods(this);
  connect(this.Map, 'onInit', this, 'load');
  connect(this.Map, 'onDragEnd', this, 'load');
  connect(this.Map, 'onMoveEnd', this, 'load');
  connect(this.Map, 'onRefresh', this, 'refresh');
  connect(this.refreshButton, 'onmousedown', this, 'refresh');
};

MapPOIs.prototype = {
  clear: function () {
    for (i in this.POIs)
      this.Map.pointRemove(this.POIs[i].id);
    this.POIs = {};
  },
  refresh: function (bounds) { 
    this.clear();
    this.load(bounds);
  },
  load: function (bounds) {
    if (this.requestFrom==2) this.djson.requestAbort();
    if (isUndefinedOrNull(bounds) || isUndefinedOrNull(bounds.minX)) {
      var b = this.Map.boundsMapVisible;
      var mi = this.Map.xy2gps({x:b.minX,y:b.maxY});
      var ma = this.Map.xy2gps({x:b.maxX,y:b.minY});
      bounds = {
        minX: mi.x,
        maxX: ma.x,
        minY: mi.y,
        maxY: ma.y
      };
    }
    var params = {
      nums: 0,
      notin: '',
      t: $('t').value,
      f: $('f').checked,
      c: $('c').checked,
      zoom: this.Map.zoomCurrent
    };
    params['bounds'] = serializeJSON(bounds);
    for (var i in this.POIs) {
      if (parseFloat(this.POIs[i].coords.x)<bounds.minX || parseFloat(this.POIs[i].coords.x)>bounds.maxX || this.POIs[i].coords.y<bounds.minY || this.POIs[i].coords.y>bounds.maxY) {
        this.Map.pointRemove(this.POIs[i].id);
        delete(this.POIs[i]);
      } else {
        params['nums']++;
        if (params['notin']>'') params['notin']+= ',';
        params['notin']+= "'" + this.POIs[i].id.substr(1) + "'";
      }
    }
    this.showProgress();
    this.requestFrom = 2;
    this.djson.request('pois-load.php', params);
  },
  showPoint: function (id) {
    var params = {'p': id};
    if (this.requestFrom==3) this.djson.requestAbort();
    this.requestFrom = 3;
    this.djson.request('pois-load.php', params);
  },
  onDJSONComplete: function (json) {
    if (json.status==1) {
      for (var j in json.items) {
        var i = json.items[j];
        i.x = parseFloat(i.x);
        i.y = parseFloat(i.y);
        if (i.f>0) var photo = '<div class="photo"><a target="_blank" title="Kliknij, aby zobaczyć szczegóły punktu." href="http://www.miplo.pl/point.php?p='+i.id+'"><img src="http://f.miplo.pl/80x80/'+i.f+'.jpg" width="60" /></a></div>'; else var photo = '';
        if (i.cs>0) var comments = '<a target="_blank" title="'+i.cs+' komentarz(e/y) do punktu." href="http://www.miplo.pl/point.php?p='+i.id+'#comments"><div class="comments">'+i.cs+'</div></a>'; else var comments = '';
        this.POIs[i.id] = this.Map.pointAdd(
          'mypoint', 
          {x: i.x, y: i.y},
          {
            id: 'p'+i.id,
            icon: {imageUrl: iconURL[i.cid], coordsAnchor: {x: 8, y: 8}, dimension: {w: 37, h: 37}},
            name: i.c,
            fGetContextMenu: function(id){
              return [];
            },
            balloonParams: {
              body: photo + comments + '<h3>'+i.n+'</h3><p>'+i.d+'</p><p><i>'+i.t+'</i></p><p><a href="http://www.miplo.pl/point.php?p='+i.id+'" target="_blank">Szczegóły punktu w Miplo.pl</p>',
              size: {width: 300, height: 200},
              icon: i.s>0 ? i.s+'.png' : undefined
            },
            modSpecific: {FindRoute: {revgeo: 0}}
          }
        );
        connect(this.POIs[i.id], 'onMouseDown', this, 'zoomPoint');
      }
    }
    if (json.status==2)
      this.Map.zoomAndCenter({x: json.coords.x, y: json.coords.y}, 0);
    this.hideProgress();
  },
  zoomPoint: function (id) {
    var i = this.POIs[id.substr(1)];
    this.Map.zoomAndCenter({x: i.coords.x, y: i.coords.y}, 0);
  },
  showProgress: function () {
    this.hideProgress();
    progressBar = DIV({'id':'progressBar'}, 'null');
    appendChildNodes(this.Map.elementMap, progressBar);
    showElement(progressBar);
  },
  hideProgress: function () {
    if ($('progressBar')) removeElement($('progressBar'));
  }
};