var tableObjList = new Array();
var jobs = { earlier: { down: false, id: -1 }, later: { down: false, id: -1 } };
var timeout = 300;

function tableObj(obj)
{
	var tmp = obj.firstChild;

	while(tmp) {
		if (!tmp.id) {
			tmp = tmp.nextSibling;
			continue;
		}

		switch (tmp.id) {
			case 'ttHeader':
				this.headerDiv  = tmp;
			break;
			case 'ttMargin':
				this.marginDiv	= tmp;
			break;
			case 'ttBody':
				this.contentDiv	= tmp;
			break;
		}

		tmp = tmp.nextSibling;
	}


	if (this.headerDiv && this.marginDiv && this.contentDiv)
		this.valid = true;
	else
		this.valid = false;
}

function handleIE()
{
	for(var item in tableObjList)
	{
		if (item && tableObjList[item] && tableObjList[item].valid)
		{
			addScrollSynchronization(tableObjList[item].marginDiv, tableObjList[item].contentDiv, "vertical");
			addScrollSynchronization(tableObjList[item].headerDiv, tableObjList[item].contentDiv, "horizontal");
		}

		if (item && tableObjList[item] && tableObjList[item].valid)
		{
			addScrollSynchronization(tableObjList[item].marginDiv, tableObjList[item].contentDiv, "vertical");
			addScrollSynchronization(tableObjList[item].headerDiv, tableObjList[item].contentDiv, "horizontal");
		}
	}
}

function handleGecko()
{
	for(var item in tableObjList)
	{
		if (item && tableObjList[item] && tableObjList[item].valid)
		{tableObjList[item].contentDiv.onscroll = onScrollGeckoHandler;}
	}
}

function onScrollGeckoHandler(event)
{
	if (event)
	{
		var obj = null;
		for (var tableObj in tableObjList) {
			if (tableObjList[tableObj].contentDiv.id == event.target.id) {
				obj = tableObjList[tableObj];
				break;
			}
		}

		if (obj)
		{
			// Vertical
			obj.headerDiv.scrollLeft = event.target.scrollLeft;
			obj.marginDiv.scrollTop = event.target.scrollTop;
			
			ttScrollCurrentOffset = obj.headerDiv.scrollLeft;
		}

	}
}

// This is a function that returns a function that is used
// in the event listener
function getOnScrollFunction(oElement) {
	return function () {
		if (oElement._scrollSyncDirection == "horizontal" || oElement._scrollSyncDirection == "both")
			oElement.scrollLeft = event.srcElement.scrollLeft;
		if (oElement._scrollSyncDirection == "vertical" || oElement._scrollSyncDirection == "both")
			oElement.scrollTop = event.srcElement.scrollTop;
	};

}
// This function adds scroll syncronization for the fromElement to the toElement
// this means that the fromElement will be updated when the toElement is scrolled
function addScrollSynchronization(fromElement, toElement, direction) {
	removeScrollSynchronization(fromElement);

	fromElement._syncScroll = getOnScrollFunction(fromElement);
	fromElement._scrollSyncDirection = direction;
	fromElement._syncTo = toElement;
	toElement.attachEvent("onscroll", fromElement._syncScroll);
}

// removes the scroll synchronization for an element
function removeScrollSynchronization(fromElement) {
	if (fromElement._syncTo != null)
		fromElement._syncTo.detachEvent("onscroll", fromElement._syncScroll);

	fromElement._syncTo = null;;
	fromElement._syncScroll = null;
	fromElement._scrollSyncDirection = null;
}

function lineSelectionChange()
{
	var selForm = document.getElementById('lineSelectionForm');
	if (selForm) selForm.submit();
}

function expandAllSections()
{
	var imgs = document.getElementsByTagName('img');	
	
	for (var i=0; i < imgs.length; i++)
	{
		if (imgs[i].src.indexOf('expand.png') > -1) {
			var oc = imgs[i].onclick;
			if (oc)
				oc.apply();
		}
	}
}

