﻿// JScript File

// Vehicle Manager zarządzanie wszystkimi pojazdami - usówanie starych i dodawanie nowych
var PATH='';//zmienna nadpisywana
var REFRESH_TIME  = 20000;//czas odświeżania co 20s 

VehicleManager = function(map,opt_opts)
{
    this._arrOfVehicles   = new Array();
    this._arrOfTracks     = new Array();
    this._arrOfTimers     = new Array(); 
    this._visibleVehicles = new Array();
 
    this._map             = map;
    this._opts            = opt_opts || {};
    this._strInfoResp     = opt_opts.strInfoResp|| "tbVehicles" //"second_tab";
    
    this._vInfoIcon       = opt_opts.infoImgSrc || [PATH + "img/circ1.png",PATH + "img/circ2.png"]; //ikonka pojazdu w prawym menu
    this._vInfoClass      = opt_opts.infoClass  || "vehicleInfoBus"; //styl pojazdu w prawym menu
    
    this._xmlData         = null; //dane pobrane z DB
    this._timerForAll     = null; //odświeżanie wszystkich pojazdów
    this._timerForFew     = null;//odświeżanie częścipojazdów
    this._isVisible       = false;
    this._showCnrInfo     = opt_opts.showCnrInfo || false;
    
    this._style           = this._opts.vehicleStyle ||  new VehicleStyle();//domyślny styl dla pojazdów
  
    var _me = this;
    
    //czy wyświetlane mają być labele
    this._isNbLabels =  this._opts.isNbLabels  || false;
    this._isNrLabels =  this._opts.isNrLabels  || false;
    this._isDmLabels =  this._opts.isDmLabels  || false;
    this._isVarLabels = this._opts.isVarLabels || false;
    this._isKrLabels =  this._opts.isKrLabels  || false;
    
 
      this.Filter = {
                    routeNr : [],
                    zajNr : [],
                    kursowki:[],
                    stopId : '',
                    state : '',
                    variance : '',
                    nb       : '',
                    types    :'',
                    trackT:''
                  }
                  
    this._vehPosType = opt_opts.vehPosType!=null?opt_opts.vehPosType :1; //0- na podst gps, 1 - na podst trasy, 2-hybryda
                        
    this._wbs1 = null; //WebServiceClient                  
    this._wbs2 = null; //WebServiceClient                  
    GEvent.bind(this,"vehicleLoaded",this,function(veh){});
 }
//manager tras ->wczytuje,usuwa odpowiednie trasy
VehicleManager.routeManager =  new RouteDirectionManager();
 
 
VehicleManager.prototype.indexOfVehicle = function(strRoute,strTrack){
    for(var i =0;i<this._arrOfVehicles.length;++i){
        if(this._arrOfVehicles[i].CnrInfo.routeNr == strRoute && this._arrOfVehicles[i].CnrInfo.trackT == strTrack)
            return i;
    }
    return -1;
}

VehicleManager.prototype._addNewVehicle = function(id, nb, vehtype, cnrInfo, time) {
    var me = this;
    var p = this._map.getCenter();

    if (!me._isVisible) return;     // WAŻNE!! 
    
    //pobranie parametrów pojazdu z pliku konfiguracyjnego
    var vc = Global.VT.get(vehtype);
    var veh = new Vehicle(p, { 
        vehicleType: vc,
        vehicleStyle: new VehicleStyle(vc.vehIcon,vc.vehShineIcon,vc.vehArrows,null,null,null,null,null,vc.labelColor),
        nb: nb,
        ctrLabelColor: true,
        cnrInfo: cnrInfo,
        showCnrInfo: this._showCnrInfo,
        id: id,
        isNbLabel: this._isNbLabels,
        isNrLabel: this._isNrLabels,
        isDmLabel: this._isDmLabels,
        isVarLabel: this._isVarLabels,
        isKrLabel: this._isKrLabels
    });

    switch (this._vehPosType) {
        case 0:
            veh.updatePosition = veh.updatePosition_0;
            break;
        case 1:
            veh.updatePosition = veh.updatePosition_1;
            break;
        default:
            veh.updatePosition = veh.updatePosition_2;
            break;
    }


    me._arrOfVehicles.push(veh);
    me._arrOfTracks[id].index = me._arrOfVehicles.length - 1;

    //dodawanie do mapy następuje po wczytaniu trasy                                   
    if (veh.CnrInfo.trackT == null || veh.CnrInfo.routeNr == null) return;


    var ev = GEvent.addListener(veh, "load", function(route, fromCache) {
            veh._routeDirection = route;
            if(!fromCache){//jeśli to nowo wczytana trasa to ukrycie,w przeciwnym wypadku pozostaw bez zmian
                route.isStopsDrawed = false;
                route.isPolylineDrawed = false;
            }
            TaStops.map.addOverlay(veh);
            me.vehLoaded(veh);
            veh.updatePosition();
            GEvent.removeListener(ev);
    });
     VehicleManager.routeManager.loadRouteInNModeForVeh(veh);
   
    //},time);
}

