function addEvent(_elem, _evtName, _fn, _useCapture)
{
   if (typeof _elem.addEventListener != 'undefined')
   {
      if (_evtName === 'mouseenter')
         { _elem.addEventListener('mouseover', mouseEnter(_fn), _useCapture); }
      else if (_evtName === 'mouseleave')
         { _elem.addEventListener('mouseout', mouseEnter(_fn), _useCapture); }
      else
         { _elem.addEventListener(_evtName, _fn, _useCapture); }
   }
   else if (typeof _elem.attachEvent != 'undefined')
   {
      _elem.attachEvent('on' + _evtName, _fn);
   }
   else
   {
      _elem['on' + _evtName] = _fn;
   }
}

function mouseEnter(_fn)
{
   return function(_evt)
   {
      var relTarget = _evt.relatedTarget;
      if (this === relTarget || isAChildOf(this, relTarget))
         { return; }

      _fn.call(this, _evt);
   }
};

function isAChildOf(_parent, _child)
{
   if (_parent === _child) { return false; }
      while (_child && _child !== _parent)
   { _child = _child.parentNode; }

   return _child === _parent;
}

var is_over = false;
var positions = [];
var next_position = 0;
var timer = null;
var interval = null;

var leftarrow = null;
var rightarrow = null;


var stopScrolling = false;
var currentlyScrolling = false;
var framenodes = [];
var ANIMATION_INTERVAL = 16;
var FRAME_INTERVAL = 30;
var START_TIMEOUT = 4000;
var DEFAULT_TIMEOUT = 5000;
var DEFAULT_SLIDE_DURATION = 1000;
var HOVER_SLIDE_TIMEOUT = 11000;
var CLICK_SLIDE_DURATION = 500;

function ease_smooth(pos){
    return ((-Math.cos(pos*Math.PI)/2) + 0.5);
//this transition is from script.aculo.us
}

function scroller(){
  var scrollbox = document.getElementById('main-articles');
  framenodes[next_position].className = 'index-box-frame';
 
  next_position += 1;
  
  if(next_position == positions.length)
      next_position = 0;
  
    // origin + diff * position
    var startpos = scrollbox.scrollLeft;
    var start = (new  Date).getTime();
    var duration = DEFAULT_SLIDE_DURATION;  
    var finish = start + duration;
        
    var is_scrolling = true
    
    function interval_function(){
        var time = (new  Date).getTime(),  
            pos  = time > finish ? 1 : (time -start) / duration;
        scrollbox.scrollLeft = startpos + (positions[next_position]-startpos) * ease_smooth(pos)
        if(time > finish){
            framenodes[next_position].className = 'index-box-frame active';
            // clear the animation timeout
            clearTimeout(interval);
            // dont set if hovering
            if(!is_over){
                // set the scroll timeout
                timer = setTimeout(scroller, DEFAULT_TIMEOUT);
            }
            return
        }
        
        setTimeout(interval_function, ANIMATION_INTERVAL);
    }
    
    clearTimeout(timer);
    // set the animation timeout
    interval = setTimeout(interval_function,ANIMATION_INTERVAL);
}

