/*
 *
 * Given a standard table, inject the DOM with cruft (additional divs + tables) to make the tfoot and thead 'static'.
 * Sad that in 2007 this can't be done with straight CSS, but there you go. 
 *
 * Modelled on jquery.datagrid.js by Matthew Knight - Ajax functionality there is overkill, and it
 * doesn't support footers, so here we are.
 *
 * Copyright (c) 2007 Coutts Library Services
 * 
 *
 * jQueryDate:   9/14/07
 * jQueryAuthor: Jeff Dietrich
 *
 */
 
 jQuery.fn.couttstable = function(o){
	num = 0;

	// Build our base attributes and allow them to be overridden
	var p = {
	  someOption: false,
	  idPrefix: '__ctable',
	  activate: false,
	  width: [],
	  tableClass: ""
	};
	
	// merge defaults with user values
	jQuery.extend(p, o);		

	// call actual function, incrementing 'num' value for each call.
	return this.each(function(){
		new jQuery.couttstable(this, p, num++);
	});	
}

jQuery.couttstable = function(obj, p, num) {

	var table = obj;
	
	// elem ids
	var gSel		= 'div#' + p.idPrefix + num.toString();
	var hdivSel		= 'div#' + p.idPrefix + num.toString() + 'hdiv';
	var htblSel		= 'table#' + p.idPrefix + num.toString() + 'htbl';
	var bdivSel		= 'div#' + p.idPrefix + num.toString() + 'bdiv';
	var ldivSel		= 'div#' + p.idPrefix + num.toString() + 'loadingdiv';
	var fdivSel     = 'div#' + p.idPrefix + num.toString() + 'fdiv';
	var ftblSel		= 'table#' + p.idPrefix + num.toString() + 'ftbl';
	var bDiv;
	
	// we're going to split the table into 3: thead and tfoot create new single-row tables.
	

	// create the 'g' container, which sits just under BrowseTableContainer
	var container = '<div id="' + gSel.substring(4) + '"></div>';
	
	// append the table to it.
	jQuery(table).before(container);
	var g = jQuery(gSel);
	g.append(table);
	
	// inspect the existing table, record widths - TODO: we're using first tbody row, should use real thead?
	getWidths();
	
	var thead = jQuery('thead:first',g);
	// iterate on the 'th' elems of the thead
	jQuery('tr:first th',thead).each(function(i){
		var w = p.width[i];
		jQuery(this).width(w);  // -6
	});

	// get the width
	var tWidth = jQuery(table).width();

	// create our header table
	var hTable = document.createElement('table');
	var tHeadClone = thead.clone();

	if ($.browser.msie) { 
	    jQuery("tr", thead).attr("id", "BrowseTableHiddenHeader").css("visibility", "hidden")
	                       .css("padding", 0).css("margin", 0).css("position", "absolute").css("top", "-18px");
	}
	else { 
	    jQuery("tr", thead).attr("id", "BrowseTableHiddenHeader").css("visibility", "collapse");
	}

	jQuery(hTable)
		.attr('id', htblSel.substring(6))
		.attr('cellSpacing', jQuery(table).attr('cellSpacing'))
		.attr('cellPadding', jQuery(table).attr('cellPadding'))
		.addClass(p.tableClass)
		.addClass("scroll")
		.append(tHeadClone);
	// create header table container.

	var hDiv = document.createElement('div')
	jQuery(hDiv)
		.attr('id', hdivSel.substring(4))
		.bind('selectstart', function(){ return false; })
		.css({ overflow: 'hidden' })
		.addClass("HeaderFooterDiv header")
		.append(hTable);

		//width: (tWidth + p.scrollbarW) + 'px', 

	g.prepend(hDiv);

	// create the scrolling container for our main body table:
	bDiv = document.createElement("div")
	jQuery(bDiv)
		.attr('id', bdivSel.substring(4))
		.scroll(function(e){ gridScroll() })
		.css({ padding: '0px', margin: '0px', overflow: 'auto' })
		.css("overflow-x", "hidden")
		.append(table);
		// height: p.height + 'px',
		//, width: (tWidth + p.scrollbarW) + 'px'
	g.append(bDiv);

	// footer experimentation

	var tfoot = jQuery('tfoot:first',g);
	jQuery('tr:first th', tfoot).each(function(i) { 
		var w = p.width[i];
		jQuery(this).width(w);  // - 6
	});

	var fTable = document.createElement('table');
	var tFootClone = tfoot.clone();

	if ($.browser.msie) { 
        jQuery("tr", tfoot).attr("id", "BrowseTableHiddenFooter").css("visibility", "hidden")
                            .css("padding", 0).css("margin", 0).css("position", "absolute").css("top", "-18px");
	}
	else { 
        jQuery("tr", tfoot).attr("id", "BrowseTableHiddenFooter").css("visibility", "collapse");
	}

	jQuery(fTable)
		.attr('id', ftblSel.substring(6))
		.attr('cellSpacing', jQuery(table).attr('cellSpacing'))
		.attr('cellPadding', jQuery(table).attr('cellPadding'))
		.addClass(p.tableClass)
		.addClass("scroll")
		.append(tFootClone);
	
	var fDiv = document.createElement('div');
	jQuery(fDiv) 
		.attr('id', fdivSel.substring(4))
		.bind('selectstart', function(){ return false; })
		.css({ overflow: 'hidden' })
		.addClass("HeaderFooterDiv footer")
		.append(fTable);

	g.append(fDiv);

	if(! $.browser.msie) { 
	    /* for reasons unknown we need to setTimeout for mozilla - even 1 ms does the trick now,
	       but directly attaching the handler gives inconsistent results */
		jQuery(window).resize(function() { 
		  setTimeout(updateHeaderFooterWidth,10);
		});
	}
	else
	{ 
		jQuery(window).resize(updateHeaderFooterWidth);
	}

	function getWidths() {
		var tbody = jQuery('tbody:first',table);

//		if ($.browser.msie) { 
//		  jQuery("#BrowseTableHiddenHeader").css("display", "block");
//		}

		p.width = new Array(jQuery("#BrowseTableHiddenHeader th").length);
		//p.width = new Array(jQuery('tr:first td',tbody).length);

		jQuery("#BrowseTableHiddenHeader th").each(function(i) { 
			//console.log(i + " width: " + jQuery(this).width() + " text:" + jQuery(this).text() );
			if (i == p.width.length - 1)
			{
			  //var rawTableDiv = jQuery(bDiv).get()[0];
			  //console.log("getWidths() last column: ");
			  //console.log("tableDiv clientHeight: " + rawTableDiv.clientHeight);
			  //console.log("tableDiv scrollHeight: " + rawTableDiv.scrollHeight);
			}

            //p.width[i] = jQuery(this).width();
            var paddingLeft = jQuery(this).css("padding-left").replace("px", "");
            var paddingRight = jQuery(this).css("padding-right").replace("px", "");
            var width = jQuery(this)[0].clientWidth;
            var widthSansPaddding = width - (parseInt(paddingLeft) + parseInt(paddingRight));

		    p.width[i] = widthSansPaddding; // using clientWidth: excludes padding + margin, where jQuery width() uses scrollWidth which includes it. 

			//console.log("   width of col " + i + ": " + p.width[i]);
			//console.log("   cwidth         : " + this.clientWidth);
			//console.log(" innerwidth          : " + jQuery(this).innerWidth());

            //console.log("   width " + i + ": " + width);
			//console.log("   paddingLeft " + i + ": " + paddingLeft);
			//console.log("   paddingRight " + i + ": " + paddingRight);
			//console.log("   widthSansPaddding " + i + ": " + widthSansPaddding);
		})

//		if ($.browser.msie) { 
//		  jQuery("#BrowseTableHiddenHeader").css("display", "none");
//		}
	}

	function drawMarker(top, left, height) { 

	    jQuery(".square").remove();
	    var marker = document.createElement("div");
	    marker.className = "square";
	    marker.style.backgroundColor = "lightgrey"
	    marker.style.top = top + "px";
	    marker.style.left = left + "px";
	    marker.style.height = height + "px";
	    marker.style.zIndex = "9999";
	    marker.style.width = "100px";
	    jQuery(bDiv).append(marker);
	}

	function gridScroll() { 

	}

	function fixWidths() { 

	    getWidths();

        var thead = jQuery('thead:first',g);
	    // iterate on the 'th' elems of the thead
	    jQuery('tr:first th',thead).each(function(i){ 
	        var w = p.width[i];
	        jQuery(this).width(w);
	    });

	    var tfoot = jQuery('tfoot:last',g);
	    jQuery('tr:first th', tfoot).each(function(i) { 
		    var w = p.width[i];
		    jQuery(this).width(w);
	    });

//	    if ($.browser.msie) { 
//	        jQuery("#browseBody tr:first td").each(function(i) { 
//	            var w = p.width[i];
//		        jQuery(this).width(w);
//		        //console.log("Update width: " + w);
//	        });
//	    }
	}

	function updateHeaderFooterWidth() { 

		dbg("In updateHeaderFooterWidth() ");

		var parentPane = jQuery(bDiv).parent().parent().parent();
		var topOfPane = parentPane.offset().top;

		var hfheights = 0;
		jQuery(bdivSel).siblings().each(function(i) { 
		    //dbg("  Sibling " + jQuery(this).attr('id') + ": " + jQuery(this).height());
			hfheights += jQuery(this).height();
		});

		var topHeight = parentPane.height();
		var newHeight = topHeight - hfheights;
		jQuery(bdivSel).height(newHeight - 8); //Removed 8px from overall Coutts table height to compensate for jQuery 1.3.2 new height calculation.

		fixWidths();
		return;
	}
};

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);
