﻿// JScript File

StopStyle =  function(icon1Url,icon2Url,icon3Url,iconSize,iconAnchor,labelClass,labelOffset){
    this.bluredIcon  = icon1Url;
    this.focusedIcon = icon2Url;
    this.clickedIcon = icon3Url;
    this.iconSize =    iconSize   || new GSize(18,18);
    this.labelClass =  labelClass || "markerLabel";
    this.labelOffset = labelOffset || new GSize(0, 0);
    this.iconAnchor =  iconAnchor || new GPoint(this.iconSize.width/2,this.iconSize.height/2);
}


//var PATH = '';
//domyślne style
var STOPSTYLE1 = new StopStyle('img/bus.png','img/bus_shine.png','');
var STOPSTYLE2 = new StopStyle('img/mm_20_blue.png',
                               'img/mm_20_blue_shine.png',"",
                               new GSize(18,24),new GPoint(6,20));
var STOPSTYLE3 = new StopStyle('http://www.google.com/intl/en_ALL/mapfiles/dd-start.png',
                               'http://www.google.com/intl/en_ALL/mapfiles/dd-start.png',"",
                               new GSize(12,20),new GPoint(6,20));
var STOPSTYLE4 = new StopStyle('http://www.google.com/intl/en_ALL/mapfiles/dd-end.png',
                               'http://www.google.com/intl/en_ALL/mapfiles/dd-stop.png',"",
                               new GSize(12,20),new GPoint(6,20));



Stop = function(latlng, opt_opts)
{
  this.latlng_ = latlng;
  this.opts_ = opt_opts;


  this.labelText_       = opt_opts.labelText     || "";
  this.count_           = opt_opts.count         || 1;
  this.id_              = opt_opts.id            || 0;
  this.nr_              = opt_opts.nr            || 0;
  this.nrs_             = opt_opts.nrs           || 0;
  this.consistRoute_    = opt_opts.consistRoute  || false;
  this.style_           = opt_opts.stopStyle     || STOPSTYLE1;
  this.opts_.icon       = this._createIcon();
  this._arrOfRoutes     = new Array();  //zawiera informacje o liniach jakie przejeżdżają przez dany przystanek
  this.listeners        = [""];
  
  this.clickable_       = opt_opts.clickable     || true;
  this.title_           = opt_opts.title         || "";
  this.hasLabel_        = opt_opts.hasLabel      || false;
  this.hasFlashLabel_   = opt_opts.hasFlashLabel || false;
  this.labelVisibility_ = false;
  this.IsOnMap          = false;//public
  
  var me  = this;
  var clicable  = false;
  this.flashLabel_ = new FlashLabel(this.latlng_,{offset:new GSize(-18,-18)});
 
  
  GMarker.apply(this, arguments);
}

Stop.selected = null; //zmienna globalna, aktualnie kliknięty przystanek
Stop.prototype = new GMarker(new GLatLng(0, 0));
Stop.prototype.onclick_ = function(){this._openInfoWindow();};

Stop.prototype.onclose = function(){};
Stop.prototype.setBlurStyle_ = function(){this.setImage(this.style_.bluredIcon);};
Stop.prototype.setFocusStyle_ = function(){this.setImage(this.style_.focusedIcon);};




Stop.prototype.initialize = function(map) {
  // Do the GMarker constructor first.
  
  
  GMarker.prototype.initialize.apply(this, arguments);
  
  this.map_ = map;
  this.IsOnMap = true;
  
 
  if(this.hasLabel_){
      this.div_ = document.createElement("div");
    //  this.div_.className = this.labelClass_;
      this.div_.className = this.style_.labelClass;
      this.div_.innerHTML = this.labelText_;
      this.div_.style.position = "absolute";
      this.div_.style.cursor = "pointer";
      this.div_.style.visibility = 'hidden';
      this.div_.title = this.title_;
      map.getPane(G_MAP_MARKER_PANE).appendChild(this.div_);
  }
  
  if(this.hasFlashLabel_)  
    this.flashLabel_.initialize(map);
   
}

Stop.prototype.redraw = function(force) {
  GMarker.prototype.redraw.apply(this, arguments);
  
  if(this.hasLabel_)
     this._redrawLabel();

 if(this.hasFlashLabel_)
     this.flashLabel_.redraw();
  

};

Stop.prototype._redrawLabel = function()
{
      var p = this.map_.fromLatLngToDivPixel(this.latlng_);
      var z = GOverlay.getZIndex(this.latlng_.lat());
      
    
      this.div_.style.left = (p.x + this.style_.labelOffset.width) + "px";
      this.div_.style.top = (p.y + this.style_.labelOffset.height) + "px";
      this.div_.style.zIndex = z;  
    
}


