﻿// JScript File



VirtualTable = function(stopid,respDiv,opt_opts)
{
       this.blk1 = new Blink();
       this.blk3 = new Blink();
       this.blk_odj = new Blink();
       this.opt_opts = opt_opts || {};
       
       this.isStaticOne  = true;
       this.isStaticAll  = false;
       this.isDaysLoaded = false;
       this.enableMenu   = false || this.opt_opts.menu;
       this.enableDays = false || this.opt_opts.days;
       this.enableVehicles = false || this.opt_opts.enableVehicles;
      
      
       this.rowLimit =  this.opt_opts.rowLimit || 100;
       this.stopid  =  stopid;
       this.respDiv = respDiv;
       this.hDiv = document.createElement('div');//nagłówek np menu
       this.tbDiv = document.createElement('div');//element zawiera tablice z rozkładem
       this.daysDiv = document.createElement('div');//element zawiera informacje o typach dni
       this.menuDiv = document.createElement('div');//element zawiera poziome menu
      
       this.xmlResp = null;
       this.arrayOfData = [];//sprasowanie informacje o rozkladzie
       this.scheduleTime =[];//czas pobrania rozkladu
       this.stopname = '';
       this.dayName = '';//opis dnia np ROBOCZY
       this.dayType = '';//typ dnia np RO
       this.timerId = null;
       this.maxHeight =  this.opt_opts.maxHeight || 100  ;//maksymalna wysokosc tabeli w pikselach
       this.minHeight =  this.opt_opts.minHeight || 50  ;//minimalna wysokosc tabeli w pikselach
      
       this.respDiv.appendChild(this.menuDiv);
       this.respDiv.appendChild(this.daysDiv);
       this.respDiv.appendChild(this.hDiv);
       this.respDiv.appendChild(this.tbDiv);
     
     //this.daysDiv.innerHTML = "<span style='float:right;font-family:Arial;font-size:10px'> || <input type='checkbox'>Odświeżaj</input></span>";
      
}