VehicleManager.prototype.vehLoaded = function(veh){}

VehicleManager.prototype._removeVehicle = function(id) {
    if (this._arrOfTracks[id] == null) return;
    var idx = this._arrOfTracks[id].index;

    var vehToDel = this._arrOfVehicles[idx];

    window.clearTimeout(this._arrOfTimers[idx]); //upewnienie się że zakończono upgrade pozycji przed usunięciem pojazdu
    this._map.removeOverlay(this._arrOfVehicles[idx]);
    this._arrOfVehicles.splice(idx, 1); //usunięcie z tablicy

    //przeindeksowanie
    for (var i = idx; i < this._arrOfVehicles.length; ++i)
        this._arrOfTracks[this._arrOfVehicles[i]._id].index = i;

    this._arrOfTracks[id] = null;

    //po usunięciu pojazdu sprawdz czy trasa do której należy używana jest przez inny pojazd, jeśli nie to usuń trasę z mapy
    if (this.indexOfVehicle(vehToDel.CnrInfo.routeNr, vehToDel.CnrInfo.trackT) == -1) {
        VehicleManager.routeManager.hideRoute(vehToDel.CnrInfo.routeNr, vehToDel.CnrInfo.trackT);
    }

}

VehicleManager.prototype._findFirstEmpty = function()
{
    for(var i=0;i<this._arrOfVehicles.length;++i)
        if(this._arrOfVehicles[i] == null) return i;
    return this._arrOfVehicles.length;
}

VehicleManager.prototype._updateVehicle = function(id,cnrInfo,time)
{
    if(this._arrOfTracks[id] != null){
      if(this._arrOfTimers[this._arrOfTracks[id].index]!=null) 
        window.clearTimeout(this._arrOfTimers[this._arrOfTracks[id].index]); //upewnienie się że poprzednia aktualizacja pozycji się zakończyła
        var _me=this;
        this._arrOfTimers[_me._arrOfTracks[id].index]=window.setTimeout(function(){
            
            if(!_me._isVisible) return;     // WAŻNE!! 
            if(_me._arrOfTracks[id]!=null)
                _me._arrOfVehicles[_me._arrOfTracks[id].index].update(cnrInfo)
            ;}
      ,time); 
    }
}

VehicleManager.prototype._removeNoExist = function() {

    for (var i = 0; i < this._arrOfTracks.length; ++i)
        if (this._arrOfTracks[i] != null && this._arrOfTracks[i].updated == false) {
        window.clearTimeout(this._arrOfTimers[this._arrOfTracks[i].index]); //upewnienie się że zakończono upgrade pozycji przed usunięciem pojazdu
        this._removeVehicle(i);
    }
}

VehicleManager.prototype.centreMap2All = function() {
    if (this._arrOfVehicles.length > 0) {
        var bound = new GLatLngBounds();
        for (var i = 0; i < this._arrOfVehicles.length; ++i)
            bound.extend(this._arrOfVehicles[i].getPoint());
        this._map.setCenter(bound.getCenter(), this._map.getBoundsZoomLevel(bound));
    }

}
VehicleManager.prototype.centreMap2Selected = function(){
    if(Vehicle.selected != null)
        Vehicle.selected.centreMap();
}
VehicleManager.prototype.centreMap2Track = function(){
    if(Vehicle.selected != null && Vehicle.selected._routeDirection!=null)
        Vehicle.selected._routeDirection.centreMap();
}



