/* look.js */

/* main js-file for dynamik timetable visualisation */
if( typeof gLOOKJS == 'undefined' ){
  var gLOOKJS = 'defined';

  var CLookStatus = {
    show: function( text ){
      if( $("look_statusdiv") ){
        $("look_statusdiv").innerHTML = text;
      }
    }
  }
  
  /**
   * Collection of functions to handle html elements with js
   **/
  var CNodes = {
    removeAllChilds: function( elem ){
      var child = elem.firstChild;
      while( child ){
        elem.removeChild( child );
        child = elem.firstChild;
      }
    },
  
    getElem: function( tag, id, position, display, left, top, width, height ){
      var elem = document.createElement(tag);
      elem.id = id;
      elem.style.position = position;
      elem.style.display = display;
      elem.style.left = left + 'px';
      elem.style.top = top + 'px';
      if( width != '' ){
        elem.style.width = width + 'px';
        elem.width = width;
      }
      if( height != '' ){
        elem.style.height = height + 'px';
        elem.height = height;
      }
      return elem;
    }
  }
  
  var PeriodicalExecuterForObjects = Class.create();
  PeriodicalExecuterForObjects.prototype = Object.extend(new PeriodicalExecuter(), {
  
    initialize: function(aobject, afrequency) {
      this.obj = aobject;
      this.frequency = afrequency;
      this.currentlyExecuting = false;
      this.registerCallback();
    },
  
    callback: function(){
      if( typeof this.obj != 'undefined' && typeof this.obj.callback != 'undefined' )
        this.obj.callback();
    }
  });
  
  
  
  var look_time = {
    hours: 8,
    minutes: 0,
    seconds: 0,
    refreshtime: 1000,
    faktor: 2,
    
    start: function( h, m, s, fak ){
      this.hours = h;
      this.minutes = m;
      this.seconde = s;
      this.faktor = fak;
      window.setInterval("look_time.event_handler()",this.refreshtime);
    },
  
    event_handler: function() {
      this.addseconds(this.faktor);
    },
    
    addseconds: function(s){
      this.seconds += s;
      if( this.seconds >= 60 ){
        this.minutes += Math.floor(this.seconds / 60);
        this.seconds %= 60;
        if( this.minutes >= 60 ){
          this.hours += Math.floor(this.minutes / 60);
          this.minutes %= 60;
          if( this.hours >= 24 ){
            this.hours %= 24;
          }
        }
      }
    },
  
    getString: function() {
      var currenttime = '';
      if( this.hours < 10 ) currenttime += '0';
      currenttime += this.hours + ':';
      if( this.minutes < 10 ) currenttime += '0';
      currenttime += this.minutes + ':';
      if( this.seconds < 10 ) currenttime += '0';
      currenttime += this.seconds;
      return currenttime;
    }
  }
     
  var look = {
    style: 'standard',
  
    /* functions */
    /* --------- */
    init: function (){
  //   look_ajax.updateperiodically(look_trains.getUrl(),'look_ajaxelem_trains'); 
      window.setInterval("look.event_handler()",2000);
      look_singlechain.clearcanvas();
      look_chainalt.clearcanvas();
    },
  
    event_handler: function (){
      look_time.faktor = parseInt(document.getElementById('input_id_look_speed').value);
      var e=document.getElementById('look_general_input');
      if(e.checked==true){
        if( look_chainalt.showline == true || look_perl.show == true ){
          if( look_chainalt.showline == true ){
            look_chainalt.refresh();
          }
        } else {
          look_trains.refresh();
        }
  
      }
    },
  
    generalinputclick: function (){
      var e=document.getElementById('look_general_input');
      if(e.checked==true){
        document.getElementById('look_input').style.display = 'block';
      }else{
        document.getElementById('look_input').style.display = 'none';
      }
    }
  
  }
  
  var lookalphashadow=lookalphashadow?lookalphashadow:99;
  
  function lookchangeAlphaBy( value ){
    looksetMapAlpha( value + lookalphashadow );
  }
  
  function looksetMapAlpha( newAlpha ){
    lookalphashadow = Math.min(100,Math.max( 0, Math.round(newAlpha) ));
    if( $('look_ajaxelem_mapshadow') ){
      $('look_ajaxelem_mapshadow').style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' +lookalphashadow+ ')';
      $('look_ajaxelem_mapshadow').style.opacity = lookalphashadow / 100;
    }
    gLiveMapLinkRegistration.addOption("lookmapalpha", lookalphashadow);
  }
  
  
  var look_ajax = {
    update: function(url,elementID){
      return new Ajax.Updater(elementID, url, { evalScripts: true });
    },
  
    updateperiodically: function(murl,melementID,mfrequency){
      return new Ajax.PeriodicalUpdater(melementID, murl, { frequency: mfrequency, evalScripts: true } );
    },
  
    replaceSequence: function(url){
      var newUrl = url;
  
      if (currentSequence == -1){
          return null;
        }
  
      newUrl = url.replace (/seqnr=.*?&/, 'seqnr='+currentSequence+'&');
  
      return newUrl;
    },
  
    updateSequenceNumbers : function (){
      var anchors = document.getElementsByTagName('a');
  	 if (currentSequence != -1){
  	   // loop through all anchor tags
  	   for (var i=0; i<anchors.length; i++){
   	     var anchor = anchors[i];
  	 	  var url = anchor.getAttribute('href');
  	 	  if (url){
  	 	    var newUrl = replaceSequence (url);
            anchor.setAttribute ('href', newUrl);
  	 	  }
  	 	}
      }
    },
  
    updateMap: function (mapUrlParams, mapElemId)
    {
      var url = basePath + mapUrlParams + "&maponly=1&ajax=1&ident=" + currentIdent + "&seqnr=" + currentSequence;
  
      if (currentLayoutParam)
         {
         url = url+ "&" + currentLayoutParam;
         }
  
      this.loadUpdatedMap (url, mapElemId);
    },
  
    loadUpdatedMap: function (url, mapElemId){
      new Ajax.Request(url,
      {
         method: 'get',
         onSuccess: function(transport)
             {
             var responseHtml = transport.responseText.replace (/seqnr=(\d+)&CONTENT/, '');
             currentSequence = RegExp.$1;
  
             if ($(mapElemId))
                 {
                 $(mapElemId).replace(responseHtml);
                 }
             else
                 {
                 alert ("Id "+$(mapElemId)+" not found. Could not update map content");
                 }
  
             look_ajax.updateSequenceNumbers ();
             }
      });
    }
  }
  
  
  
  var help = {
  	posInElementId: function (x,y,id){
  	  var elem = document.getElementById(id);
  	  if( elem ){
  		 var cx = absLeft(elem)-getScrollPos().x;
  		 var cy = absTop(elem)-getScrollPos().y;
  		 if( x >= cx &&
  			y >= cy &&
  			x < cx+elem.clientWidth &&
  			y < cy+elem.clientHeight ){
  		 return true;
  		 }
  	  }
  	  return false;
  	},
  
  	switchCheckbox: function (checkboxchecked,imgid){
  	  var checkbox = document.getElementById(imgid);
  	  var newstate = false;
  	  if ( checkbox ){
  		 if ( checkboxchecked == true ){
  			checkbox.src = look_gettpl('imagePath')+'look/checkbox_0.gif';
  		 }
  		 else {
  			newstate = true;
  			checkbox.src = look_gettpl('imagePath')+'look/checkbox_1.gif';
  		 }
  	  }
  	  return newstate;
  	},
  	
    getproductclasscolour: function( productclass ){
      if( typeof look_getproductclasscolour != 'undefined' )
        return look_getproductclasscolour( productclass );
      productclass = Math.round( Math.log( productclass ) / Math.log( 2 ) );
      switch (productclass){
      case 0:
        return "rgba(255,0,0,1)";
      case 1:
        return "rgba(0,0,255,1)";
      case 2:
        return "rgba(0,0,0,1)";
      case 3:
        return "rgba(148,148,148,1)";
      case 4:
        return "rgba(8,132,74,1)";
      case 5:
        return "rgba(240,240,30,1)";
      case 6:
        return "rgba(0,156,206,1)";
      case 7:
        return "rgba(0,82,140,1)";
      case 8:
        return "rgba(220,43,25,1)";
      case 9:
        return "rgba(220,220,150,1)";
      default:
        return "rgba(100,100,100,1)";
      }
  	},
    getproductclasscolours: function( productclassbitfield ){
      var retarray = new Array;
      if( typeof productclassbitfield != 'undefined' && productclassbitfield && productclassbitfield != '' && productclassbitfield != '0' ){
        productclassbitfield = parseInt(productclassbitfield);
        var currindx = 0;
        var tmpprod = 1;
        for( var p = 0; p < 10; p++ ){
          if( ( productclassbitfield & tmpprod ) != 0 ){
            retarray[currindx++] = help.getproductclasscolour( tmpprod );
          }
          tmpprod *= 2;
        }
      }else{
        retarray[0] = "rgba(255,0,0,1)";
      }
      return retarray;
  	}
  
  }
}