function sectionCollapsExpand(objID)
{
	resetBodyHeight();
	var blockButton=document.getElementById('ttBut_sect_'+objID);
	
	if (blockButton)
	{
	    
	    if(blockButton.src && blockButton.src.substr(blockButton.src.length-11)=="collaps.png")
	    {
	        //section collaps 
	        blockButton.src=blockButton.src.substr(0,blockButton.src.length-11)+"expand.png";
	        
	        for(var iRow=0;iRow<150;iRow++)
	        {
	        	var index = parseInt(objID)+iRow;
	        	var rowMDiv=document.getElementById('ttMR_row_'+index);
	        	var rowBDiv=document.getElementById('ttBR_row_'+index);
	        	
	        	if (rowMDiv && rowBDiv)
	        	{
	        		if (rowMDiv.className=="ttMarginTP")
	        		{
	        			break;
	        		}
	        		else
	        		{
	        			rowMDiv.style.display='none';
	        			rowBDiv.style.display='none';
	        		}
	        	}
	        }
	    }
	    else
	    {
	        //section expand
	        blockButton.src=blockButton.src.substr(0,blockButton.src.length-10)+"collaps.png";

	        for(var iRow=0;iRow<150;iRow++)
	        {
	        	var index = parseInt(objID)+iRow;
	        	var rowMDiv=document.getElementById('ttMR_row_'+index);
	        	var rowBDiv=document.getElementById('ttBR_row_'+index);
	        	
	        	if (rowMDiv && rowBDiv)
	        	{
	        		if (rowMDiv.className=="ttMarginTP")
	        		{
	        			break;
	        		}
	        		else
	        		{
	        			rowMDiv.style.display='block';
	        			rowBDiv.style.display='block';
	        		}
	        	}
	        }
	    }                
	}
	adjustBodyHeight();
	setTTScrollCurrentOffset(ttScrollCurrentOffset);
}

function onTTCBRowChange(objID)
{
    var marginBlock=document.getElementById('ttMB_row_'+objID);
    var bodyBlock=document.getElementById('ttBB_row_'+objID);
    var selector=document.getElementById('ttCB_row_'+objID);
    
    if (marginBlock && bodyBlock && selector)
    {
        if(selector.value=='on')
        {
            marginBlock.style.display='none';
            bodyBlock.style.display='none';
        }
        else
        {
            marginBlock.style.display='block';
            bodyBlock.style.display='block';        
        }
    }
}

function adjustBodyWidth()
{
    var ttTable=document.getElementById('ttTable');
    if(ttTable)
    {
	 var viewportwidth;
 	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight 
 	if (typeof window.innerWidth != 'undefined')
 	{viewportwidth = window.innerWidth;}
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if (typeof document.documentElement != 'undefined'
     		&& typeof document.documentElement.clientWidth !=
     		'undefined' && document.documentElement.clientWidth != 0)
 	{viewportwidth = document.documentElement.clientWidth;}
 	// older versions of IE
 	else
 	{viewportwidth = document.getElementsByTagName('body')[0].clientWidth;}
    
    	if(viewportwidth>800)
    	{ttTable.style.width=(viewportwidth-65)+"px";}	
    }
    
    var bodyRow=document.getElementById('ttBR_row_1');
    if (bodyRow)
    {
        var lastDivElem=null;
        for(var iElem=bodyRow.childNodes.length-1;iElem>=0;iElem--)
        {
        	if(bodyRow.childNodes[iElem].tagName=="DIV")
        	{
        		lastDivElem=bodyRow.childNodes[iElem];
        		break;
        	}
        }        
        if (lastDivElem)
        {
            var newLength=lastDivElem.clientWidth+lastDivElem.offsetLeft+10;
            if (newLength<650) newLength=650;
            
            for(var iRow=1;iRow<150;iRow++)
            {
            	var curRow=document.getElementById('ttBR_row_'+iRow);
            	if(curRow){curRow.style.width=newLength+'px';}
            	//else{break;}
            }
        }
    }
}

function resetBodyHeight()
{
	var bodyDiv=document.getElementById('ttBody');
	if (bodyDiv)
	{
		bodyDiv.style.height="";
	}

}

function adjustBodyHeight()
{
	var bodyDiv=document.getElementById('ttBody');
	if (bodyDiv)
	{
		var newHeight=bodyDiv.clientHeight+35+"px";
		bodyDiv.style.height=newHeight;
	}
}

function onLoadLegTT()
{
	var legTTs = document.getElementsByTagName('div');

	for (var tt in legTTs) {
		if (tt && legTTs[tt].id == 'ttTable') {
			var tmpObj = new tableObj(legTTs[tt]);
			if (tmpObj && tmpObj.valid) {
				tableObjList[legTTs[tt].id] = tmpObj;
			}
		}
	}

	document.all ? handleIE() : handleGecko();
	adjustBodyWidth();
	adjustBodyHeight();
	
	var elr = document.getElementById('ttScrollEarlier');
	var ltr = document.getElementById('ttScrollLater');
	
	if (elr) {
		attachEventListener(elr, 'mousedown', ttScrollEarlier_onmousedown, true);
		attachEventListener(elr, 'mouseup', ttScrollEarlier_onmouseup, true);
	}

	if (ltr) {
		attachEventListener(ltr, 'mousedown', ttScrollLater_onmousedown, true);
		attachEventListener(ltr, 'mouseup', ttScrollLater_onmouseup, true);
	}
}

