var AssemblyBelt = {
  WAY_LEFT_TO_RIGHT: 0,
  WAY_RIGHT_TO_LEFT: 1,
  
  init: function(container) {
    // configure attributs
    this.jumpspeed = 2;
    this.timespeed = 40;
    this.moveway = AssemblyBelt.WAY_RIGHT_TO_LEFT;
    
    // attributs
    this.container = $(container);
    this.wrapper;
    this.parts = [];
    
    //create basic structure...    
    var childs = this.container.childElements();
    
    this.wrapper = $(document.createElement("div"));
    this.wrapper.setAttribute('class', 'assemblybelt-wrapper')
    this.container.insert(this.wrapper);
    
    var part = $(document.createElement("div"));
    part.setAttribute('class', 'assemblybelt-part');
    this.wrapper.insert(part);
    
    for(var i=0; i < childs.length; i++){
      child = childs[i];
      child.remove();
      part.insert(child);
    }
    
    // count how many part are needed
    var count = 3*Math.ceil(this.container.getWidth() / this.wrapper.getWidth())
    if(count == Infinity)count=0;
    this.count = count;
	
    wrapper_width = 0;
    // create parts
    this.parts[this.parts.length] = part;
    
    for(var i=0; i<(count-1); i++){
      clone = part.cloneNode(true);
      this.parts[this.parts.length] = clone
      this.wrapper.insert(clone);
    }
	wrapper_width = this.parts[0].getWidth()*this.count;
    this.wrapper.setStyle({width: wrapper_width + 'px'});
    this.wrapper.setStyle({position: 'absolute'});
    
    AssemblyBelt.swappart.bind(this)();
    setInterval(AssemblyBelt.move.bind(this), this.timespeed);
  },
  
  move: function(){
    if(this.wrapper.getHeight() > 55){
	  wrapper_width = this.parts[0].getWidth()*this.count;
      this.wrapper.setStyle({width: wrapper_width + 'px'});
	}
    var x = parseInt(this.wrapper.getStyle('left'));
    if(isNaN(x))x=0;
    if(this.moveway==AssemblyBelt.WAY_LEFT_TO_RIGHT) x += this.jumpspeed;
    else if(this.moveway==AssemblyBelt.WAY_RIGHT_TO_LEFT) x -= this.jumpspeed;
    this.wrapper.setStyle({left: x+'px'});
    AssemblyBelt.swappart.bind(this)();
  },
  
  swappart: function(){
    for(var i = 0; i < this.parts.length; i++){
      part = this.parts[i]
      if(this.moveway==AssemblyBelt.WAY_LEFT_TO_RIGHT){
        if( parseInt(this.container.getWidth()*1.5) < parseInt(part.viewportOffset().left) ){
          this.wrapper.setStyle({left: (parseInt(this.wrapper.getStyle('left'))-part.getWidth())+'px'})
        }
      } else if(this.moveway==AssemblyBelt.WAY_RIGHT_TO_LEFT){
        if( parseInt(this.container.getWidth()*0.5)*-1 > (parseInt(part.viewportOffset().left) + parseInt(part.getWidth())) ){
          this.wrapper.setStyle({left: (parseInt(this.wrapper.getStyle('left'))+part.getWidth())+'px'})
        }
      }
    }
  }
}

function initAssemblyBelt() { 
  $$('.assemblybelt').each(function(container) {
    new AssemblyBelt.init(container)
  });
}

document.observe('dom:loaded', initAssemblyBelt);

