//-----------------------------------------------------------------------------
// writeHTML.js
// 2005.10.11 - written by rk7138 for AT&T Communications
// 2005.10.21 - revised by rk7138 altered validateForm() calls for UVerse
// 2007.05.04 - added getFilteredElementsByClassName()
// 2007.09.17 - added clone
// 2007.10.11 - created getDescendantsFilteredByClasses()
// 2007.11.06 - added htmlToText
// 2007.11.15 - popupBigCentered returns childObj
//-----------------------------------------------------------------------------
// INFORMATION:
// provides three functions:
//
//  $ (divId)		
//  - pass in an HTML tag ID, retrieves DOM reference
//
//    EXAMPLE:
//      var elId = 'myInputElement';
//      var elObj = $ (elId);
//      var valueStr = elObj.value;
//
//
//	setInnerHTML (objDiv, givenHTML)
//	- pass in DOM reference and string, replaces HTML within the tag with string
//
//    EXAMPLE:
//      var elId = 'myInputElement';
//      var elObj = $ (elId);
//      var htmlStr = 'HELLO WORLD';
//
//      setInnerHTML (elObj, htmlStr);
//
//
//	addEvent (objElement, eventStr, objFunc)
//	- pass in function definition to be called upon window load event, will
//	  utilize the proper window.onload form
//
//    EXAMPLE:
//       function myFunc(){ alert ('hello world!'); }
//
//       addEvent(window, "load", myFunc);
//
//  getQueryParameter (givenKeyStr)
//  - pass in querystring parameter name and retrieve value of the pair, if it exists
//
//	  EXAMPLE:
//		 ASSUME URL has something like http://somedomain/cgi-bin/index.cgi?pid=9500
//       
//       var keyStr = 'pid';
//       var keyValue = getQueryParameter(keyStr);
//
//		 alert(keyStr + " = " + keyValue); //shows pid = 9500
//

// Add push() and pop() if necessary
if (typeof Array.prototype.push == 'undefined' ){
	Array.prototype.push = function( element ) { this[this.length] = element; }
}

if (typeof Array.prototype.pop == 'undefined' ){
	Array.prototype.pop = function (){ 
		var last = this[ this.length - 1 ]; this.length--; return last; 
	}
}

function $ (divId){
	var objDiv = "";

	if (document.getElementById){
		objDiv = document.getElementById(divId);
	}
	else if (document.all){
		objDiv = document.all[divId];
	}
	else if (document.layers){
		objDiv = document.layers[divId];
	}
	else {
		alert("ALERT:\nYou have an unsupported implementation of HTML DOM.");
	}

	return objDiv;
}

function setInnerHTML (givenObj, givenHTML){
	var objDiv = null;
	
	if (typeof givenObj == 'string'){ objDiv = $(givenObj); }
	else { objDiv = givenObj; }
	
	if (document.getElementById){
		objDiv.innerHTML = givenHTML;
	}
	else if (document.all){
		objDiv.innerHTML = givenHTML;
	}
	else if (document.layers){
		objDiv.document.open();
		objDiv.document.write(givenHTML);
		objDiv.document.close();
	}
}

function getInnerHTML (givenObj, bStripHtml){
	var objDiv = null;
	var outputStr;
	
	if (typeof givenObj == 'string'){ objDiv = $(givenObj); }
	else { objDiv = givenObj; }
	
	if (document.getElementById){
		outputStr = objDiv.innerHTML;
	}
	else if (document.all){
		outputStr = objDiv.innerHTML;
	}
	else if (document.layers){
		return null;
	}
	
	if (bStripHtml){
		return outputStr.replace(/(<([^>]+)>)/ig,''); 	
	}
	
	return outputStr;
}

function getOperatingForm(givenFormObj){
	var resultObj;
	
	if (givenFormObj != null){
		if (typeof givenFormObj == 'string'){ resultObj = $(givenFormObj); }
		else { resultObj = givenFormObj; }		
	}
	else { resultObj = document.forms[0]; }
	
	return resultObj;
}

