// JavaScript Document - Utils.js
//This unit contains common utility functions
//Uses Prototype.js
//Uses betterinnerhtml.js
//Uses browserdetect.js
//The bolow variables are used to replace the & and = characters pass to the server to avoid
//conflict with the & and = separators
var andCode = "(^";
var equalCode = "^|";
var numCode = "@%";

function browserWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth,myHeight];
}

function newAjaxRequest(urlStr,responseFunction,loadingFunction){
	if(loadingFunction!=null){
		new Ajax.Request(urlStr,
		{
			method:'get',
			onLoading:loadingFunction,
			onSuccess:responseFunction,
			onFailure:function(){alert('Something went wrong - null!');}
		});
	}
	else{
		new Ajax.Request(urlStr,
		{
			method:'get',
			onSuccess:responseFunction,
			onFailure:function(){alert('Something went wrong!');}
		});
	}
}

function applyResponse(obj,response){
	if (browser=="Explorer"){
		obj.innerHTML = response;
	}
	else{
		BetterInnerHTML(obj,response);
	}
}

function indexByName(selectObj,aName){
	var anIndex = 0;
	for(var x=0;x<selectObj.options.length;x++){		
		if(trim(selectObj.options[x].text)==trim(aName)){
			anIndex = x;
			break;
		}
	}
	return anIndex;
}

function insertOptionBefore(selName,optName,optValue){
  var elSel = document.getElementById(selName);
  if (elSel.selectedIndex >= 0) {
    var elOptNew = document.createElement('option');
    elOptNew.text = optName;
    elOptNew.value = optValue;
    var elOptOld = elSel.options[elSel.selectedIndex];  
    try {
      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew, elSel.selectedIndex); // IE only
    }
  }
}


function formatPhone(aPhoneStr,areaCode){
	if(areaCode.length<3){
		areaCode = "713";
	}
	var theNumbers = new Array();
	var idx = 0;
	var newPhone = "(";
	var char;
	for(var i=0; i<aPhoneStr.length; i++){
		char = aPhoneStr.charAt(i);
		if(IsNumeric(char)){
			theNumbers[idx] = char;
			idx++;
		}
	}
	if(theNumbers.length<7){
		alert("You must enter at least 7 numbers!");
		newPhone = false;
	}
	else{
		if(theNumbers.length<10){
			newPhone += areaCode+") ";
			newPhone += theNumbers[0];
			newPhone += theNumbers[1];
			newPhone += theNumbers[2];
			newPhone += "-";
			newPhone += theNumbers[3];
			newPhone += theNumbers[4];
			newPhone += theNumbers[5];
			newPhone += theNumbers[6];
		}
		else{
			newPhone += theNumbers[0];
			newPhone += theNumbers[1];
			newPhone += theNumbers[2];
			newPhone += ") ";
			newPhone += theNumbers[3];
			newPhone += theNumbers[4];
			newPhone += theNumbers[5];
			newPhone += "-";
			newPhone += theNumbers[6];
			newPhone += theNumbers[7];
			newPhone += theNumbers[8];
			newPhone += theNumbers[9];
		}
	}
	
	return newPhone;
}

function IsNumeric(sText)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
		
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;   
}

function IsAlphabetical(strValue){
  var objRegExp  = /^[a-zA-Z\u00C0-\u00ff]+$/;
  return objRegExp.test(strValue);
}

function addRowToTable(tbl,cellCt_d)
{
	var allRows = tbl.getElementsByTagName("tr");
	var lastRow = allRows.length;
	var cellCt = (cellCt_d==null) ? 1:cellCt_d;
	if(allRows.length>0){
		cellCt = allRows[0].getElementsByTagName("td").length;
		if(cellCt==0){
			cellCt = allRows[0].getElementsByTagName("th").length;
		}		
	}
	if(browser=="Firefox" && browserVersion=="2"){
		var row = tbl.insertRow(0);
	}
	else{
		var row = tbl.insertRow(lastRow);
	}
	
	for(var i=0; i<cellCt; i++){		
		row.insertCell(i);
	}

	return  lastRow;
}

function alertFormat(aStr){
	var regEx = new RegExp ('<br/>', 'gi') ;
	var result = aStr.replace(regEx, "\n");
	regEx = new RegExp ('<br />', 'gi') ;
	result = result.replace(regEx, "\n");
	return result;
}

function isNumberKey(evt){
	var result;
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if (charCode > 31 && (charCode < 48 || charCode > 57)){
	 result = false;
	}
	//Allow arrow keys, Home, End and Del and Backspace
	if((charCode>=35 && charCode<=40)||(charCode==46)||(charCode==8)||(charCode==9)||(charCode==13)){
	 result = true;
	}
	if(IsNumeric(String.fromCharCode(charCode))){
		result = true;
	}
	return result;
}

function isAlphaKey(evt){
	var result=false;
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8){
	 result = true;
	}
	//Allow arrow keys, Home, End and Del and Backspace and Space
	if((charCode>=35 && charCode<=40)||(charCode==46)||(charCode==8)||(charCode==9)||(charCode==13)||(charCode==32)){
	 result = true;
	}
	return result;
}

function isAlphaNumKey(evt){
	if(isAlphaKey(evt) || isNumberKey(evt)){
		return true;
	}
	else{
		return false;
	}
}

function isPhoneNumberKey(evt){
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	var isNumber = isNumberKey(evt);
	var validKey = false;
	if(isNumber){
		validKey = true;
	}
	else{
		if(charCode==40 || charCode==41 || charCode==45 || charCode==46 || (charCode>31 && charCode<41)){
			validKey = true;
		}
	}
	return validKey;
}