Stop.prototype.setLatLng = function(latlng) {
  this.latlng_ = latlng;
  GMarker.prototype.setLatLng.apply(this, arguments);
   if(this.hasLabel_)
         this._redrawLabel();
         
   if(this.hasFlashLabel)
        this.flashLabel_.redraw();

};

Stop.prototype.setRouteInfo = function(routeInfo)
{
    this._arrOfRoutes = routeInfo;
}
Stop.prototype.getRouteInfo = function()
{
    return this._arrOfRoutes;
}

Stop.prototype.getRouteNumbers = function()
{
   var result = new Array();
   for (var i=0;i<this._arrOfRoutes.length;++i)
        result.push(this._arrOfRoutes[i].split(',')[0]);
   return result.RemoveDuplicatesStr();      
}


Stop.prototype.remove = function() {
//this.disableDragging();

 //this.closeInfowWindow(); //zamknij indoWindow przed usunięciem markera
 
 if(this.hasLabel_){
      this.div_.innerHTML ="";
      
      if (this.div_.outerHTML) {
        this.div_.outerHTML = ""; //prevent pseudo-leak in IE
      }
      if (this.div_.parentNode) {
        this.div_.parentNode.removeChild(this.div_);
      }
      this.div_ = null;
  }
  
  if(this.hasFlashLabel_)
    this.flashLabel_.remove();
  
  this.IsOnMap = false;
  
  /*_arrOfRoutes = null;
   this.style_=null;
   this.opts_.icon = null;
   this.labelText_ = null;
   this.map_=null;
 */ 
  //GEvent.clearListeners(this,"infowindowclose");
  //GEvent.clearListeners(this,"dragend");  
 // GEvent.clearListeners(this,"click");  
  
  //this.onclick_ = null;
  
  //GEvent.clearInstanceListeners(this);
 // GEvent.clearListeners(this,"infowindowclose"); //dziwny problem w FF, to zdarzenie musi być wcześniej usunięte
 
  GMarker.prototype.remove.apply(this, arguments);
};

Stop.prototype.initListeners = function(){//domyślne zdarzenia
  var me = this;
//  GEvent.bind(this,"dragend",this,function(latlng){me.stopDragened(latlng);});
  //GEvent.bind(this,"infowindowclose",this,function(){me.setBlurStyle_();});
  GEvent.bind(this,"click",this,function(){if(Stop.selected && Stop.selected.IsOnMap) Stop.selected.setBlurStyle_(); Stop.selected = me;me.setFocusStyle_();me.onclick_();});


  if(this.hasFlashLabel_){
   
   
    GEvent.addListener(this,"mouseover",function(){me.flashLabel_.show();});
    GEvent.addListener(this,"mouseout",function(){me.flashLabel_.hide();});
    
    
    //dodanie dodatkowego zdarzenia
    GEvent.addListener(this.flashLabel_,"click",function(latlng){
    
        if(me.clusterGroupBounds!=null){ //jeśli to przystanek sklastrowany
            var bounds = me.clusterGroupBounds;
            me.map_.setCenter(me.map_.setCenter(bounds.getCenter(),me.map_.getBoundsZoomLevel(bounds)));
       }
        else{//dla pojedynczego prystanku centrujemy mapę
            me.map_.setCenter(me.latlng_);
            me.map_.zoomIn();me.map_.zoomIn();
    }
});  
  }
}

Stop.prototype.clearListeners = function(){
    GEvent.clearInstanceListeners(this);
}


Stop.prototype.hideLabel = function() {
 if(this.hasLabel_ && this.div_!=null)
  this.div_.style.visibility = 'hidden';
};

Stop.prototype.showLabel = function() {
 if(this.hasLabel_ && this.div_!=null)
  this.div_.style.visibility = 'visible';
};

Stop.prototype.show = function()
{
  GMarker.prototype.show.apply(this, arguments);
  if (this.labelVisibility_) {
    this.showLabel();
  } else {
    this.hideLabel();
  }
}
Stop.prototype.hide = function()
{
  GMarker.prototype.hide.apply(this, arguments);
  this.hideLabel();
}