VirtualTable.openPopUp = function(id)
{
    window.open((typeof(PATH)!='undefined'?PATH:'')+ "Druki/AllSchedToPdf.aspx?id=" +id+ "&day=ALL","KreatorPdf","width=600,height=360,toolbar=yes,scrollbars=yes");
}
VirtualTable.prototype.noFindMessage = function(respDiv)
{
    this.hDiv.innerHTML='<h3 style=\"color: #5E58C9;text-align:center\">' + Global.lang.nieznal +  '</h3>';
    this.tbDiv.innerHTML='';
}

    
VirtualTable.prototype.viewBind =function(_routeNr) 
    { 
        var respdiv = this.tbDiv;
        var buffer = new StringBuffer();
        var d = new Date();
        var curr_sec = d.getSeconds();
        var row_col = ["class=\"back_col_1\"", "class=\"back_col_2\""];
        var time_color='<span>';
      
        //**************HEADER*******************
        buffer.append("<table class=\"odjazdy_header\">");
        buffer.append("<tr><th class=\"blank\"></th>");
        buffer.append("<th>" + this.stopname + "</th>");
        buffer.append("<th style=\"text-align:right\"><span id=\"cur_time\"> " + this.scheduleTime[0]+":");
        buffer.append(this.scheduleTime[1] + "</span> </th></tr>");
        buffer.append("");
        buffer.append("<tr><td></td><td></td><td class='dzien'>" + this.dayName + "</td></tr></table>");
        
                 
        //*************MAIN TABLE****************
        buffer.append("<table class=\"odjazdyVTBL\" style='border-bottom:0px'>");
        buffer.append("<thead>");
        buffer.append("<tr>");
        
        if(this.isStaticOne && this.enableVehicles)
            buffer.append("<th style='width:24px'>" + Global.lang.pojazdy.substring(0,Math.min(Global.lang.pojazdy.length, 3)) + "</th>");
        
        buffer.append("<th class='nr_lini' onclick=\'javascript:virtualT.sortByRoutes()\' >" + Global.lang.linie + "</th>"
        + "<th class='dir' onclick=\'javascript:virtualT.sortByDirections()\'>"
        + Global.lang.kierDoc + "</th><th class='time' onclick=\'javascript:virtualT.sortByTime()\'>" + Global.lang.odjazd + "</th></tr>");
         buffer.append("</thead></table>");

        
        this.hDiv.innerHTML = buffer.toString();
        buffer.clear();
        buffer.append("<table class=\"odjazdyVTBL\"><tbody>");


        this.blk_odj.setBlinkTime(500);
           
       for(var i=0;i<this.arrayOfData.length;++i)   
       {
       
           var time_arr=[];
           var time_full="";
           var route_nr = this.arrayOfData[i][0];
           var dir = this.arrayOfData[i][1];
           
       
          if(this.arrayOfData[i][2].length>1)
           {    
                time_full = "";
                var a = this.arrayOfData[i][2];
                for(var k =0;k<a.length;++k)
                  time_full += (a[k][0]+":" + a[k][1] + a[k][2] +" ");
           }
          else {
                time_arr = this.arrayOfData[i][2][0];
                var time_min;
                if (time_arr[0]=="")
                {
                    time_min = time_arr[1];   
                     if (parseInt(time_min) >= 0 && parseInt(time_min) <= 2 || time_min =="<1MIN"){
                         time_color = "<span class=\"blink\">";
                         this.blk_odj.setBlinkTime((parseInt(time_min)+1)*300)
                         }
                     else
                         time_color = "<span class=\"green_font\">";
                     
                     time_full = time_min +" " +time_arr[2];
                }
                else{ 
                    time_full = time_arr[0]+":"+time_arr[1] + time_arr[2]+ " ";
                    time_color =  "<span>";
               }
          }
        
        if( _routeNr =='' || (route_nr.trim() == _routeNr.trim()) )
        {   
              buffer.append("<tr " + row_col[i%2] + ">");
              
              if(this.isStaticOne){
                  if(this.enableVehicles){
                        buffer.append("<td style='width:30px'>&nbsp;");
                   
                        if(this.arrayOfData[i][2][0][4])//jeśli jest pojazd na trasie
                        {
                            buffer.append("<img src='" + (typeof(PATH)!='undefined'?PATH:"") + "img/bus_32x32.png' width='16' height='16' style='cursor:pointer' onclick=\"VirtualTable.vehicleSelected('"+this.arrayOfData[i][0]+"',"+ this.arrayOfData[i][2][0][3] + ")\"></img>");
                        }
                        buffer.append("</td>");
                    }
              }

              buffer.append("<td class=\"nr_lini\" ><span class=\"nr_lini\">" + route_nr + "</span></td>");
              buffer.append("<td class='dir'><span id=\"frow\">" + dir + "</span></td>");
              buffer.append("<td class='time'>" + time_color + time_full+"</td>");
              buffer.append("</tr>");
         }
        } 
     
       buffer.append('</tbody><table>');
       
       respdiv.innerHTML =  buffer.toString();
         this.blk1.clear();this.blk3.clear();this.blk_odj.clear();
         
         this.blk1.setBlinkTime(1000);
         this.blk1.setBlinkById('frow');this.blk1.oneBlink();
        
         this.blk_odj.setBlinkByTag('span');this.blk_odj.startBlink();
         
         this.blk3.setBlinkById('cur_time');this.blk3.setBlinkTime(400);
         
         if (curr_sec>0 && curr_sec<10)
             this.blk3.startBlink();
             
        this.checkSize();  
        this.viewLoaded(buffer);     
}

VirtualTable.prototype.beginLoad=function()//odpalane gdy rozpoczęto ładowanie rozkładu
{}
VirtualTable.prototype.viewLoaded=function(buffer)//odpalane gdy tabela z rozkładem zostanie wyświetlona
{}
VirtualTable.prototype.dataLoaded=function(buffer)//odpalane gdy sparsowano dane
{}

VirtualTable.prototype.checkSize = function(){
        if(this.tbDiv.firstChild.offsetHeight  > this.maxHeight){
            this.tbDiv.style.height = this.maxHeight  + 'px';
            this.tbDiv.style.overflow = 'auto';
            this.tbDiv.firstChild.style.width=(this.tbDiv.offsetWidth-20) +'px';
        }
        else{
        
            if(this.tbDiv.firstChild.offsetHeight < this.minHeight)
            {
              this.tbDiv.style.height = this.minHeight + 'px';
            }
            else
              this.tbDiv.style.height = 'auto';
            
            this.tbDiv.firstChild.style.width = '100%';
        }
}

VirtualTable.prototype.choseRoute=function(_routeNr)
{
    this.viewBind(_routeNr);
}


