
/*NOTE: this Javascript depends on MooTools 1.2.1 for functionality*/

function BuildMirrorHeader(tableID, numRows, widthKey, className, selectorID, selectDefStr) {
	/*Style with a class named .mirrorHeader */
	if(!tableID || !numRows) return;
	
	var table    = $(tableID);
	var parent   = table.getParent();
	var rows     = table.getElements('tr');
	var copyRows = Math.min(numRows, rows.length);
	var tempWidth;
	var clone;
	var cloneCells;
	var keyCells;
	var selector = table.getElementById(selectorID);
	
	var newTable = new Element('table');
	var newBody  = new Element('tbody');

	newTable.id  = table.id+'Mirror';
		
	newTable.grab(newBody);

	
	tempWidth = table.offsetWidth;
	tempWidth%2 ? tempWidth-=1 : tempWidth; //insure even number
	table.style.width = tempWidth+'px'; //insure width matches

	className ? newTable.className = className : false;
	newTable.style.width 	= table.style.width;
	newTable.style.position = 'fixed';
	newTable.style.left  	= '-9999px';
	newTable.style.top   	= '0px';
	newTable.cellSpacing 	= table.cellSpacing;
	newTable.cellPadding 	= table.cellPadding;
	newTable.setProperty('shown', 0);
	newTable.store('left',table.offsetLeft);
	newTable.setStyle('margin-left', table.offsetLeft+'px');
	
	if(Browser.Engine.trident4) { //IE6
		newTable.setStyle('position', 'absolute');
		newTable.store('top', parent.getPosition().y);
	}
	
	//Copy rows and insure cell widths match
	for(i = 0; i < copyRows; i++) {
			clone = rows[i].clone();
			keyCells = rows[i].getElements('th');
			if(!keyCells) keyCells = rows[i].getElements('td');
			cloneCells = clone.getElements('th');
			if(!cloneCells) cloneCells = clone.getElements('td');
		
			if(i == widthKey - 1) {
				for(j = 0; j < keyCells.length; j++) {
					cloneCells[j].width = getActualWidth(keyCells[j]);
				}
			}
			newBody.grab(clone);
	}
		
	parent.grab(newTable);
	
	
	BuildSelect(table, selector, newTable, selectDefStr, 1);
	//Prepare select tag if it is in mirror
	if(selector) {
		var newSelect = newTable.getElement('select');
		newSelect.id = selector.id+'Mirror';
	 	BuildSelect(table, newSelect, newTable, selectDefStr, 1);
	}

	
	window.addEvent('scroll',displayTableHeader.pass([table, newTable]).bindWithEvent());
	window.addEvent('mousewheel',displayTableHeader.pass([table, newTable]).bindWithEvent());
	window.addEvent('domready', BindTableAnchorEvents.bindWithEvent(window, [table, newTable]));
	displayTableHeader(table, newTable); //run once on load to see if page is in position to display
}

	
function BindTableAnchorEvents(obj, table, header) {
	var anchors = document.getElements('a[href^=#]');
	var internalIDs = table.getElements('*[id]');
	var a;
	var i;
	var ref;
	
	for(a = 0; a < anchors.length; a++) {
		ref = anchors[a].get('href').substring(1,anchors[a].get('href').length);
		if(ref == table.id) {
			anchors[a].addEvent('click', jump.bindWithEvent(anchors[a], [table]));	
		}
		else {
			for(i = 0; i < internalIDs.length; i++) {
				if(ref == internalIDs[i].id) {
					anchors[a].addEvent('click', jump.bindWithEvent(anchors[a], [table, header]));	
				}
			}
		}
	}
}
/***NEED TO UPGRADE THESE NEXT TWO FUNCTIONS ***/

function getActualWidth(cell) {
	var width = cell.getSize().x;
	var padR  = Math.round(parseFloat(actualStyle(cell, 'paddingRight', 'padding-right')));
	var padL  = Math.round(parseFloat(actualStyle(cell, 'paddingLeft', 'padding-left')));
	
	width = width - padR - padL;

	return width;
}


function actualStyle(el, cssproperty, csspropertyNS) {
	if (el.currentStyle) { //if IE5+
		return el.currentStyle[cssproperty]
	} 
	else if (window.getComputedStyle) { //if NS6+
		var elstyle=window.getComputedStyle(el, "")
		return elstyle.getPropertyValue(csspropertyNS)
	}
}
	