function addEvent(objElement, eventStr, objFunc){

	if (objElement.addEventListener){
		window.addEventListener(eventStr, objFunc, false);
		
		return true;
	} 
	else if (objElement.attachEvent){
		var temp = objElement.attachEvent("on" + eventStr, objFunc);
		
		return temp;
 	} 
 	else {
		return false;
	}
}

		
//ASSUME [['fred','div']] or [['fred','div'],['barney','div'], ...]
//and elementsArray is optional but should be an Array of HTMLElements
function getDescendantsFilteredByClasses (searchArray, elementsArray){
	var searchSpace = elementsArray || document;
	var searchPair = [];
	var className;
	var tagName;
	var searchResults = [];

	if (!(searchArray instanceof Array)){ return null; }
	if (!(searchArray[0] instanceof Array)){ return null; }

	for (var i = 0; i < searchArray.length; i++){
		searchPair = searchArray[i];
		className = searchPair[0];
		tagName = (searchPair[1]) ? searchPair[1] : null;			

		if (searchResults.length > 0){
			searchResults = getFilteredElementsByClassName(className, tagName, searchResults);
		}
		else {
			searchResults = getFilteredElementsByClassName(className, tagName, searchSpace);
		}
	}
	
	return searchResults;
}

//ASSUME desiredClassName is space-delimited string, desiredTagName is optional, 
//and givenElements is either HTMLElement or an Array of HTMLElements
//EXAMPLE getFilteredElementsByClassName("index", "div")
function getFilteredElementsByClassName (desiredClassName, desiredTagName, givenElement) {	
	var resultArray = [];
	var searchTag = desiredTagName || "*";
	var elements = [];
	var foundElements;
	var item;
	
	if (givenElement){		
		if (givenElement instanceof Array){
			for (var i = 0; i < givenElement.length; i++){	
				foundElements = givenElement[i].getElementsByTagName(searchTag);
				
				if (foundElements && foundElements.length){
					for (var j = 0; j < foundElements.length; j++){
						item = foundElements.item(j);
						
						if (!listContains(elements, item)){ elements.push(item); }
					}					
				}				
			}
		}
		else {
			foundElements = givenElement.getElementsByTagName(searchTag);
						
			if (foundElements && foundElements.length){
				for (var j = 0; j < foundElements.length; j++){
					item = foundElements.item(j);
											
					if (!listContains(elements, item)){ elements.push(item); }
				}				
			}
		}
	}
	else {
		foundElements = document.getElementsByTagName(searchTag);
		
		if (foundElements && foundElements.length){ 
			for (var j = 0; j < foundElements.length; j++){
				item = foundElements.item(j);
				
				if (!listContains(elements, item)){ elements.push(item); }
			}
		}
	}
	
	var numElements = elements.length;
	var desiredClasses = desiredClassName.split(" ");
  
	for ( var i = 0; i < numElements ; i++ ) {
		var possibleElement = elements[i];
		var foundClassName = possibleElement.className;
		var tagName = possibleElement.tagName;

		var classList = foundClassName.split(" ");
		var numDesired = desiredClasses.length;			
		var found = 0;
		
		if (foundClassName == desiredClassName){ resultArray.push(possibleElement); continue; }
		
		for (var j = 0; j < classList.length; j++){					
			for (var k = 0; k < numDesired; k++){
				if (classList[j].toLowerCase() == desiredClasses[k].toLowerCase()){ found++; }
			}			
		}
		
		if (found == numDesired){ resultArray.push(possibleElement); }
	}
  	
	return resultArray;
}

function getQueryParameter(givenKey) {
	var queryResult = window.location.search.substring(1);
	var pairs = queryResult.split("&");
	var numPairs = pairs.length;
	
	for (var i= 0; i < numPairs; i++) {
		var pair = pairs[i].split("=");
		
		if (pair[0] == givenKey) { return pair[1]; }
	}
}


function getFunctionName(fn){
	var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/);
	return m ? m[1] : "";
}

function removeSubstring(parentStr, removeStr) {
	var index = parentStr.indexOf(removeStr);
	var resultStr = "";
	
	if (index == -1) { return parentStr; }
	
	resultStr += parentStr.substring(0, index);
	resultStr += removeSubstring(parentStr.substring(index + removeStr.length), removeStr);
	
	return resultStr;
}

function getCurrencyFormat(givenValue, addSymbol){
	var num = Math.floor(parseFloat(givenValue) * 100 + 0.5);
	var cents = num % 100;
	var dollars = Math.floor(num / 100);
	var currency = '';
	
	if(cents < 10) { cents = "0" + cents; }
	currency = dollars + "." + cents;
	
	if (addSymbol){ currency = '$' + currency; }
	
	return currency;	
}