VirtualTable.prototype.dataBind = function(xmlResp)
{

      this.arrayOfData =new Array(); 
      this.arrayOfRoutes = new Array(); 
      var stop ;
      var schedules = xmlResp.getElementsByTagName("Schedules")[0];
      
      if(schedules == null){if(!this.isStaticOne) this.setStaticOne(); else this.noFindMessage(); this.dataLoaded();return null;}
        this.scheduleTime = schedules.getAttribute('time').split(':');
      
      stop = schedules.getElementsByTagName("Stop");      
      if (stop!=null && stop.length==0){if(!this.isStaticOne) this.setStaticOne(); else this.noFindMessage(); this.dataLoaded();return null;}

      var day = stop[0].getElementsByTagName("Day");
      if (day == null || day.length==0){ this.noFindMessage() ;this.dataLoaded();return null; }
      this.dayName = day[0].getAttribute("desc");
      
      var route = stop[0].getElementsByTagName("R");
      if (route != null && route.length==0 ){ this.noFindMessage() ;this.dataLoaded();return null; }

      this.stopname =  stop[0].getAttribute("name");
               
       for(var i=0;i<route.length && i<this.rowLimit;++i)   
       {
           var schedules =  route[i].getElementsByTagName("S");
           var arrayOfTimes = new Array();
           
           if (schedules!=null && schedules.length==0) continue;
          
           for(var j=0;j<schedules.length;++j){
               arrayOfTimes.push([schedules[j].getAttribute("th"),schedules[j].getAttribute("tm"),schedules[j].getAttribute("uw"),parseInt(schedules[j].getAttribute("id")),schedules[j].getAttribute("veh")=="T"?true:false]);
          }
           var route_nr = route[i].getAttribute("nr");
           var dir = route[i].getAttribute("dir");            
           this.arrayOfData.push([route_nr,dir,arrayOfTimes]);
           this.arrayOfRoutes.push(route_nr);
        }
    this.dataLoaded();
    this.viewBind('');
}

 
VirtualTable.prototype.sortByRoutes =function ()
{
  
 _sort= function(a,b) 
    {
        var x = a[0];
        var y = b[0];
        return ((x < y) ? -1 : ((x < y) ? 0 : 1));
    }
  this.arrayOfData.sort(_sort);
  this.viewBind('');
}

VirtualTable.prototype.sortByDirections =function ()
{
  
 _sort= function(a,b) 
    {
        var x = a[1];
        var y = b[1];
        return ((x < y) ? -1 : ((x < y) ? 0 : 1));
    }
   this.arrayOfData.sort(_sort);
   this.viewBind('');
}

VirtualTable.prototype.sortByTime =function ()
{
  
 _sort= function(a,b) 
{
        var xth = a[2][0][0];
        var xtm = a[2][0][1];
        var yth = b[2][0][0];
        var ytm = b[2][0][1]; 
        
        if(xth=="" && yth!="")
            return -1;
        else if (xth!="" && yth=="")
            return 1;
        else if (xth!="" && yth!=""){
          
          /*int adelta = ahoursInt * 60 + aminutesInt - DateTime.Now.Hour * 60 - DateTime.Now.Minute;
          int bdelta = bhoursInt * 60 + bminutesInt - DateTime.Now.Hour * 60 - DateTime.Now.Minute;

          if (bdelta < 0 && adelta > 0) return node;
          else if (Math.Sign(bdelta * adelta) ==1  && bdelta > adelta) return node;
            */ 
        
        
            return ((parseInt(xth) < parseInt(yth)) ? -1 : ((parseInt(xth) == parseInt(yth)) ?(     (parseInt(xtm) < parseInt(ytm)) ? -1 : (parseInt(xtm) == parseInt(ytm))?0:1): 1));
        }
            return ((xtm < ytm) ? -1 : ((xtm < ytm) ? 0 : 1));
     
 }
   this.arrayOfData.sort(_sort);
   this.viewBind('');

}

VirtualTable.prototype.getNotes = function()
{
           var str = new StringBuffer();
           var me = this;
           var row_col = ["class=\"back_col_1\"", "class=\"back_col_2\""];
       
           wbs=new WebServiceClient("DajUwage");
           wbs.appendProperty('nr_przyst',this.stopid);
           wbs.send(function(d){

           me.arrayOfData =new Array();
           me.hDiv.innerHTML="";  
           var notes = d.getElementsByTagName("Note");
     
            str.append('<table class=\"odjazdyVTBL\">');
     
     
           if(notes==null){ this.noFindMessage() ;return null; }
               for(var i=0; i<notes.length;++i){
                   str.append("<tr "+row_col[i%2]+">");
                        str.append("<td>");   
                        str.append(notes[i].childNodes[0].childNodes[0].nodeValue);
                        str.append("</td><td>");
                        str.append(notes[i].childNodes[1].childNodes[0].nodeValue);
                        str.append("</td>")
                  str.append("</tr>")  
               }
           str.append("</table>")
       
          me.tbDiv.innerHTML = str.toString();
          me.checkSize();
          me.viewLoaded(str);
         });
        
}



   
VirtualTable.prototype.setDynamic = function()
{
        this.showLoading();
        this.isStaticOne = false;
        this.isStaticAll = false;
        this.isNotes = false;
        this.getSchedules();
}
VirtualTable.prototype.setStaticOne = function()
{
        this.showLoading();
        this.isStaticOne = true;
        this.isStaticAll = false;
        this.isNotes = false;
        this.getSchedules();
}
VirtualTable.prototype.setStaticAll = function()
{
        this.showLoading();
        this.isStaticAll = true;
        this.isStaticOne = false;
        this.isNotes = false;
        this.getSchedules();
}

