//	functions.js

//	Version 1.8
//	Dated	14 December 2010

// Copyright (c) 2000 internet.com Corp. 
// http://www.webreference.com/js/
// License is granted if and only if this entire
// copyright notice is included. By Tomer Shiran.  (for launch)

function launch(newURL, newName, newFeatures, orgName) {
  var remote = window.open(newURL, newName, newFeatures);
  if (remote.opener == null)
    remote.opener = window;
  remote.opener.name = orgName;
  return remote;
}

function openNewWindow (newURL, newWidth, newHeight) {
  newWindow = launch(newURL, 
  		   "myRemote", 
		   "height=" + newHeight + ",width=" + newWidth + ",channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=no,resizable=0,scrollbars=yes,status=no,toolbar=0", 
		   "myWindow");
}

function openNewMainWindow (newURL, newWidth, newHeight) {
  newWindow = launch(newURL, 
  		   "myRemote", 
		   "height=" + newHeight + ",width=" + newWidth + ",channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes", 
		   "myWindow");
}

// the following is written by gkirk

function openOneWindow(fileURL) {
	// to open the left window when there are no frames
	newWidth = window.outerWidth;
	newHeight = window.innerHeight + 60;
	newWindowL = launch(fileURL, "myRemoteL", 
	    "height=" + newHeight + ",width=" + newWidth +
		",channelmode=0,dependent=0,directories=0," +
		"fullscreen=0,location=0,menubar=no,resizable=1," +
		"scrollbars=yes,status=no,toolbar=yes", 
	    "myWindowL");
	newWindowL.moveBy(10,0);
	return;
}
 
function swapPicture(imageIndex, pictureSource, width, height) {
    // to swap a picture from a thumbnail to the main picture
	document.images[imageIndex].width=width;
	document.images[imageIndex].height=height;
	document.images[imageIndex].src=pictureSource;
	return;
}

// used in GkSelector
var scrollToSelectionEntryCount = 0;		// do this only once
function scrollToSelection(formname, selname) {
// to bring the selected item into view
// activated onmouseover
	if (scrollToSelectionEntryCount > 0) return;
	scrollToSelectionEntryCount++;
	var myList = document.getElementById(formname);
	// get the element index for the selector
	for (var i=0; i<myList.elements.length; i++) {
		if (myList.elements[i].name == selname) {
			if(myList.elements[i].selectedIndex >= 0) {
				indexToShow = myList.elements[i].selectedIndex ;
				myList.elements[i].selectedIndex = indexToShow;
			}
		}
	}
}

// used in GkShowAndHide
function toggleDisplay(obj) {
/*	S and H are the show and hide buttons.
 *	X is the hidden input: used to maintain state during POSTs.
 */
	var el  	= document.getElementById(obj);
	var objS	= obj + "S";
	var objH	= obj + "H";
	var objX	= obj + "X";
	var elS = document.getElementById(objS);
	var elH = document.getElementById(objH);
	var elX = document.getElementById(objX);
    if ( el.style.display != 'none' ) {
	    el.style.display = 'none';
	    elS.style.display = '';
	    elH.style.display = 'none';
	    elX.value = ' ';
	    // set the cookie
	    document.cookie = obj + '=' + 'x';
		// alert(document.cookie);		// for testing
    } else {
        el.style.display = '';
        elS.style.display = 'none';
        elH.style.display = '';
        elX.value = 'none';
		// set the cookie
	    document.cookie = obj + '=' + 'none';
		// alert(document.cookie);		// for testing
    }           
}

/* * * * * * * * * * * * * * * used by GkDrawHead * * * * */
function GkDrawheadOnLoad() {
	/*	various actions on initial loading:
	 *	- positions the window in line with the previous position
	 *	- sets focus on the element with id='DrawheadFocus'
	 *	- calls GkTableGridTdInput() to make <input type='text'> elements
	 *	  the same width as their containing td or th
	 *	- calls GkDrawheadActions() for any ad hoc actions
	 */
		// ????????????  could use readCookie()
		// get the cookies
		var allcookies = document.cookie;
		// look for the start of the gkdrawheadx cookie
		var xpos = 0;
		var pos = allcookies.indexOf('gkdrawheadx=');
		if (pos != -1) {
			var start = pos + 12;
			var end = allcookies.indexOf(';', start);
			if (end == -1) end = allcookies.length;
			xpos = unescape(allcookies.substring(start, end));
		} 
		
		// look for the start of the gkdrawheady cookie
		var ypos = 0;
		var pos = allcookies.indexOf('gkdrawheady=');
		if (pos != -1) {
			var start = pos + 12;
			var end = allcookies.indexOf(';', start);
			if (end == -1) end = allcookies.length;
			ypos = unescape(allcookies.substring(start, end));
		} 

		// look for the start of the gkdrawheadloc cookie
		var loc	= '';
		var pos = allcookies.indexOf('gkdrawheadloc=');
		if (pos != -1) {
			var start = pos + 14;
			var end = allcookies.indexOf(';', start);
			if (end == -1) end = allcookies.length;
			loc = unescape(allcookies.substring(start, end));
		}
		
		// get the current location (ie: url of the current window)
		if (loc == location) {
			// scroll the window to the old position
			window.scrollTo(xpos, ypos);
		}
		
		// set focus
		if(document.getElementById('DrawheadFocus') != null) {
			document.getElementById('DrawheadFocus').focus();
		}
		
		GkTableGridTdInput();	// for <input>s in headers
		
		// call for any ad hoc actions
		//if(typeof window.GkDrawheadActions == 'function') {
		if (typeof GkDrawheadActions == 'string' &&
		eval('typeof ' + GkDrawheadActions) == 'function') {
			eval(GkDrawheadActions + '()');
		}
	}
		