Stop.prototype._createIcon = function()
{       
       var icon = new GIcon();  
       icon.image = this.style_.bluredIcon;  
       
       //this.iconSize_=this.iconSize_;//Stop.prototype._aproxSize(this.count_):this.iconSize_;
       icon.iconSize=this.style_.iconSize;
       icon.iconAnchor = this.style_.iconAnchor;  
 
       icon.infoWindowAnchor = new GPoint(this.style_.iconSize.width/2,this.style_.iconSize.height/2);  
       icon.shadow = "";
       return icon;
}
Stop.prototype.setStyle = function(style){
       this.style_ = style || STOPSTYLE1;
       var icon = this.getIcon();
       icon.image = this.style_.bluredIcon;  
       //this.setImage(icon.image);
       
       icon.iconSize=this.style_.iconSize;
       icon.iconAnchor = this.style_.iconAnchor;  
       icon.infoWindowAnchor = new GPoint(this.style_.iconSize.width/2,this.style_.iconSize.height/2);  
       icon.shadow = "";
      
       icon =null;
}
Stop.prototype.getStyle = function(){
       return this.style_;
}


Stop.prototype.getId = function()
{
    return this.id_;
}


Stop.prototype.setLabelOffset = function (offset)
{
     this.labelOffset_ = offset || new GSize(0, 0);
};

Stop.prototype.setLabelText = function (text)
{
    this.labelText_ = text;
};
/*
Stop.prototype._openInfoWindow = function()
{

    var bufHeader=new StringBuffer();
    bufHeader.append(' <table class=\'infoWindow\' width="250"><tr ><td>'
                      + this.getTitle() +'<br/><span style=\'color:blue;font-size:8pt\'>Ilosc przystankow:<b>' 
                      + TaStops.currentStopsNodeGroup.length +'</b></span></td><td style=\'text-align:right\' id=\'link\'></td></tr></table>');
    return bufHeader.toString();
}
*/

//!!!!!!!!


Stop.prototype._clustreInfoRoutes=function(stops){//klastruje informacje o liniach
var cRouteInfo = new Array();   
 for (var i=0;i<stops.length;++i)
   {
     for (var j=0;j<stops[i].getRouteInfo().length;++j)
     {
        var tmp = stops[i].getRouteInfo()[j];
        cRouteInfo.push(tmp);
     }
   }
 this._arrOfRoutes = cRouteInfo.RemoveDuplicatesStr();
}


Stop.prototype._infoWindowHeaderHTML = function()//nagłówek
{
     var bufHeader=new StringBuffer();
     bufHeader.append('<table class=\'infoWindow\' width="250"><tr><td>' + this.getTitle()  + '<br/><span style=\'color:blue;font-size:8pt\'>');
     if(this.count_>1)
        bufHeader.append(Global.lang.iloscPrz + ':<b>'+ this.count_ +'</b></span>');
     else{
        bufHeader.append('Numer: <b>'+ this.nr_ +'</b>&nbsp;&nbsp;&nbsp;' + Global.lang.numerSlupk + ': <b>' + this.nrs_ + '</b></span>');
     }
     bufHeader.append('</td></tr></table>');
//  + this.count_ +'</b></span></td><td style=\'text-align:right\' id=\'link\'></td></tr></table>');
    return bufHeader.toString();



}


Stop.prototype._infoWindowRoutesHTML = function(routeArray,maximize)//numery lini
{
    var bufBody  =new StringBuffer();
    var arrayOfRouteNumbers = routeArray || this.getRouteNumbers();
    var w ='250';var f = 'onmouseover=\'javascript:Stop._showTracksInfo';
      
    if(maximize){
        w='100%';
        f='onclick=\'javascript:virtualT.choseRoute';
    } 
    bufBody.append('<div id="routesDiv"><table width="'+w+'"><tr><td style=\'color:red;\'>' + Global.lang.linie +':</td></tr><tr><td><ul class=\'infoWindow\' style=\'border:0px\'>');
   
    for (var i =0;i<arrayOfRouteNumbers.length;++i)
        bufBody.append('<li><a '+f+'("'+arrayOfRouteNumbers[i]+
                    '")\' class=\'routeIw\'>'+arrayOfRouteNumbers[i]+'</a><ul id="'+arrayOfRouteNumbers[i]+'" ></ul></li>');
   
    bufBody.append('</ul></td></tr></table></div>');
    return bufBody.toString();
}

    


Stop.prototype._infoWindowMaxDIV= function(headerHTML,bodyHTML)//zmaksymilizowana chmurka
{

      var maxContentDiv = document.createElement('div');
      maxContentDiv.style.width='95%';
      var buf = new StringBuffer();
     
   
      //nagłówek
      var maxheaderHTML = headerHTML.replace('width="250"','width="100%"');//.replace(".maximize()\">Najblizsze odjazdy>>",".restore()\">Zwin<<");
    
      buf.append(maxheaderHTML);
      buf.append("<table style=\'width:100%\'><tr><td style=\'text-align:left;vertical-align:top\'>")
      buf.append(bodyHTML);
      buf.append('</td></tr></table>');
      maxContentDiv.innerHTML = buf.toString();
        
      respDiv =   document.createElement('div');    
      respDiv.setAttribute('id','respDiv');
      //respDiv.style.height='200px';
      //respDiv.style.overflow='scroll';
      maxContentDiv.appendChild(respDiv); 
     
      return  maxContentDiv;
}


