/**********************************************************************************************************

	Purpose:
		This file contains javascript functions that are not Squirrelcart specific
		
	History:
		File modified on 09/19/2005 for v2.0.1 - general improvements to data grid load appearance
		File modified on 10/26/2005 - added "addRow" function
		File modified on 11/04/2005 - IE 5 and 5.5 treat a comment tag as nodeType 1, which caused problems
	
**********************************************************************************************************/

// way to grab a reference to an element via ID that
// works in all browsers	
function getRefToDivMod( divID, oDoc ) {
	if( !oDoc ) { oDoc = document; }
	if( document.layers ) {
		if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
			for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
				y = getRefToDivNest(divID,oDoc.layers[x].document); }
			return y; } }
	if( document.getElementById ) { return oDoc.getElementById(divID); }
	if( document.all ) { return oDoc.all[divID]; }
	return document[divID];
}





// purpose of function is to return the inside dimensions of the window
// returns an object with height and width properties set
function getWindowDims() {
	var x = window; 
	var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;
	var dims = new Object();
	// for NS
	if( x.innerWidth ) {
		myW = x.innerWidth; myH = x.innerHeight;
	} else if ( d && d.clientWidth ) {
		myW = d.clientWidth; myH = d.clientHeight; 
	} else if( b && b.clientWidth ) {
		// for IE
		myW = b.clientWidth; myH = b.clientHeight; 
	}
	
	if( window.opera && !document.childNodes ) { myW += 16; }
	dims.height = myH;
	dims.width = myW;
	return dims;
}




// function takes an object as a parameter, and returns
// a copy of the object
// called like this:
// myNewObj = new cloneObject(origObj);
function cloneObject(what) {

	if (what.valueOf) {
		// this does not work in IE
		return what.valueOf();
	} else {
		// this does work in IE
		for (i in what) {
			this[i] = what[i];
		}
	}
}
				
		
		
// purpose of function is to move an element in an array up or down
function moveArrayPos(arr,old_i,jump) {
	// arr 		the array
	// old_i 	the index of the element u want to move
	// jump 	a pos or neg integer representing how may moves to make in which direction
	//
	// function will return the new array
	
	// calculate new index
	new_i = old_i + jump;

	// account for fact that new index can't be above or below the top or bottom options	
	new_i = new_i < 0 ? 0 : 						// if new position is above the top option, set it to 0 (top)
			new_i > arr.length - 1 ? arr.length - 1: // if new position is below the last option, set it to the last index
			new_i;
	
	if (new_i >= 0) {
		// cut the option from the list
		cut_opt = arr.splice(old_i,1);
		// put back, in the new position
		arr.splice(new_i,0,cut_opt);
	}
	
	//alert("moving index: " + old_i + "(" + jump + "), new i: " + new_i);
	return arr;		
}

		

// purpose of function is to take an element and swap it's class on different event
// this is here, because IE doesn't support CSS pseudo classes "hover, active, etc..."
// on none <a> tags!
// elemRef is optional...if left out, the element that was moused over will get it's className swapped
// if specified, then that element will have its class swapped
// elemId is the ID of the elemnt you want to swap.
function swapClass(evtRef, elemRef, elemId) {
	
	if (!evtRef) return;	
	
	// try to grab by ID first, if elemRef is not passed
	if (!elemRef && elemId) elemRef = document.getElementById(elemId);
	
	// else, grab it from the evt. itself
	if (!elemRef) var elemRef = evtRef.target ? evtRef.target : evtRef.srcElement;

	if (!elemRef.oldClassName) elemRef.oldClassName = elemRef.className;
	
	if (evtRef.type == "mouseover" || evtRef.type == "mousedown") {
		elemRef.className = elemRef.oldClassName + "-" + evtRef.type;
	} else {
		elemRef.className = elemRef.oldClassName;
	}
	
}



// purpose is to toggle visibility of an element
function swapVis(elemRef) {
	elemRef = typeof(elemRef) == 'object' ? elemRef : document.getElementById(elemRef);

	if (elemRef.style) {
		elemRef.style.visibility = elemRef.style.visibility == 'hidden' ? 'visible' : 'hidden';
	}
}

// purpose is to toggle display of an element
function swapDisplay(elemRef) {
	elemRef = typeof(elemRef) == 'object' ? elemRef : document.getElementById(elemRef);
	
	if (elemRef.style) {
		elemRef.style.display = elemRef.style.display == 'none' ? '' : 'none';
	}
}



// submit form on enter
function submitEnter(myfield,e) {
	var keycode;
	if (window.event) {
		keycode = window.event.keyCode;
	} else if (e) {
		keycode = e.which;
	} else {
		return true;
	}
	if (keycode == 13)	{
		myfield.form.submit();
		return false;
	} else {
		return true;
	}
}