function insertAfter(parent, node, referenceNode) {
  parent.insertBefore(node, referenceNode.nextSibling);
}
goog.events.listen(window, goog.events.EventType.LOAD, function(){
  		var scrollbox = document.getElementById('main-articles');
  		  var contentbox = null;
		  var shift = 0;
		  var positionbox = null;
		  
  		  if(scrollbox){
  		      
  		  	  positionbox = document.createElement('div');
  		  	  positionbox.className = 'index-box';
  		  	  positionbox.innerHTML = '';
  		  	  //scrollbox.parentNode.insertBefore(positionbox, scrollbox);
  		  	  insertAfter(scrollbox.parentNode, positionbox, scrollbox);
			  // grab first child
			  for(var i=0; i<scrollbox.childNodes.length; i++){
				  if(scrollbox.childNodes[i].nodeType === 1){
					  contentbox = scrollbox.childNodes[i];
					  break;
				  }
			  }
			  
			  
  		  }
  		  
  		  if(contentbox){
  		  	  
			  for(i=0; i<contentbox.childNodes.length; i++){
				  if(contentbox.childNodes[i].nodeType === 1){
					  var frame = contentbox.childNodes[i];
					  
					  frame.style.left = shift + 'px';
					  frame.style.top = '0';
					  frame.style.position = 'absolute';
					  
					  var img = frame.getElementsByTagName('img')[0];
					  var newimg = img.cloneNode(true);
					  newimg.style.width ='100%';
					  positions.push(shift);
					  shift += frame.clientWidth;
					  
					  
					  
					  var indexframe = document.createElement('div');
					  if(positions.length == 1){
					      indexframe.className = 'index-box-frame active';
					  } else {
                          indexframe.className = 'index-box-frame';
				  	  }
				  	  indexframe.setAttribute('position', positions.length-1);
				  	  //indexframe.innerHTML = indexframe.getAttribute('position');
				  	  indexframe.appendChild(newimg);
				  	  framenodes.push(indexframe);
				  	  
				  	  indexframe.onclick = function(){
				  	      index_frame_onclick(parseInt(this.getAttribute('position')));
				  	  }
				  	  
				  	  
					  positionbox.appendChild(indexframe);
				  }
			  }	  
			  
			  leftarrow = document.createElement('div');
			  leftarrow.className = 'scroll-left';
			  leftarrow.innerHTML = '&lt;';
			  leftarrow.onclick = function(){
			      var pos = next_position-1;
			      if(pos < 0)
			          pos = positions.length -1;
			      index_frame_onclick(pos);
			      
			  }
			  contentbox.parentNode.parentNode.appendChild(leftarrow);
			  
			  rightarrow = document.createElement('div');
			  rightarrow.className = 'scroll-right';
			  rightarrow.innerHTML = '&gt;';
			  rightarrow.onclick = function(){
			      var pos = next_position+1;
			      if(pos >= positions.length){
			          pos = 0;
			      }
			      index_frame_onclick(pos);
			      
			  }
			  contentbox.parentNode.parentNode.appendChild(rightarrow);
			  
			  addEvent(scrollbox.parentNode, 'mouseenter', function(e){
                is_over = true;
                show_arrows();
			  	 clearTimeout(timer);
			  }, true);
			  
			  addEvent(scrollbox.parentNode, 'mouseleave', function(e){
                is_over = false;
                hide_arrows();
                timer = setTimeout(scroller, DEFAULT_TIMEOUT);
			  }, true);
			  
			  timer = setTimeout(scroller, START_TIMEOUT);
  		  }  
  }, true);

function show_arrows(){
    leftarrow.style.display = 'block';
    rightarrow.style.display = 'block';
}

function hide_arrows(){
    leftarrow.style.display = 'none';
    rightarrow.style.display = 'none';
}

function index_frame_onclick(pos){
    
    
    var scrollbox = document.getElementById('main-articles');
    
  if(currentlyScrolling){
      return
  }
  
  clearTimeout(interval);
  
  
  framenodes[next_position].className = 'index-box-frame';
  
  clearTimeout(timer);
  
  positiontogoto = parseInt(pos);
  next_position = positiontogoto;
  
    var startpos = scrollbox.scrollLeft;
    var start = (new  Date).getTime();
    var duration = CLICK_SLIDE_DURATION;  
    var finish = start + duration;
        
    framenodes[next_position].className = 'index-box-frame active';
    
    currentlyScrolling = true;
    intv = setInterval(function(){
        var time = (new  Date).getTime();
        var pos  = time > finish ? 1 : (time -start) / duration;
        scrollbox.scrollLeft = startpos + (positions[positiontogoto]-startpos) * ease_smooth(pos);
        
        if(time > finish){
            clearInterval(intv);
            currentlyScrolling = false;
            
            //timer = setTimeout(scroller, 4000);
        }
    },FRAME_INTERVAL);
    //timer = setTimeout(scroller, 8000);
}