Stop.prototype._openInfoWindow = function()
{     var bodyHTML =  this._infoWindowRoutesHTML([]); 
      var headerHTML = this._infoWindowHeaderHTML();
      var footHTML = "";
      var minContent = "";
      var maxContent ="";
      var me = this;

      if(this.count_ == 1){//jeśli to nie klaster tylko pojedynczy przystanek
        footHTML = "<div style='border-top:1px solid blue'><a href ='javascript:TaStops.cluster.zoomOut()' class=\'nav\'>" + Global.lang.zoomOut + "</a></div>";
        maxContent = this._infoWindowMaxDIV(headerHTML,bodyHTML);
        
        this.openExtInfoWindow(
            this.map_,
            "ex_info_window",
            maxContent.innerHTML,
            {beakOffset: 3
            }
        );
        virtualT = new VirtualTable(this.getId(),document.getElementById("respDiv"),{menu:true,days:true,enableVehicles:true});
        virtualT.beginLoad = function(){
        }
        virtualT.viewLoaded = function(b){
         if(me.map_.getExtInfoWindow()!=null){
            me.map_.getExtInfoWindow().resize();
         }
        }
        //w przypadku wyświetlania rozkładu jazdu, wyświetl tylko linie znajdujące się na rozkładzie (a nie wszystkie zatrzymujące się na przystanku)
        virtualT.dataLoaded = function(b){
         if(me.map_.getExtInfoWindow()!=null){
            document.getElementById('routesDiv').innerHTML=me._infoWindowRoutesHTML(this.arrayOfRoutes,true);
         }
        }
        virtualT.setStaticOne();
      }
      else{
      
       footHTML = "<div style='border-top:1px solid blue'><a href ='javascript:TaStops.cluster.zoomIn()' class=\'nav\'>" + Global.lang.zoomIn + "</a></div>";
       bodyHTML = this._infoWindowRoutesHTML();
       minContent = headerHTML + bodyHTML + footHTML;
        this.openExtInfoWindow(
            this.map_,
            "ex_info_window_mini",
            minContent,
            {beakOffset: 3}
        );
      
      
      }
    // this.openInfoWindowHtml(maxContent.innerHTML,{noCloseOnClick:true});    
      //pobranie odjazdów przy zdarzeniu maksym... wynik zostanie zapisany w respDiv, nie ma var więc jest to zmienna globalna!
   
      
 }

/***************************************************************************************************************/
/* Menu kontekstowe w chmurce
/***************************************************************************************************************/

Stop._showTracksInfo = function (routeNr)
{
     var buffer = new StringBuffer();
    
     var arrayOfTracks=Stop.selected._findTracks(routeNr);
     
     var eventclick='';
     if(arrayOfTracks.length == 0) return "";
     
     buffer.append('<table class=\'owal_box\'>'
                   +'<tr><td class=\'left_top\'></td><td class=\'middle\'></td><td class=\'right_top\'></td></tr>'
                   +'<tr><td class=\'left\'></td><td class=\'content\'>');
     
     for (var k=0;k<arrayOfTracks.length;++k)
     {
       eventclick = '"javascript:stops.drawRoute(\'' + routeNr +'\',\'' + arrayOfTracks[k][2]/*warriant trasy*/ + '\',\'' + arrayOfTracks[k][1]/*kierunek*/ + '\')"';
       buffer.append('<li><a href=' + eventclick + ' class=\'nav\'>' + arrayOfTracks[k][0] + '</a></li>');
     }             
  
    buffer.append('</td><td class=\'right\'></td></tr><tr><td class=\'left_bottom\'>'
                   +'</td><td class=\'middle\'><td class=\'right_bottom\'></td></tr></table>');
     
   document.getElementById(routeNr).innerHTML=(buffer.toString());
 return buffer.toString();
}