VehicleManager.prototype.startRefreshing2 = function(routes)
{
    var _me = this;
    if (this._timerForAll!=null) window.clearInterval(this._timerForAll);
    
    this._timerForAll=window.setInterval(function(){_me.asyncRefresh()},REFRESH_TIME);
    this.getInfo();
}
 
VehicleManager.prototype.asyncRefresh= function(routes){
        this.getVehicles();
        this.getInfo();
}

VehicleManager.prototype.syncRefresh = function(showLoader){
    var me = this;
    this.getInfo(showLoader,function(data){
        me.getVehicles();
    });
}


VehicleManager.prototype.getVehicles = function(imediate)//refresh z filtrowaniem
{

    //odświeżenie pojazdów
    if (this._wbs2) this._wbs2.abort();

    this._wbs2 = new WebServiceClient("CNR_DajPojazdy");
  //  if (this._visibleVehicles.length > 0) {
        this._wbs2.appendProperty("routes", this._visibleVehicles.join(','));
        this._wbs2.appendProperty("nr_lini", this.Filter.routeNr);
        this._wbs2.appendProperty("nr_zaj", this.Filter.zajNr);
        this._wbs2.appendProperty("id_prz", this.Filter.stopId);
        this._wbs2.appendProperty("stan", this.Filter.state);
        this._wbs2.appendProperty("odch", this.Filter.variance);
        this._wbs2.appendProperty("nb", this.Filter.nb);
        this._wbs2.appendProperty("typy", this.Filter.types);
        this._wbs2.appendProperty("war_trasy", this.Filter.trackT);


    //}
//    else { this.clearVehicles(); return };


    var me = this;
    for (var i = 0; i < this._arrOfTracks.length; ++i)
        if (this._arrOfTracks[i] != null)
        this._arrOfTracks[i].updated = false;

    this._isVisible = true;

    this._wbs2.send(function(xmlDoc) {
        if (!me._isVisible) return;     // WAŻNE!! 

        var vehicles = xmlDoc.getElementsByTagName("V");
        for (var i = 0; i < vehicles.length; ++i) {
            var v = vehicles[i];
            var id = parseInt(v.getAttribute("id"));
            var nb = v.getAttribute("nb");
            var vehtype = v.getAttribute("t"); //ten parametr narazie nie jest wykorzystywany
            var cnrInfo = {
                varStr: v.getAttribute("todch"),
                varInt: parseInt(v.getAttribute("sodch")),
                dmCode: parseInt(v.getAttribute("ka")),
                id: id,
                routeNr: v.getAttribute("nr"),
                routeCol: v.getAttribute("rcol"),
                trackT: v.getAttribute("track"),
                idp: parseInt(v.getAttribute("idp1")),
                idp2: parseInt(v.getAttribute("idp2")),
                lat: parseFloat(v.getAttribute("py")),
                lng: parseFloat(v.getAttribute("px")),
                dw: parseFloat(v.getAttribute("dw")),
                dp: parseFloat(v.getAttribute("dp")),
                dwsp: parseFloat(v.getAttribute("dwsp")),
                nrKr: v.getAttribute("nr_kur")
            }
            if (me._arrOfTracks[id] == null) {//jeśli tego pojzadu nie ma na mapie to dodaj nowy
    
                var time = (i / vehicles.length) * 100; ///określ losowy czas, by aktualizaja nastąpiła niesynchronicznie
                me._arrOfTracks[id] = { index: 0, updated: true }; //potwiedz dodanie nowego pojazdu
                me._addNewVehicle(id, nb, vehtype, cnrInfo, time);
            }
            else {
    
                var time = Math.random() * REFRESH_TIME;
                me._arrOfTracks[id].updated = true;
                me._updateVehicle(id, cnrInfo, time);
            }
        }
       
        
        me._removeNoExist();
    });
}
VehicleManager.prototype.showNrLabels = function()
{
    this._isNrLabels = true;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].showNrLabel();
}
VehicleManager.prototype.hideNrLabels = function()
{
    this._isNrLabels = false;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].hideNrLabel();
}
VehicleManager.prototype.showNbLabels = function()
{
    this._isNbLabels = true;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].showNbLabel();
}
VehicleManager.prototype.hideNbLabels = function()
{
    this._isNbLabels = false;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].hideNbLabel();
}
VehicleManager.prototype.showDmLabels = function()
{
    this._isDmLabels = true;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].showDmLabel();
}
VehicleManager.prototype.hideDmLabels = function()
{
    this._isDmLabels = false;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].hideDmLabel();
}