VirtualTable.prototype.setNotes = function()
{
        this.showLoading();
        this.isStaticAll = false;
        this.isStaticOne = false;
        this.isNotes = true;
       
        if(this.enableMenu)
            this.refreshMenu();
        this.getNotes();
}

VirtualTable.prototype.getSchedules = function(day)
{
         var m = this;
         this.dayType = day;
       
         if(this.enableMenu) this.refreshMenu();
         this.beginLoad();//ważne aby wykonano za odświeżeniem menu
        
         if(this.isStaticOne==true){
           wbs=new WebServiceClient("CNR_DajNajblizszeOdjNaPrzyst");
           wbs.appendProperty('nr_przyst',this.stopid);
           wbs.send(function(d){m.dataBind(d);});
           m.daysDiv.style.display='none';
          }
         else{
             if(!this.isDaysLoaded && this.enableDays){
                wbs = new WebServiceClient("DajTypyDni");
                m.daysDiv.style.display='block';
         
                wbs.send(function(d){
                    var days = d.getElementsByTagName("Day");
                    var buf = new StringBuffer();
                    buf.append("<span style='float:right;text-algin:right;display:block'>")
                    for(var i=0;i<days.length;++i)
                        buf.append("<a class='nav' href=\"javascript:virtualT.getSchedules('"+days[i].getAttribute("type")+"')\">"+ days[i].getAttribute("desc") +"</a> &nbsp;");
                    buf.append("</span><br/>");
                    m.daysDiv.innerHTML = buf.toString();
                    m.isDaysLoaded = true;
                    });
                }
             
         
         
              wbs=new WebServiceClient("DajOdjazdyStatyczne");
              wbs.appendProperty('nr_przyst',this.stopid);
              wbs.appendProperty('typ_dnia',day?day:"");
              wbs.appendProperty('nr_lini',"");
              wbs.send(function(d){m.dataBind(d);});
         }
        
        
}

VirtualTable.prototype.showLoading = function(){
    this.hDiv.innerHTML="<h3 style=\"color: #5E58C9;text-align:center\">" + Global.lang.czekaj + "</h3>";
   this.tbDiv.innerHTML="";
   
}

VirtualTable.prototype.refreshMenu = function()
{   
    buf = new StringBuffer();
    
    
         buf.append('<ul class=\'basictab\'>'
            +'<li class=' + ((!this.isStaticAll && !this.isNotes)?'selected':'') +  '><a href="javascript:virtualT.setStaticOne()" >' + Global.lang.najblOdj + '</a></li>'
            +'<li class=' + ((this.isStaticAll && !this.isNotes)?'selected':'') +  '><a href="javascript:virtualT.setStaticAll()" >' + Global.lang.wszystOdj + '</a></li>' 
            +'<li class=' + ((this.isNotes)?'selected':'') +  '><a href="javascript:virtualT.setNotes()" >' + Global.lang.uwagi +  '</a></li>' 
            +'<li><a href=\'javascript:virtualT.openFS()\'>'+ Global.lang.pelnyEkran + '</a></li>'
            +'<li><a href=\'Druki/AllSchedules.aspx?id='+ this.stopid+  '&day=ALL\' target="_blank">' + Global.lang.drukuj +'</a></li>'
            +'<li><a  onclick="VirtualTable.openPopUp(' + this.stopid  + ')"  target="_blank">Pdf</a></li>'
             +'</ul>');
 
    this.menuDiv.innerHTML = buf.toString();
    
return buf.toString();
}
//odświeżanie tylko w przypadku odjazdów najbliższych
VirtualTable.prototype.startRefreshing=function(time)
{
    var me = this;
    if(this.isStaticOne || (!this.isStaticOne && !this.isStaticAll))
        this.timerId = window.setInterval(function(){me.getSchedules(me.dayType);},time);
}
VirtualTable.prototype.stopRefreshing=function()
{
    window.clearInterval(this.timerId);
}
VirtualTable.prototype.openFS=function()
{
     //window.open(typeof(PATH)!='undefined'?PATH:''+'../odjazdyFS.aspx?id=' + this.stopid,'','width='+screen.width+',height='+screen.height+',top=0,left=0');
    window.open('odjazdyFS.aspx?id=' + this.stopid,'','width='+screen.width+',height='+screen.height+',top=0,left=0');
   
}
//funkcja wspólna
VirtualTable.vehicleSelected=function(routeNr,idKursu)
{
       
}