Stop.prototype._findTracks=function(nr)
{
    var arrOfTracks = new Array();
    var xml = TaStops.xmlRoutesInfo;
    var r = xml.getElementsByTagName('Route');
    var b = new Array();
    for(var i =0;i<this.getRouteInfo().length;++i)//podczas ładowania mapy każdy przystanek otrzymał w tablicy stringów informacje o liniach i wariantach tras
        b.push(this.getRouteInfo()[i].split(','));//należly te wartości porównać z wartościami zawartymi w pliku RoutesInfo.xml aby otrzymać linie przejezdzające przez dany przystanek
    var route = findNode(r,"nr",nr);
    //czasem informacji o lini może nie być w pliku
    if(route ==null || !route.hasChildNodes()) return [];
    
    for(var k =0;k<route.childNodes.length;++k)
   {
       if(route.childNodes[k].nodeType!=1) continue;//pomijamy białe znaki i inne rzeczy które nie są znacznikami XML
       for(var j=0;j<b.length;++j){
         if(route.childNodes[k].getAttribute("type")==b[j][2] &&route.childNodes[k].getAttribute("dir")==b[j][1]) {
            arrOfTracks.push([route.childNodes[k].getAttribute("desc1") +" - " + route.childNodes[k].getAttribute("desc"),b[j][1],b[j][2]]);
         break;
         }
       }
   }
   return arrOfTracks.RemoveDuplicates();
}

/*************************************************************************************/
/*************************************************************************************/
//Definicja etykiety służącej do centrowania mapy po najechaniu na przystanek
FlashLabel = function(latlng, opt_opts)
{
    this.latlng_ = latlng              || new GLatLng(0,0);
    this.opt_opts_ = opt_opts           || {};
    this.visible_ = opt_opts.visible    || false;
    this.text_ = opt_opts.text          || "+";
    this.cssClass_=opt_opts.cssClass    ||"markerZoomLabel";
    this.listeners         =            [];
    this.timeOut_ = opt_opts.timeout    || 200;
    this.offset_ = opt_opts.offset      || new GSize(0,0);
    this.timerId_=null;
    this.mapPane_         = opt_opts.mapPane       || G_MAP_MARKER_PANE;
 
}



FlashLabel.prototype.initialize = function(map) {
  
      this.map_ = map;
      this.div_ = document.createElement("div");
      this.div_.className = this.cssClass_;
      this.div_.innerHTML = this.text_;
      this.div_.style.position = "absolute";
      this.div_.style.cursor = "pointer";
      this.div_.style.visibility = 'hidden';
      map.getPane(this.mapPane_).appendChild(this.div_);
      
    //utworzenie podstawowych zdarzeń
      this.initListeners();
   
      
  }   

FlashLabel.prototype.setText = function(text)
{
    this.div_.innerHTML = this.text_ = text;
}
FlashLabel.prototype.getText = function(text)
{
    return  this.text_ ;
}


FlashLabel.prototype.setLatLng = function(latlng)
{
    this.latlng_=latlng;
    this.redraw();
}


FlashLabel.prototype.redraw = function()
{
      var p = this.map_.fromLatLngToDivPixel(this.latlng_);
      var z = GOverlay.getZIndex(this.latlng_.lat());
      
      // Pozycja diva
      this.div_.style.left = (p.x + this.offset_.width) + "px";
      this.div_.style.top = (p.y + this.offset_.height) + "px";
      this.div_.style.zIndex = z; // in front of the marker 
}
FlashLabel.prototype.remove = function() {
 
      this.div_.innerHTML ="";
      
      if (this.div_.outerHTML) {
        this.div_.outerHTML = ""; // pseudo-leak w IE
      }
      if (this.div_.parentNode) {
        this.div_.parentNode.removeChild(this.div_);
      }
      this.div_ = null;
      this.clearListeners();
  
 };


FlashLabel.prototype.initListeners = function(){
     var me = this;
   
     function newEventPassthru(obj, event) {
      return function() { 
        GEvent.trigger(obj, event);
      };
    }
  
    var eventPassthrus = ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout'];
    for(var i = 0; i < eventPassthrus.length; i++) {
      var name = eventPassthrus[i];
      GEvent.addDomListener(this.div_, name, newEventPassthru(this, name));
    }
     
   GEvent.addListener(this, "mouseover", function(){me.show();});
   GEvent.addListener(this, "mouseout", function(){me.hide();});
}

FlashLabel.prototype.show = function(){
    clearTimeout(this.timerId_);
     
    if(!this.visible_){
        this.div_.style.visibility = 'visible';
        this.visible_=true;
    }
}

FlashLabel.prototype.hide = function(){
    if(this.visible_){
        var me = this;
        me.timerId_=setTimeout(function(){me.hidedelay_()},me.timeOut_);
    }
}

FlashLabel.prototype.hidedelay_ = function(){
        this.div_.style.visibility = 'hidden';
        this.visible_=false;
 }


FlashLabel.prototype.clearListeners = function(){
    GEvent.clearInstanceListeners(this);
}