function isEmailKey(evt){
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	var isNumber = IsNumeric(String.fromCharCode(charCode))
	var isAlpha = IsAlphabetical(String.fromCharCode(charCode));
	if(isNumber || isAlpha){
		return true;
	}
	else{
		if(charCode==41 || charCode==44 || charCode==46 || charCode==58 || charCode==59 || charCode==64 || charCode==91 || charCode==93 || charCode==33 || charCode==35 || charCode==36 || charCode==37 || charCode==38 || charCode==39 || charCode==42 || charCode==43 || charCode==45 || charCode==47 || charCode==61 || charCode==63 || charCode==94 || charCode==95 || charCode==123 || charCode==125 || charCode==126){
			return true;
		}
		//Allow arrow keys, Home, End and Del and Backspace
		if((charCode>=35 && charCode<=40)||(charCode==46)||(charCode==8)||(charCode==9)||(charCode==13)){
		 return true;
		}
	}
	return false;
}

function keyPressed(charCode,e){
	var result = false;
	var code = (window.event) ? event.keyCode : e.keyCode;
	if (code==charCode){
		result = true;		
	}
	return result;
}

function capFirstLetter(e) {
	var code = (window.event) ? event.keyCode : e.keyCode;
	if (code!=32 && code!=8){
		var val = this.value;
		var newVal = '';
		val = val.split(' ');
		var spc = val.length>1?' ':'';
		for(var c=0; c < val.length; c++) {
			if(c==(val.length-1)){ spc='';}
			newVal += val[c].substring(0,1).toUpperCase()+val[c].substring(1,val[c].length)+spc;
		}
		this.value = newVal;
	}
}

function cleanValueStr(aStr){
	aStr = aStr.replace(/&/g,andCode);
	aStr = aStr.replace(/=/g,equalCode);
	aStr = aStr.replace(/#/g,numCode);
	return aStr;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}

function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

/* CLOSED_IMAGE - the image to be displayed when the sublists are closed
 * OPEN_IMAGE   - the image to be displayed when the sublists are opened
 */
CLOSED_IMAGE='images/plus2.png';
OPEN_IMAGE='images/minus2.png';

/* makeCollapsible - makes a list have collapsible sublists
 * 
 * listElement - the element representing the list to make collapsible
 */

function makeCollapsible(listElement){

  // removed list item bullets and the sapce they occupy
  listElement.style.listStyle='none';
  listElement.style.marginLeft='0';
  listElement.style.paddingLeft='0';

  // loop over all child elements of the list
  var child=listElement.firstChild;
  while (child!=null){

    // only process li elements (and not text elements)
    if (child.nodeType==1){

      // build a list of child ol and ul elements and hide them
      var list=new Array();
      var grandchild=child.firstChild;
      while (grandchild!=null){
        if (grandchild.tagName=='OL' || grandchild.tagName=='UL'){
          grandchild.style.display='none';
          list.push(grandchild);
        }
        grandchild=grandchild.nextSibling;
      }

      // add toggle buttons
      var node=document.createElement('img');
      node.setAttribute('src',CLOSED_IMAGE);
      node.setAttribute('class','collapsibleClosed');
      node.onclick=createToggleFunction(node,list);
      child.insertBefore(node,child.firstChild);

    }

    child=child.nextSibling;
  }

}

/* createToggleFunction - returns a function that toggles the sublist display
 * 
 * toggleElement  - the element representing the toggle gadget
 * sublistElement - an array of elements representing the sublists that should
 *                  be opened or closed when the toggle gadget is clicked
 */
function createToggleFunction(toggleElement,sublistElements){

  return function(){

    // toggle status of toggle gadget
    if (toggleElement.getAttribute('class')=='collapsibleClosed'){
      toggleElement.setAttribute('class','collapsibleOpen');
      toggleElement.setAttribute('src',OPEN_IMAGE);
    }else{
      toggleElement.setAttribute('class','collapsibleClosed');
      toggleElement.setAttribute('src',CLOSED_IMAGE);
    }

    // toggle display of sublists
    for (var i=0;i<sublistElements.length;i++){
      sublistElements[i].style.display=
          (sublistElements[i].style.display=='block')?'none':'block';
    }

  }

}

function ElementPosition(param){
	var x=0, y=0;
	var obj = (typeof param == "string") ? document.getElementById(param) : param;
	if (obj) {
		x = obj.offsetLeft;
		y = obj.offsetTop;
		var body = document.getElementsByTagName('body')[0];
		while (obj.offsetParent && obj!=body){
			x += obj.offsetParent.offsetLeft;
			y += obj.offsetParent.offsetTop;
			obj = obj.offsetParent;
		}
	}
	this.x = x;
	this.y = y;
}

function stripAlphaChars(pstrSource) 
{ 
	var m_strOut = new String(pstrSource); 
    m_strOut = m_strOut.replace(/[^0-9]/g, ''); 

    return m_strOut; 
}

function addNewListValue(aValueName,aListID){
	var newValue;
	if(newValue=prompt("Type a New "+aValueName,"")){
		var obj=document.getElementById(aListID);
		var exists=false;
		for(var i=0; i<obj.options.length; i++){
			if(obj.options[i].text.toLowerCase()==newValue.toLowerCase()){
				exists=true;
			}
		}
		if(exists){
			alert("The "+aValueName+" already exists! Please try again.");
			onAddPrefixClick();
		}
		else{
			return newValue;
		}
	}
	return false;
}