function GkDrawheadOnUnload() {		// set the cookies
	// IE does not support window.pageXOffset so we need this extra code
	// obtained from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}

	// ??? could use createCookie()
	document.cookie = 'gkdrawheadx=' + escape(scrOfX);
	document.cookie = 'gkdrawheady=' + escape(scrOfY);
	document.cookie = 'gkdrawheadloc=' + escape(location);
	// alert(document.cookie);		// for testing
	
	GkTgOnUnload();			// save any relevant cookies
}

// used in GkTableGrid
function gkTableGridSubmitTool(obj, formObj) {
/*	T and F are the true and false state buttons.
 *	X is the hidden input: used to maintain state during POSTs.
 */
	var objT	= obj + "T";
	var objF	= obj + "F";
	var objX	= obj + "X";
	var elT = document.getElementById(objT);
	var elF = document.getElementById(objF);
	var elX = document.getElementById(objX);
	var	formname = formObj.name;
    if ( elT.style.display == 'none' ) {
	    elT.style.display = 'inline';
	    elF.style.display = 'none';
	    elX.value = 'inline';
	    document.forms[formname].submit();
    } else {
        elT.style.display = 'none';
        elF.style.display = 'inline';
        elX.value = 'none';
    }
}

function gkTableGridSubmit(obj, formObj) {
/*	This is the submit() in the table cells.
 */
	var objT	= obj + "T";
	var elT = document.getElementById(objT);
	var	formname = formObj.name;
	//alert(objT );
	if ( elT == null) {
		document.forms[formname].submit();
	} else if ( elT.style.display == 'inline' ) {
 		document.forms[formname].submit();
 	}
}

function GkTableGridTdInput() {
/*	Used to make the width of an <input type='text'> element the same as its
 *	containing td or th (which is named GkTd).
 */
	var listElements = new Array();
	listElements = document.getElementsByName('GkTd');
	for (var i=0; i<listElements.length; i++) {
		var subElements = listElements[i].getElementsByTagName('input');
		var width = listElements[i].offsetWidth - 2;
		// the -2 is so that table borders aren't over-written	
		for (var j=0; j<subElements.length; j++) {
			var node = subElements[j];
			var nodeType = node.getAttribute('type').toLowerCase();
			if ((nodeType == 'text') || (nodeType == 'submit')) {
				node.style.width = width + 'px';
                // remove sizing constraints
        		node.style.minWidth = null;
        		node.style.maxWidth = null;
			}
		}
	}					
}

/* * * * * * * * * * * Tables with resizable columns 
 *	Original author: Aleksandras Novikovas
 *	an@systemtier.com
 *
 *	A JavaScript function enabling the resizing of HTML table columns.
 *	The table must have <thead><tr><th>.
 *	The table must have id='valueOfTableIdProperty'.
 *	To make table resizable you must execute:
 *	<script type='text/javascript'>gkTGinstallTable('valueOfTableIdPropery')</script>
 *	AFTER the table has been rendered.
 *	On successful setup, installTable 
 *		adds a special marker ('|') to each column header element,
 *		sets onmousedown on each marker 
 *		sets onmouseup and onmousemove for the document body.
 *	You can drag this marker to resize the column.
 *	Minimum column width can be set by changing value of gkTGminWidth.
 *
 *	The sizes are stored in cookies, which expire after 1 hour.
 *	There is a cookie for each table, named gktg_valueOfTableIdProperty.
 *	The array gktgArray is an associative array indexed by 'valueOfTableIdProperty'.
 *	Each element is an indexed array of widths (px but number only) 
 *		indexed by column number (0-n).
 */