function displayTableHeader(table, mirror) {
	var curYPos   = window.getScroll().y;
	var tableTop = table.getPosition().y - 1;
	var tableBottom = tableTop + table.getSize().y;
	var dif       = (curYPos > tableTop && curYPos < tableBottom) ? (tableBottom - curYPos) : 0; 
	if(dif <= 0 && !mirror.shown) return;

	var isIE6 = Browser.Engine.trident4;
	var mirrorHgt = mirror.getSize().y;
	var leftShift = window.getScroll().x;
	var edge  = dif - mirrorHgt;
	var topShift = mirror.getParent().getPosition().y + mirrorHgt;

	if(isIE6) { //IE6
		mirror.setStyle('top', window.getScroll().y-mirror.retrieve('top')-1);
		mirror.shown = mirror.shown.toInt(); //correct IE6 error
	}
 	if(dif > 0 && !mirror.shown) { //enter table
		if(edge < 0) {
			mirror.setStyles({position: 'absolute', top: (tableBottom - topShift)+'px'});
		}	
		if(leftShift && mirror.getStyles('position') == 'fixed') {
			mirror.setStyle('margin-left', mirror.retrieve('left')-leftShift+'px')
		}
		
		
		mirror.setStyle('left', 'auto');
		mirror.shown = 1;
		window.addEvent('resize',displayTableHeader.pass([table, mirror]).bindWithEvent());
	}
	else if (dif <= 0 && mirror.shown) { // leave table
		if(!isIE6) {
			mirror.setStyles({position: 'fixed', left: '-9999px', top: '0px'});	
		}
		else {
			mirror.setStyles({left: '-9999px', top: '0px'});	
		}
		mirror.shown = 0;
		window.removeEvent('resize',displayTableHeader);
	}
	else if (mirror.shown) { //in table
		if(edge < 0) {
			mirror.setStyles({position: 'absolute', top: (tableBottom - topShift)+'px', marginLeft: mirror.retrieve('left')+'px'});
		}
		else if(!isIE6) {
			mirror.setStyles({position: 'fixed', top: '0px', marginLeft: mirror.retrieve('left')-leftShift+'px'});	
		}
	}
}


/*This function expects a table to obtain ID's for selector and 
the id of the select tag itself*/
function BuildSelect(table, selector, header, defStr, row) {
	//Process manidtory variables
	if (!table || !selector) return;

	var ids;
	var opt;
	
	if(row) { //ids tied to rows
		ids = table.getElements('tr[id]');
	}
	else { //ids tied to cells
		ids = table.getElements('td[id]');
	}

	//Build Selector
	if(defStr) {
		opt = new Element('option',
			{
				'html': defStr,
				'value': ''
			}
		);
		
		selector.grab(opt);
	}
	


	for (i = 0; i < ids.length; i++) {
		opt = new Element('option',
				{
					'html': ids[i].id,
					'value': ids[i].id
				}
			);
		selector.grab(opt);
	}
	
	if(selector.getStyle('display') == 'none') selector.setStyle('display', 'inline');
	window.addEvent('domready', BindSelectorEvent.bindWithEvent(window, [selector, table, header, defStr]));
	
}

function BindSelectorEvent(obj, selector, table, header, defStr) {
	selector.addEvent('change', jump.bindWithEvent(selector, [table, header, defStr]));
}

function jump(obj, table, header, def) {
		
		var isIE6 = Browser.Engine.trident4;
		var isAnchor = this.nodeName.toLowerCase() == 'a';
		var adjust;
		var target;
		var fxScroll;
		var distance;	
		var isTable = 0;
		
		header ? adjust = header.getSize().y - 1 : adjust = 0;
		
		if(!isAnchor) {
			if(this.selectedIndex.value == '' || !table) {
				if(def) this.selectedIndex = 0;
				return true;
			}		
			target = document.getElementById(this.options[this.selectedIndex].value);
		}
		else {
			if(!table) return true;
			target = document.getElementById(this.get('href').substring(1,this.get('href').length));
		}
		
		if(!table.getElementById(target.id)) isTable = 1; //if target is table itself
		target = target.getPosition().y
		target -= adjust;
		distance = Math.abs(window.getScroll().y - target);
		 
		if(!isIE6 && !isTable) {
			fxScroll = new Fx.Scroll(window, {duration: distance+200, transtion: 'quint'}).start(window.getScroll().x, target);
		}
		else { 
			fxScroll = new Fx.Scroll(window).set(window.getScroll().x, target);
		}
		if(def && !isIE6 && !isAnchor) this.selectedIndex = 0;
		return false;
	}