var ttScrollCurrentOffset = 0;
function onButtonTTTPExpand(url)
{
	window.location.href=url + "&itdLPxx_scrollOffset=" + ttScrollCurrentOffset;
}

function setTTScrollCurrentOffset(val)
{
	if (tableObjList && tableObjList.ttTable)
	{
		tableObjList.ttTable.contentDiv.scrollLeft=val;
		ttScrollCurrentOffset = tableObjList.ttTable.contentDiv.scrollLeft;
	}
}

function setTTScrollOffsetCurrentTime()
{
	if(ttRowElemCurTime>0)
	{
	    var bodyRow=document.getElementById('ttBR_row_1');
	    if (bodyRow)
	    {
	        var matchingElem=null;
	        if (ttRowElemCurTime>=0 && ttRowElemCurTime<=bodyRow.childNodes.length)
	        {
	        	matchingElem=bodyRow.childNodes[ttRowElemCurTime-1];
	        }
	        
	        if(matchingElem)
	        {
	        	setTTScrollCurrentOffset(matchingElem.offsetLeft-bodyRow.offsetLeft);
	        }
	    }
	}
}

function ttScrollEarlier_onmousedown (e)
{
	ttScrollCurrentOffset = tableObjList.ttTable.contentDiv.scrollLeft;
	jobs['earlier'].down = true;
	jobs['earlier'].id = window.setTimeout(ttEarlier, timeout);
}

function ttScrollEarlier_onmouseup (e)
{
	jobs['earlier'].down = false;
}

function ttScrollLater_onmousedown (e)
{
	ttScrollCurrentOffset = tableObjList.ttTable.contentDiv.scrollLeft;
	jobs['later'].down = true;
	jobs['later'].id = window.setTimeout(ttLater, timeout);
}

function ttScrollLater_onmouseup (e)
{
	jobs['later'].down = false;
}

function ttEarlier()
{
	if (tableObjList && tableObjList.ttTable) {		
		tableObjList.ttTable.contentDiv.scrollLeft = ttScrollCurrentOffset - 250;
		ttScrollCurrentOffset = tableObjList.ttTable.contentDiv.scrollLeft;
	}

	if (jobs['earlier'].down) {
		jobs['earlier'].id = window.setTimeout(ttEarlier, 20);
	}
}

function ttLater()
{
	if (tableObjList && tableObjList.ttTable) {		
		tableObjList.ttTable.contentDiv.scrollLeft = ttScrollCurrentOffset + 250;		
		ttScrollCurrentOffset = tableObjList.ttTable.contentDiv.scrollLeft;
	}

	if (jobs['later'].down) {
		jobs['later'].id = window.setTimeout(ttLater, 20);
	}
}

function ttOpositeDirection()
{	
	// We start from scratch and discard all user defined filters...
	document.forms[0].reset();

	var dir = document.getElementById('itdLPxx_selLineDir');	

	var n = dir.firstChild;
	var i = 0;

	while (n) {
		if (n.getAttribute('selected') || n.defaultSelected)
			break;
		
		n = n.nextSibling;
		i++;
	}
	
	if (dir.length > i) 
	{
		dir.selectedIndex = i==0 ? 1 : 0;
	}
	
	// Go!
	document.forms[0].submit();
}

/*
 * 
 * PREDEFINED OBJECTS
 * extend only if method is not defined elsewhere.
*/
if (typeof Function.prototype.bind !== 'function') {
 	Function.prototype.bind = function(obj) {
	  var method = this, temp = function() {
	    return method.apply(obj, arguments);
	   };
	  return temp;
	 }; 
}

function attachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.addEventListener != "undefined")
  {
	target.addEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.attachEvent != "undefined")
  {
	target.attachEvent("on" + eventType, functionRef);
  }
  else
  {
	eventType = "on" + eventType;

	if (typeof target[eventType] == "function")
	{
	  var oldListener = target[eventType];

	  target[eventType] = function()
	  {
		oldListener();

		return  functionRef();
	  }
	}
	else
	{
	  target[eventType] = functionRef;
	}
  }

  return true; 
}