var gkTGarray 				= new Array();		// the overall column array; for all tables
var gkTGminWidth 			= 10;
var gkTGdraggingColumn 		= null;
var gkTGdraggingColumnIndex = 0; 
var gkTGstartingX 			= 0;
var gkTGcurrentX 			= 0;
var	gkTGtableId				= '';		// set to tableId by gkTGinstallTable()

function gkTGgetNewWidth () {
    var newWidth = gkTGminWidth;
    if (gkTGdraggingColumn != null) {
        newWidth = parseInt (gkTGdraggingColumn.parentNode.style.width);
        if (isNaN (newWidth)) {
            newWidth = 0;
        }
        newWidth += gkTGcurrentX - gkTGstartingX;
        if (newWidth < gkTGminWidth) {
            newWidth = gkTGminWidth;
        }
    }
    // note the column width
    gkTGarray[gkTGtableId][gkTGdraggingColumnIndex] = newWidth;
    newWidth = newWidth + 'px';
    return newWidth;
}

function gkTGcolumnMouseDown (event) {
// when the mouse is clicked over a mover handle
    if (!event) {
        event = window.event;
    }
    gkTGstartingX = event.clientX;
    gkTGcurrentX = gkTGstartingX;
    gkTGdraggingColumn = this;
    // now find the column number
    var thNode = gkTGdraggingColumn.parentNode;
    var trNode = thNode.parentNode;	
    var colNumber = 0;
    for (var i=0; i<trNode.childNodes.length; i++) {
    	if (trNode.childNodes[i].nodeName.toLowerCase() == 'th') {
    		if (trNode.childNodes[i] == thNode) {
    			// node found: note its column number
    			gkTGdraggingColumnIndex = colNumber;
    			break;
    		}
    		colNumber++;
    	}
    } 
    
    // Check whether there is an <input> element.
    // If so, set its width to 8px to allow small columns.
    var thNode = gkTGdraggingColumn.parentNode;
    for (var m=0; m<thNode.childNodes.length; m++) {
    	if (thNode.childNodes[m].nodeName.toLowerCase() == 'input' ) {
    		thNode.childNodes[m].style.width = (gkTGminWidth -2) + 'px';
    	}
    }
    return true;
}

function gkTGcolumnMouseUp () {
// when the mouse comes off the mover handle
    if (gkTGdraggingColumn != null) {
        var thNode = gkTGdraggingColumn.parentNode;
        thNode.style.width = gkTGgetNewWidth();
        for (var m=0; m<thNode.childNodes.length; m++) {
        	if (thNode.childNodes[m].nodeName.toLowerCase() == 'input' ) {
                // Check whether there is an <input> element.
		        // If so, set its width to suit.
        		var inputNode = thNode.childNodes[m];	// the input node
        		inputNode.style.width = (thNode.offsetWidth -2) + 'px';
        	} 
        }
        gkTGdraggingColumn = null;
    }
	return true;
}

function gkTGcolumnMouseMove (event) {
// when a mouse moves anywhere on the <body>
    if (!event) {
        event = window.event;
    }
    if (gkTGdraggingColumn != null) {
	    gkTGcurrentX = event.clientX;
        gkTGdraggingColumn.parentNode.style.width = gkTGgetNewWidth ();
        gkTGstartingX = event.clientX;
        gkTGcurrentX = gkTGstartingX;
	}
	return true;
}