VehicleManager.prototype.showKrLabels = function()
{
    this._isKrLabels = true;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].showKrLabel();
}
VehicleManager.prototype.hideKrLabels = function()
{
    this._isKrLabels = false;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].hideKrLabel();
}



VehicleManager.prototype.showVarLabels = function()
{
    this._isVarLabels = true;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].showVarLabel();
}
VehicleManager.prototype.hideVarLabels = function()
{
    this._isVarLabels = false;
    for(var i =0; i<this._arrOfVehicles.length;++i)
        this._arrOfVehicles[i].hideVarLabel();
}

VehicleManager.prototype.setFilter = function(routeNr,zajNr,kursowki,stopId,state,variance,nb,typy,trackType){
    //odchylenie podawane jest w minutach->konwersja na sekundy
    var t = typy || this.Filter.types;//stare typy
    this.Filter={   routeNr : routeNr,
                    zajNr : zajNr,
                    kursowki:kursowki,
                    stopId : stopId,
                    state : state,
                    variance : variance,
                    nb : nb,
                    types :t,
                    trackT:trackType
                }
    this.syncRefresh();               
}
VehicleManager.prototype.clearFilter = function(){
    //odchylenie podawane jest w minutach->konwersja na sekundy
    this.Filter={   routeNr : '',
                    zajNr : '',
                    kursowki:'',
                    stopId : '',
                    state : '',
                    variance : '',
                    nb : '',
                    types :'',
                    trackT:''
                }
    this.syncRefresh();               
}



VehicleManager.prototype.setTypes = function(types){
   // alert(types);
    this.Filter.types = types;
    this.syncRefresh(true);   
}


VehicleManager.prototype.clear = function()
{
    if (this._timerForAll!=null) window.clearInterval(this._timerForAll);
    this.clearVehicles();
}

VehicleManager.prototype.clearVehicles = function()
{
    this._isVisible = false;
    
    for(var i =0;i<this._arrOfVehicles.length;++i)
    if(this._arrOfVehicles[i]!=null){
        window.clearTimeout(this._arrOfTimers[i]);
        this._map.removeOverlay(this._arrOfVehicles[i]);
        }
  
    this._arrOfVehicles = new Array();
    this._arrOfTracks = new Array();
    this._visibleVehicles = new Array();
}