function listContains(givenArray, givenValue){
	if (!givenArray){ return false; }
	
	var numItems = givenArray.length;

	for (var i = 0; i < numItems; i++){
		var item = givenArray[i];
		
		if (givenValue === item){ return true; }
	}
	
	return false;	
}

function getWindowSize() {
	var width
	var height;
	
	if (self.innerHeight) {
		width = self.innerWidth;
		height = self.innerHeight;
	} 
	else if (document.documentElement && document.documentElement.clientHeight) {
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	} 
	else if (document.body) {
		width = document.body.clientWidth;
		height = document.body.clientHeight;
	}
	
	return {'width': width, 'height': height};
}

function setPosition(givenId, x, y, bAbsolute, bApplyScroll){
	var elObj = $(givenId);	
	if(getStyle(givenId, 'display') != 'block'){ return; }
	
	var positionType = "relative";
	var scrollOffset = { left: 0, right: 0 };
	
	if (bApplyScroll){ scrollOffset = getScrollOffset(); }	
	if (bAbsolute){ positionType = "absolute"; }	
	
	elObj.style.position = positionType;
	var finalX = scrollOffset.left + x;
	var finalY = scrollOffset.top + y;	
	
	if (document.layers){
		elObj.moveTo(finalX + "px", finalY + "px");
	}
	else {
	    elObj.style.top = finalY + "px";
	    elObj.style.left = finalX + "px";
	}
}

function getDimensions(givenId){
	var width;
	var height;
	
	width = $(givenId).clientWidth || $(givenId).innerWidth;
	height = $(givenId).clientHeight || $(givenId).innerHeight;
	
	return { 'width': width, 'height': height };
}

function getScrollOffset() {
	//From: http://www.quirksmode.org/js/doctypes.html
	var top;
	var left;
	
	if (document.documentElement && document.documentElement.scrollTop){ 
		top = document.documentElement.scrollTop; 
		left = document.documentElement.scrollLeft;	
	}
	else if (document.body){ 
		top = document.body.scrollTop; 
		left = document.body.scrollLeft; 	
	}
	
	return {'left': left, 'top': top};
}

//TAKEN from http://www.thescripts.com/forum/thread437572.html
function htmlToText (htmlMarkup) {
	var div = document.createElement('div');
	div.innerHTML = htmlMarkup;
	
	if (typeof div.innerText != 'undefined'){ return div.innerText;	}
	else if (
		typeof div.ownerDocument != 'undefined' && 
		typeof div.ownerDocument.createRange != 'undefined') {
			
		var range = div.ownerDocument.createRange();
		range.selectNodeContents(div);
		
		return range.toString();
	}
	else if (typeof div.textContent != 'undefined') { return div.textContent; }
	else { return htmlMarkup }
}

function createElement(element) {
    if (typeof document.createElementNS != 'undefined') {
        return document.createElementNS('http://www.w3.org/1999/xhtml', element);
    }
    if (typeof document.createElement != 'undefined') {
        return document.createElement(element);
    }
    return false;
}
 
            
//selectObj is an an object literal with one or more attributes
//  [{id:, name:, size:, class:, onchange:, onclick:, title:} <,...>]
//optionsArray is an array of object literal containing value and text
//  [{value:, text:, } <,...>]
function getSelectBoxDOM(selectObj, optionsArray){
	var elementType = 'select';
	var childType = 'option';
    var selectBox = createElement(elementType);
    
    if (typeof selectObj != 'object'){ return ''; }
    if (typeof optionsArray != 'object'){ return ''; }
    if (typeof optionsArray[0] != 'object'){ return ''; }
       
    for (var i in selectObj){
    	selectBox[i] = selectObj[i];
    }				

	var numOptions = optionsArray.length;
    for (i = 0; i < numOptions; i++) {
    	var optionsObj = optionsArray[i];
    	var value = optionsObj["value"];
    	var text = optionsObj["text"];
    	
        optionItem = createElement(childType);
        optionItem.appendChild(document.createTextNode(text));
        optionItem["value"] = value;

        selectBox.appendChild(optionItem);
    }

    return selectBox;
}