function gkTGinstallTable (tableId) {
// Works for tables with <thead><tr><th>
	gkTGtableId = tableId;
	// read any cookie and set up array of column widths
	var gkTGarraySer = readCookie('gktg_' + gkTGtableId);
	// unserialise it into gkTGarray[valueOfTableIdProperty] - an indexed array
	//	which is indexed by column number (0-n)
	if (gkTGarraySer != undefined) {
		gkTGarray[gkTGtableId] = gkTGarraySer.split(',');
	}
	
	var table = document.getElementById (tableId);
    // Test if there is such element in the document
    if (table != null) {
        if (table.nodeName.toLowerCase () == 'table') {
        	document.body.onmouseup = gkTGcolumnMouseUp;
            document.body.onmousemove = gkTGcolumnMouseMove;
            for (var i=0; i<table.childNodes.length; i++) {
            	var tableHead = table.childNodes[i];
                if (tableHead.nodeName.toLowerCase () == 'thead') {
                	// Go through THEAD nodes and set resize markers
                    for (var j = 0; j < tableHead.childNodes.length; j++) {
                    	var trNode = tableHead.childNodes[j];
                        // Handles IE style THEAD with TR
                        if (trNode.nodeName.toLowerCase () == 'tr') {
                        	var columnNumber = 0;	// indexes columns
                        	for (var k=0; k<trNode.childNodes.length; k++) {
                            	if (trNode.childNodes[k].nodeName.toLowerCase() == 'th' ) { 
                            		var column = trNode.childNodes[k];	// the th node
                                    var marker = document.createElement('span');
                                    marker.innerHTML = '|';
                                    marker.style.cursor = 'move';
                                    marker.style.width = '1px';
                                    marker.style.fontSize = '1pt';
                                    marker.style.display = 'inline';
                                    marker.className = 'transparent_class';
                                    // If there is an <input> element, don't float right.
                                    // the following line causes a line feed before the | for non-input
                                    //marker.style.cssFloat = 'right';
                                    for (var m=0; m<column.childNodes.length; m++) {
                                    	if (column.childNodes[m].nodeName.toLowerCase() == 'input' ) {
                                    		marker.style.cssFloat = null;
                                    	}
                                    }
                                    marker.onmousedown = gkTGcolumnMouseDown;
                                    column.appendChild(marker); // append to th
                                    
                                    // set the column width if set via cookie (in gkTGarray)
                                    if ((gkTGarray != undefined) &&
                                    	(gkTGarray[gkTGtableId] != undefined) &&
                                    	(gkTGarray[gkTGtableId][columnNumber] != undefined)) {
                                    	var xx = gkTGarray[gkTGtableId][columnNumber];
                                    	column.style.width = xx + 'px';
                                    	// set the widths of any <input> elements
                                    	for (var m=0; m<column.childNodes.length; m++) {
								        	if (column.childNodes[m].nodeName.toLowerCase() == 'input' ) {
								        		var inputNode = column.childNodes[m];	// the input node
								        		inputNode.style.width = (xx -2) + 'px';
								        	} 
								        }
								      
                                    } else {
	                                    if (column.offsetWidth < gkTGminWidth) {
	                                    	xx = gkTGminWidth -2;
	                                    } else {
	                                    	xx = column.offsetWidth;
	                                    }
	                                    column.style.width = xx + 'px';
	                                    // note the column width
	                                    if (gkTGarray == undefined) {
	                                    	gkTGarray = new Array();
	                                    }
	                                    if (gkTGarray[gkTGtableId] == undefined) {
	                                    	gkTGarray[gkTGtableId] = new Array();
	                                    }
	                                    gkTGarray[gkTGtableId][columnNumber] = xx;
									}
									columnNumber++;
                                    // ensure some css
                                    column.style.whiteSpace = 'nowrap';
                                    column.style.minWidth = null;
                                    column.style.maxWidth = null;
		                        }
                			}
                        }
                    }
                    table.style.tableLayout = 'fixed';
                    // Once we have found THEAD element and updated it
                    // there is no need to go through rest of the table
                    i = table.childNodes.length;
                }
            }
        }
    }
}

function GkTgOnUnload() {
// save the column data array to a cookie 
	// serialise the data array
	var gkTGarraySer = '';
	if ((gkTGarray != undefined) && (gkTGarray[gkTGtableId] != undefined)) {
		// avoid saving blank items at the end
		var realLength = gkTGarray[gkTGtableId].length;
		while(realLength > 1) {
			if (gkTGarray[gkTGtableId][realLength-1] > 0) break;
			realLength--;
		}
		for (var i=0; i<realLength; i++) {
			gkTGarraySer += gkTGarray[gkTGtableId][i] + ',';
		}
	}
	var xx = 'gktg_' + gkTGtableId;
	createCookie(xx, gkTGarraySer, 1);
}
/* * * * * * * * * * * end of resizable columns */
	
/* * * * * * * * * * * cookie functions * * * * * * * * * */
function createCookie(name, value, hours) {
/*	This writes the cookie.
 *	It escapes the value.
 */
	if (hours) {
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	value = escape(value);
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
/*	The value is unescaped (having been escaped by createCookie().
 *	Returns null if no cookie found.
 */
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
			var xx = c.substring(nameEQ.length,c.length);
			return unescape(xx); 
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
/* * * * * * * * * * * end of cookie functions * * * * * * * * * */

	
/* * * * * * * * * * * used by GkQueryString * * * * * * * * * */
var	GkQueryString;	// global variable - query string with initial ?

function OnSubmitForm(formId) {
/*	In the <form> element, there is onSubmit="return OnSubmitForm(formId);".
 *	This causes the query string to be updated to what is in GkQueryString.
 *	GkQueryString is kept up to date by any time a change is made to the 
 *	new query string in GkQueryString(). 
 */
 	// remove any existing query string from the url
 	var url = document.forms[formId].action; // the current action url
 	var pos = url.indexOf("?");
 	if (pos >= 0) 
 		url = url.slice(0, pos);	// up to but excluding ?
 	
 	// set the new query string
 	document.forms[formId].action = url + GkQueryString;
 	return true;	// if false return, the form will not be submitted
}