/*
Purpose:
	Swap the src of all images that are specified by the imgName var. 

Parameters:
	imgName			name of image(s) to swap src
	excludeRef		ref. to an image to exclude
	forceNewSrc		URL to use for new src, if you don't want to use the one set in the swapsrc attribute
*/
function swapAllSrc(imgName,excludeRef,forceNewSrc) {

	// grab all images with imgName
	imgs = document.getElementsByName(imgName);

	for(i=0; i < imgs.length; i++) {
		img = imgs[i];

		if(excludeRef != img) {
			newSrc = forceNewSrc ? forceNewSrc : img.getAttribute('swapsrc');
			// store current src as swapsrc
			img.setAttribute('swapsrc',img.src);
			img.src = newSrc;
		}
	}
}




function getNextElement(elemRef) {
	/*************************************************************************
		Purpose:
			Grab the next sibling node of elemRef, excluding any text, comments,
			or other non tag nodes
		
		Parameters:
			elemRef	= a element reference, OR id
	*************************************************************************/
	if (typeof(elemRef) == 'string') elemRef = document.getElementById(elemRef);
	
	if (elemRef) {
		// node Type 1 is for an element...tag only. (not a comment, text, etc...)
		nextSib = elemRef.nextSibling;
		if (nextSib) {
			if (nextSib.nodeType != 1 || nextSib.nodeName == '!') {
				nextSib = nextSib.nextSibling;
			} 
			if (nextSib) {
				if (nextSib.nodeType != 1 || nextSib.nodeName == '!') {
					nextSib = nextSib.nextSibling;
				} 
			}
			if (nextSib) {
				if (nextSib.nodeType != 1 || nextSib.nodeName == '!') {
					nextSib = nextSib.nextSibling;
				}
			}
		}
		
		if (nextSib) return nextSib;
	}
	
}


function getPreviousElement(elemRef) {
	/*************************************************************************
		Purpose:
			Grab the previous sibling node of elemRef, excluding any text, 
			comments, or other non tag nodes
		
		Parameters:
			elemRef	= a element reference, OR id
	*************************************************************************/
	if (typeof(elemRef) == 'string') elemRef = document.getElementById(elemRef);
	
	if (elemRef) {
		// node Type 1 is for an element...tag only. (not a comment, text, etc...)
		previousSib = elemRef.previousSibling;
		if (previousSib) {
			if (previousSib.nodeType != 1 || previousSib.nodeName == '!') {
				previousSib = previousSib.previousSibling;
			} 
			if (previousSib) {
				if (previousSib.nodeType != 1 || previousSib.nodeName == '!') {
					previousSib = previousSib.previousSibling;
				} 
			}
			if (previousSib) {
				if (previousSib.nodeType != 1 || previousSib.nodeName == '!') {
					previousSib = previousSib.previousSibling;
				}
			}
		}
		
		if (previousSib) return previousSib;
	}
	
}





function getLastChildElement(parentRef) {
	/*************************************************************************
		Purpose:
			Grab the last child element of parent node parentRef, excluding any text, 
			comments, or other non tag nodes
		
		Parameters:
			parentRef	= an element reference, OR id
	*************************************************************************/
	if (typeof(parentRef) == 'string') parentRef = document.getElementById(parentRef);
	
	if (parentRef) {
		// node Type 1 is for an element...tag only. (not a comment, text, etc...)
		lastChildRef = parentRef.lastChild;
		if (lastChildRef) {
			if (lastChildRef.nodeType != 1 || lastChildRef.nodeName == '!') {
				lastChildRef = getPreviousElement(lastChildRef);
			}
		
			if (lastChildRef.nodeType == 1 && lastChildRef.nodeName != '!') return lastChildRef;
		}	
	}
}





/***************************************************************************
	Purpose:
		To return a reference to the first child node that is an actual
		element (tag).
	
	Parameters:
		elemRef		- reference to element OR id
***************************************************************************/
function getFirstChildElement(elemRef) {
	
	if (typeof(elemRef) == 'string') elemRef = document.getElementById(elemRef);
	
	if (elemRef) {
		// node Type 1 is for an element...tag only. (not a comment, text, etc...)
		// IE prior to 6.0 still treats a comment as node type 1, so we add something to throw that out by nodeName
		firstChildRef = elemRef.firstChild;
		if (firstChildRef) {
			if (firstChildRef.nodeType != 1 || firstChildRef.nodeName == '!') {
				firstChildRef = firstChildRef.nextSibling;
			} 
			if (firstChildRef) {
				if (firstChildRef.nodeType != 1 || firstChildRef.nodeName == '!') {
					firstChildRef = firstChildRef.nextSibling;
				} 
			}
			if (firstChildRef) {
				if (firstChildRef.nodeType != 1 || firstChildRef.nodeName == '!') {
					firstChildRef = firstChildRef.nextSibling;
				}
			}
		}
		
		if (firstChildRef) return firstChildRef;
	}

}