//wrapper for getSelectBoxDOM
//parentId is probably ID of a tr, div, or could be body
//containerTag could be 'td', 'span', 'div', 'p'
function createSelectBox(parentId, containerTag, selectObj, optionsArray){
	var htmlStr = getSelectBoxDOM(selectObj, optionsArray);
	var container = createElement(containerTag);

	container.appendChild(htmlStr);
	container.appendChild(document.createTextNode(''));
	container.innerHTML += '';
	
	$(parentId).appendChild(container);
}

function insertAfter(childObj, newElement) {
	var parent = childObj.parentNode;
			
	parent.appendChild(newElement);
	parent.insertBefore(newElement, childObj);
}

//DOM create radio element
function addRadio (parentId) {
	if (!parentId) { return false; }
	
	parentObj = document.getElementById(parentId);
	
	if (!parentEl) { return false; }
	
	var newRadio = document.createElement("input");
	
	newRadio.type = "radio";
	newRadio.id = "myRadio"&++radioCount;
	newRadio.name = "myRadio";
	newRadio.value = "someValue";
	
	var newLabel = document.createElement("label");
	newLabel.htmlFor = "myRadio"&radioCount;
	newLabel.appendChild(document.createTextNode('someLabelText'));
	parentEl.appendChild(newRadio);
	parentEl.appendChild(newLabel);
	
	return false;
}

function popupBigCentered(URL, w, h, bClean) {
	var desiredWidth = w || (screen.width / 1.28);
	var desiredHeight = h || (screen.height / 1.28);

	var left = Math.floor((screen.width - desiredWidth)/ 2);
	var top = Math.floor((screen.height - desiredHeight)/ 2);
	var properties;
	
	if (bClean){ properties = 'toolbar=0,scrollbars=auto,location=0,statusbar=0,menubar=0,resizable=1'; }
	else { properties = 'toolbar=1,scrollbars=yes,location=1,statusbar=1,menubar=1,resizable=1'; }
	
	var childObj = window.open(URL,'ATT', properties + ',width=' + desiredWidth + ',height=' + desiredHeight + ',top=' + top + ',left=' + left + '');
	
	return childObj;
}

function winResize(w, h) {
	window.resizeTo(w, h);
	self.focus();
}

function setTextFieldAttributes(attributeName, valueStr){
	var formObj = getOperatingForm();
	var tempObj = {}
	var elTitle;
	var elType;
	var elName;
	
	for (var i in formObj){
		if (tempObj[i]){ continue; }
		
		tempObj[i] = true;
		
		elName = i;
		elementObj = formObj[elName];
		
		try {
			elType = elementObj.type;
			if (!elType){ elType = elementObj[0].type; }
		} catch(e){}
		
		if (!elType){ continue; }
		if (!( elType == 'text' || elType == 'textarea')){ continue; }
		
		elTitle = elementObj.title;
		if (elTitle){ continue; }
		
		if (elementObj.setAttribute){ elementObj.setAttribute(attributeName, valueStr); }
	}
}

//FROM quirksmode via http://www.quirksmode.org/dom/getstyles.html
// provide either ID or object reference
function getStyle(element,givenStyleName){
	var elObj = element;
	var resultStr;
				
	if (typeof element == 'string'){
		if (! $(element)){ return; }
		
		elObj = $(element);
	}
		
	if (!elObj){ return; }
	if (!givenStyleName){ return; }
	
	if (elObj.currentStyle){ resultStr = elObj.currentStyle[givenStyleName]; }
	else if (window.getComputedStyle){ resultStr = document.defaultView.getComputedStyle(elObj,null).getPropertyValue(givenStyleName); }

	return resultStr;
}

//PERFORMS deep copy
function clone(givenObj){
	var tempObj = {};
	
    if(givenObj == null || typeof(givenObj) != 'object'){ return givenObj; }
    if(givenObj.constructor == Array){
        var tempObj = [];

        for(var i = 0; i < obj.length; i++) {
            if (typeof(givenObj[i]) == 'object'){ tempObj.push(clone(givenObj[i])); }
            else { tempObj.push(givenObj[i]); }
        }

        return temp;
    }
    
    for(var key in givenObj){ tempObj[key] = clone(givenObj[key]); }
    
    return tempObj;
}

function trimWhiteSpace (givenStr) { return givenStr.replace(/^\s+|\s+$/g,'') }