//globalna funckja ponbierająca informacje o liniach - wyświetlane w prawym menu
VehicleManager.prototype.getInfo=function(showLoader,callback)
{
    var divResp = document.getElementById(this._strInfoResp);
 
    var fletter = '-1';
    var me = this;
 
    if (divResp ==null) return;
    
    if(this._wbs1) this._wbs1.abort();//anuluj poprzednie zapytanie
    
    this._wbs1 = new WebServiceClient("CNR_DajAktualneNrPojazdow");
        this._wbs1.appendProperty("nr_lini",this.Filter.routeNr);
        this._wbs1.appendProperty("nr_zaj",this.Filter.zajNr);
        this._wbs1.appendProperty("id_prz",this.Filter.stopId);
        this._wbs1.appendProperty("stan",this.Filter.state);
        this._wbs1.appendProperty("odch",this.Filter.variance);
        this._wbs1.appendProperty("nb",this.Filter.nb);
        this._wbs1.appendProperty("typy",this.Filter.types);
        this._wbs1.appendProperty("war_trasy",this.Filter.trackT);
        
        
 //alert(this.Filter.types);
    if(showLoader) divResp.innerHTML = Global.lang.czekaj;
   
    var conf = Global.VT;
   
    this._wbs1.send(function(data){
        var resp = data.getElementsByTagName("Vehicles")[0];
        var routes  = [];
        var vehConf = conf.getByGroup(me.Filter.types);
        
        if(resp == null || resp.firstChild==null ) 
            routes = [];
        else
            routes = resp.firstChild.nodeValue.split(",");
        
        var buffer = new StringBuffer();
        buffer.append("<div class=\"options\"><h2>" + Global.lang.pojazdy + "</h2><table>");
             
        for(var i=0;i<routes.length;++i){
           if(routes[i].charAt(0) != fletter)
           {
             if(fletter!='-1') buffer.append("</td></tr>");
               fletter = routes[i].charAt(0);
               buffer.append("<tr><td style=\'background:"+vehConf.panelLabelColor+";border:1px solid white;padding:3px\'><b>"+routes[i].charAt(0)+"</b></td><td>");
           }
           
           if( me._visibleVehicles.indexOf(routes[i])==-1)
             buffer.append("<span id=\"v_"+routes[i]+"\" onclick='TaStops.vehicleManager._onclickInfo(\"v_"+routes[i]+"\")' class=\'vehicle\' clicked=\"false\" img1='"+vehConf.infoIcon+"' img2='"+vehConf.infoHoverIcon+"' col2='"+vehConf.panelLabelColor+"' style=\"background:url('"+vehConf.infoIcon+"')\">"+routes[i]+"</span>");
           else
             buffer.append("<span id=\"v_"+routes[i]+"\" onclick='TaStops.vehicleManager._onclickInfo(\"v_"+routes[i]+"\")' class=\'vehicle\' clicked=\"true\" img1='"+vehConf.infoIcon+"' img2='"+vehConf.infoHoverIcon+"' style=\"background:url('"+vehConf.infoHoverIcon+"');color:"+vehConf.panelLabelColor+"\">"+routes[i]+"</span>");
          }
        
        buffer.append("</td></tr></table></div>");
        divResp.innerHTML = buffer.toString();
        
        var parent = divResp.parentNode.parentNode;
        //alert(parent.offsetHeight);
        if(parent!=null && parent.offsetHeight> 0){
                var dy = -25;
                if(divResp.previousSibling!=null)
                    dy-=divResp.previousSibling.offsetHeight;
                   
            var h = (parent.offsetHeight+dy) +'px';
            divResp.style.height = h;
        }
        
        
        
        if(callback!=null) callback(data);
    
    });
}

VehicleManager.prototype._onclickInfo = function(parent)
{
    var p = document.getElementById(parent);
    var routeNr = parent.substring(2,parent.length);
       
    if(p.getAttribute("clicked")=="true"){
             p.style.color = "white";
             p.style.background = "url('" + p.getAttribute("img1") + "')";
            var i=this._visibleVehicles.indexOf(routeNr);
            if(i!=-1)
               this._visibleVehicles.splice(i,1);//usunięcie z tablicy
            p.setAttribute("clicked","false")
            }
           else{
             p.style.background = "url('" + p.getAttribute("img2") + "')";
             p.style.color = p.getAttribute("col2");
             this._visibleVehicles.push(routeNr);
             p.setAttribute("clicked","true")
             } 
           this.getVehicles(null,"");
}

VehicleManager.prototype.addRoute = function(strRouteNr)
{
    if( this._visibleVehicles.indexOf(strRouteNr)==-1)
            this._visibleVehicles.push(strRouteNr);
}

VehicleManager.prototype.removeRoute = function(strRouteNr)
{
    var idx = this._visibleVehicles.indexOf(strRouteNr);
    if( idx!=-1)
            this._visibleVehicles.splice(idx,1);
}
 
VehicleManager.prototype.getVehicle = function(id_k)
{
   if(this._arrOfTracks[parseInt(id_k)]== undefined) return null;
   
   return this._arrOfVehicles[this._arrOfTracks[parseInt(id_k)].index];
   
   
}