/*********************************************************************************************************

	Function toggleCheckboxes()

	Purpose: 
		Toggle check box state for all fields with the given name
		
	Parameters:
		fieldName		- string - name of field, or string that occurs in the field
		state			- state - true for checked, false for unchecked
		partial			- optional. set to true to make this work for all fields that contain the string
						specified as fieldName

*********************************************************************************************************/
function toggleCheckboxes (fieldName, state, partial) {
	// grab fields...either ALL input fields, or the ones with the given name
	fields = partial ? document.getElementsByTagName('INPUT') : document.getElementsByName(fieldName);
	
	// loop through them
	for(i=0;i<fields.length;i++){
		if (
				(
					(partial && fields[i].name.indexOf(fieldName) != -1) 
					|| !partial
				)
				&& fields[i].type == "checkbox"
		) 
		{
			fields[i].checked = state;
			
			// this is for IE...without it, if you try to move this field via the DOM, it loses it's value :(
			fields[i].defaultChecked = state;
		}	
	}
}





function dumpElement(elemRef) {
	// purpose of function is to dump the element passed
	// into a table showing each prop and its value
	// this does not recurse through objects
	
	var t; // for text output from this function
	var dumpArr = new Array();
	var propArr = new Array();
	var prop;
	
	for(prop in elemRef) {
		dumpArr[prop] = elemRef[prop];
		propArr[propArr.length] = prop;
	}
	propArr.sort();
	
	t += '<html><head><style>td {font-size: 10px; font-family: tahoma}</style></head><body><table border="1">';
	
	for(i=0; i < propArr.length; i++) {
		prop = propArr[i];
		t += '<tr><td>' + prop + '</td><td>';
		if (prop == 'innerHTML' || prop == 'outerHTML') {
			t += 'HTML ...';
		} else {
			t += dumpArr[prop];
		}
		t += '&nbsp;</td></tr>';
	}
	t += '</table></body></html>';
	var newWin = window.open();
	newWin.document.write(t);		
}






/***********************************************************************
	Purpose:
		To loop through all rows in a table, and alternate the className
		
	Parameters:
		tableRef	- element reference OR id of table
		class1		- string - name of 1st class to use
		class2		- string - name of 2nd clas to use
***********************************************************************/
function altRowClass(tableRef, class1, class2) {
	var currentClass;
	
	// check if tableRef is an ID
	if (typeof(tableRef) == 'string') tableRef = document.getElementById(tableRef);
	
	// grab TBODY tag (inside <table>)
	tBodyRef = getFirstChildElement(tableRef);
	if (tBodyRef) {
		// table rows AND text nodes
		rows = tBodyRef.childNodes;
				
		if (rows) {
			// loop through children, and alternate className on the TR tags only
			// we are skipping the first row, assuming it is a header
			for(i=1; i < rows.length; i++) {
				if (rows[i].tagName == "TR") {
					currentClass = currentClass == class1 ? class2 : class1;
					rows[i].className = currentClass;
				}
			}
		}
	}
}





/********************************************************************************************************

	Function addRow
	
	Purpose: to add a row to a table before another row
	
	Parameters:
		beforeRow		ref. OR id of the row to insert the new row before
		rowTag			(string) row tag to add. Example: <tr><td>stuff</td></tr>
		
********************************************************************************************************/
function addRow(beforeRow,rowTag) {
	// if beforeRow was passed as an id, grab a ref. to that row
	if (typeof(beforeRow) == 'string') beforeRow = document.getElementById(beforeRow);
	
	//var tb 		= document.getElementById('tbl');
	//var beforeRow = document.getElementById('prod_opts_last_row');
	var tbody 	= beforeRow.parentNode;
	
	// create new div to receive the dummy table
	var dummy_div = document.createElement('div');
	
	// add dummy table to dummy div
	dummy_div.innerHTML = '<table>'+ rowTag + '</table>';
	
	// grab reference to the row inside the dummy table
	var newRow = getFirstChildElement(getFirstChildElement(getFirstChildElement(dummy_div)));

	// clone new row
	var newRowCloned = newRow.cloneNode(true);

	//	var inputs 		= newRowCloned.getElementsByTagName('INPUT');	// grab all inputs inside the fieldset
//	// loop through inputs
//	for(var i = 0; i < inputs.length; i++) {
//		if (inputs[i].type == 'checkbox') {
//			// grab ref to parent
//			parentRef = inputs[i].parentNode;
//
//			// remove node
//			removed = parentRef.removeChild(inputs[i]);
//			
//			// put it back
//			parentRef.appendChild(removed);
//			
//		}
//	}
//	
	// insert cloned row in table, right before last row
	tbody.insertBefore(newRowCloned,beforeRow);
}