
// a common function to string objects:
String.prototype.trim = function() { 
	return this.replace(/^\s+|\s+$/, ''); 
};
String.prototype.startsWith = function(s) { 
	return this.indexOf(s)==0; 
};

function addEvent(o, e, f) {
   if(o.addEventListener) {
      o.addEventListener(e, f, true);
      return true;
      }
   else if(o.attachEvent) {
      return o.attachEvent("on" + e, f);
      }
   else {
      return false;
      }
   }


function pcngIsNull(o){
	return o==null || (typeof o == 'undefined');
}

function pcngIsEmpty(o){
	if(pcngIsNull(o))
		return true;
	o=(""+o);
	o=o.trim();
	return o.length==0;
}

function isDebugJS(){
	if(typeof debugJS == 'undefined'){
		return false;
	}
	return true;
}

function getDebugJS(){
	if(typeof debugJS == 'undefined'){
		return null;
	}
	return debugJS;
}

function getDebugJSLevel(){
	if(isDebugJS()){
		var level=parseInt(debugJS);
		if(!isNaN(level)){
			return level;
		}
		return 100;
	}
	
	return 0;
}

function object2String(anObject){
	var str="";
	for(var i in anObject)
		str+=i+"="+anObject[i]+"; ";
	return str;
}

function copyInto(from, to){
	for(var i in from)
		to[i]=from[i];
}


function ptpDisplayObject(anObject){
	alert(anObject+" has: \n"+object2String(anObject));
}

function visitNodes(aNode, visitorFunc){
	if(visitorFunc(aNode)==false)
		return;
	for(var i=0;i<aNode.childNodes.length;i++){
		visitNodes(aNode.childNodes[i], visitorFunc);
	}
}

function findNodeById(aNode, theId){
	for(var i=0;i<aNode.childNodes.length;i++){
		if(aNode.childNodes[i].id && aNode.childNodes[i].id==theId){
			return aNode.childNodes[i];
		}
	}
	for(var i=0;i<aNode.childNodes.length;i++){
		var found=findNodeById(aNode.childNodes[i], theId);
		if(found!=null)
			return found;
	}
	
	return null;
}

function findNodeByClass(aNode, className){
	var nodesFound=new Array();
	if(!aNode)
		return nodesFound;
	for(var i=0;i<aNode.childNodes.length;i++){
		if(aNode.childNodes[i].className!=null && (aNode.childNodes[i].className+'').indexOf(className)>=0){
			nodesFound[nodesFound.length]=aNode.childNodes[i];
		}
	}
	for(var i=0;i<aNode.childNodes.length;i++){
		var found=findNodeByClass(aNode.childNodes[i], className);
		if(found!=null){
			for(var j=0;j<found.length;j++)
				nodesFound[nodesFound.length]=found[j];
		}
	}

	if(nodesFound.length==0)
		return null;	
	return nodesFound;
}

function getKeycode(e){
	if (window.event)
	   return window.event.keyCode;
	else if (e)
	   return e.which;
}

function isEnterPressed(e){
	return getKeycode(e)==13;
}

function isEscPressed(e){
	return getKeycode(e)==27;
}
function isTabPressed(e){
	return getKeycode(e)==9;
}

function processKeyPressNumbersOnlyEvent(event){

	if(this.numbersOnly || (this.getAttribute && this.getAttribute("numbersOnly")))
	{
	        
			if(isNumberKeyPressed(this, event, this.value, this.positiveOnly || (this.getAttribute && this.getAttribute("positiveOnly")))){
				if(this.currencyField || (this.getAttribute && this.getAttribute("currencyField")))
				{
				 //if(validateCurrency(this.value))
				 //return false;
				 
				}
				return true;
			}
			else{
				return false;
			}
		}
	return true;
}
function processKeyPressEvent(event){

	if(isEnterPressed(event)){
		if(this.type=="button" || this.type=="submit"){
			// let default handle it:
			return true;
		}
		if(this.type!="textarea" && this.form){
			this.form.submit();
			return false;
		}
	}

	if(!processKeyPressNumbersOnlyEvent.call(this, event))
		return false;

	if(this.form && isTextKey(getKeycode(event)))
		this.form.dirty=true;

	return true;
}
function isNumberKeyPressed(myfield, e, currentValue, allowNegative)
{
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;

	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   return true;
	   
	keychar = String.fromCharCode(key);
	
	// numbers
	if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	else if (keychar == "."){
		if(currentValue){
			if(currentValue.indexOf(".")>=0){
				return false;
			}
		}
	    return true;   
	}
	else if(keychar=='-' && (typeof allowNegative != 'undefined') && allowNegative){
		return true;
	}
	else
	   return false;   
}

function isTextKey(keycode){
	switch(keycode){
	case 8: // back space
	case 9: // tab:
	case 13: // enter
	case 18: // alt
	case 17: // ctrl:
	case 16: // shift:
	case 19: // page/break
	case 20: // CAPS
	case 27: // esc
	case 33: //page up
	case 34: // page down
	case 35: // end
	case 36: // home
	case 37: // left arrow
	case 38: // up
	case 39: // right arrow
	case 40: // down
	case 45: //	insert
	case 46: // delete
	case 32:
	case 92: // windows key
	case 93: // 
	case 144: // num lock	
		return false;;
	default:
		if(112<=keycode && keycode<=123)	// F1 - F12
			return false;
		// regular keypress ...
		return true;
	}
}

function findChildById(aNode, theId){
	if(aNode){
		if(aNode.id){
			if(aNode.id==theId)
				return aNode;
		}
		if(aNode.childNodes){
			for(var i=0;i<aNode.childNodes.length;i++){
				
				var tmp=findChildById(aNode.childNodes[i], theId);
				if(tmp!=null)
					return tmp;
			}
		}
	}
	return null;
}

function findParentById(aNode, theId){
	if(aNode.parentNode){
		if(aNode.parentNode.id){
			if(aNode.parentNode.id==theId)
				return aNode.parentNode;
		}
		return findParentById(aNode.parentNode, theId);
	}
	return null;
}

function findParentByType(aNode, nodeName){
	if(aNode.parentNode){
		if(aNode.parentNode.nodeName){
			if(aNode.parentNode.nodeName==nodeName.toUpperCase())
				return aNode.parentNode;
		}
		return findParentById(aNode.parentNode, nodeName);
	}
	return null;
}

function walkTree(node, callBackFunc){
	return walkTree_internal(node, callBackFunc);
}

function walkTree_internal(node, callBackFunc){
	if(node && node.childNodes){
		for(var i=0;i<node.childNodes.length;i++){
			var b;
			try{
				b=callBackFunc(node.childNodes[i]);
			}
			catch(err){}
			if(typeof b == 'undefined' || b){
				if(!walkTree_internal(node.childNodes[i], callBackFunc))
					return false;
			}
			else
				return false;
		}
	}
	
	return true;
}

function myTimer(callBackFunc){
	var startTime=new Date();
	callBackFunc();
	alert("Used "+((new Date()).getTime()-startTime.getTime())/1000+" seconds.");
}

function hasFocusInMe(node){
	var curElement=document.activeElement;
	while(curElement){
		if(curElement==node){
			return true;
		}
		curElement=curElement.parentNode;
	}
	
	return false;
}

var tmpFocusStartPoint=null;
function toFocusPoint(fromNode, async){
	if(async){
		tmpFocusStartPoint=fromNode;
		setTimeout("toFocusPoint_Internal();", 350);
		return;
	}
	toFocusPoint_Internal(fromNode);
}

function toFocusPoint_Internal(fromNode){
	if(typeof fromNode == 'undefined')
		fromNode=tmpFocusStartPoint;
		
	var focused=false;
	walkTree(fromNode, function(node){
		if(node.focus && !node.disabled && !node.readOnly && node.style.display!='none' && (node.getAttribute && node.getAttribute("focus_point"))){
			try{
				node.focus();
				focused=true;
				return false;	// no more walking.
			}
			catch(exx){
				if(isDeubgJS()){
					alert("delay set focus failed. "+ex);
				}
			}
		}
		
		return true;
	});  
	
	if(!focused){
		try{
			fromNode.focus();
		}
		catch(ex){
			if(isDebugJS()){
				alert("set focus failed. "+ex);
			}
		}
	}
}

function getTopLeft(anElment){
	var left=0;
	var top=0;
	while(anElement!=null){
		left+=anElment.offsetLeft;
		top+=anElement.offsetTop;
		anElement=anElement.offsetParent;
	}
	
	return {top:top, left:left};
}

function makeFixLenStr(str, len){
	if(str.length>len)
		str=str.substr(0, len-3)+'...';
	else{
		while(str.length<len)
			str+='&nbsp;';
	}
	return str;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
		
	return (((sign)?'':'-') + num + '.' + cents);
}

function validateCurrency(v){
	v=''+v;
	var index=v.indexOf('.');
	if(index>=0){
		if(index<v.length-3){
			return "A valid currency value can contain maximum 2 digits.";
		}
	}
	
	return null;
}

function parseBoolean(s){
	if(!s)
		return false;
	s=s.toString().toLowerCase();
	return s == "true" || s == "yes" || parseInt(s) > 0;
}

var waitWindow=null;
function showWaitWindow(){
	if(!waitWindow){
		waitWindow=document.getElementById('waitingWindow');
		if(waitWindow){
			waitWindow.waitWindowTicker=0;
			waitWindow.waitWindowMsg=findChildById(waitWindow, 'waitingWindowMsg');
			if(waitWindow.waitWindowMsg)
				waitWindow.waitWindowMsg.waitMsgTime=0;
		}
	}
	if(waitWindow){
		if(typeof waitMsgList != "undefined" && waitMsgList && waitMsgList.length>0){
			if(waitWindow.waitWindowMsg){
				var now=new Date();
				if(((now.getTime())-waitWindow.waitWindowMsg.waitMsgTime)>2000){
					waitWindow.waitWindowMsg.innerHTML=waitMsgList[Math.floor(Math.random() * waitMsgList.length)];
					waitWindow.waitWindowMsg.waitMsgTime=now.getTime();
				}
			}
		}
		waitWindow.style.display="block";
		if(waitWindow.waitWindowTicker<0)
			waitWindow.waitWindowTicker=0;
		waitWindow.waitWindowTicker++;
	}
}
function cancelWaitWindow(){
	if(waitWindow){
		waitWindow.waitWindowTicker--;
		if(waitWindow.waitWindowTicker<=0)
			waitWindow.style.display="none";
	}
}

function isIE(){
	return navigator.appName == "Microsoft Internet Explorer";
}

function isMoz(){
	return navigator.appName == "Netscape";
}

function addParm(url, name, value){
	if(url.indexOf("?")<0)
		url+="?";
	else
		url+="&";
	url+=name+"="+value;
	
	return url;
}


var domTemplates=new Array();
function ptpCreateElement(typeName){
	typeName=typeName.toUpperCase();
	if(!domTemplates[typeName])
		domTemplates[typeName]=document.createElement(typeName);
		
	return domTemplates[typeName].cloneNode(false);
}
function ptpInsertCell(aRow){
	var aCell=ptpCreateElement("TD");
	aRow.appendChild(aCell);
	return aCell;
}
function ptpInsertRow(aTable){
	return aTable.insertRow(-1);
//	var aRow=ptpCreateElement("TR");
//	aTable.appendChild(aRow);
//	return aRow;
}

function alternateTableRows(aTable, firstRowIsHead, noneVisibleRowAction){
	alternateTableRowsExt(aTable, firstRowIsHead, noneVisibleRowAction, "normalRow", "alternateRow");
}

function alternateTableRowsExt(aTable, firstRowIsHead, noneVisibleRowAction, normalRowClass, alternateRowClass){
	if(!aTable)
		return;
	var startingRow=0;
	if(firstRowIsHead){
		aTable.rows[0].className="sectionTitle";
		startingRow=1;
	}
	
	var normalRowNow=true;
	var alternatingStarted=false;
	for(var i=startingRow;i<aTable.rows.length;i++){
		if(hasClass(aTable.rows[i], 'sectionTitle') || hasClass(aTable.rows[i], 'tableTitle') || hasClass(aTable.rows[i], 'pageTitle')){
			normalRowNow=true;
			continue;
		}

		if(aTable.rows[i].style.display=='none'){
			if(!noneVisibleRowAction)
				continue;
			else{
				if(noneVisibleRowAction=='normal'){
				}
				else if(noneVisibleRowAction=='followPrevious' && alternatingStarted){
					normalRowNow=!normalRowNow;
				}
			}
		}

		removeClass(aTable.rows[i], normalRowClass);
		removeClass(aTable.rows[i], alternateRowClass);
		addClass(aTable.rows[i], normalRowNow?normalRowClass:alternateRowClass);
			
		if(aTable.rows[i].style.display=='none' && noneVisibleRowAction=='followNext'){
			// no alternating.
		}
		else{
			normalRowNow=!normalRowNow;
		}
		
		alternatingStarted=true;
	}
}

function hasClass(node, clz){
	if(node.className==clz)
		return true;
	if(node.className.indexOf(clz+" ")>=0)
		return true;
	if(node.className.indexOf(" "+clz)>=0)
		return true;
		
	return false;
}

function addClass(node, toAdd){
	if(pcngIsNull(node.className)){
		node.className=toAdd;
	}
	else if(!hasClass(node, toAdd)){
		node.className+=" "+toAdd;
	}
}

function removeClass(node, clz){
	if(pcngIsNull(node))
		return;
	if(pcngIsNull(node.className))
		return;
	if(node.className==clz)
		return node.className="";
	
	var str=node.className+'';
	var index=str.indexOf(clz+" ");	
	if(index>=0)
		node.className=str.substr(0,index)+str.substr(index+clz.length+1);
	var index=str.indexOf(" "+clz);	
	if(index>=0)
		node.className=str.substr(0,index)+str.substr(index+clz.length+1);
}

function formatPhoneNumber(pnumber){
	var countryCode=null;
	if(pnumber.length==11){
		countryCode=pnumber.substr(0,1);
		pnumber=pnumber.substr(1);
	}
	
	var areaCode=null;
	if(pnumber.length==10){
		areaCode=pnumber.substr(0, 3);
		pnumber=pnumber.substr(3);
	}
	
	var exchangeNumber=pnumber.substr(0,3);
	pnumber=pnumber.substr(3);
	
	var extNum=pnumber;
	
	var str='';
	if(countryCode!=null)
		str+=countryCode+"-";
	if(areaCode!=null)
		str+="("+areaCode+") ";
	return str+=exchangeNumber+"-"+extNum;
	
}

var generalMessageDiv=null;
var default_general_msg_timeout=12000;
var default_important_msg_timeout=60000;
function getGeneralMessageDiv(){
	if(generalMessageDiv==null)
		generalMessageDiv=document.getElementById("generalMessagesDiv");
		
	return generalMessageDiv;
}
function displayGeneralMessage(message){
	return displayGeneralMessage(message, default_general_msg_timeout);
}
function displayGeneralMessage(message, timeout){
	var aa=new Array();
	aa.push(message);
	if(!timeout)
		timeout=default_general_msg_timeout;
	return displayGeneralMessages(aa, timeout);
}

function displayGeneralMessages(messages, timeout){
	if(!timeout)
		timeout=default_general_msg_timeout;
	return displayGeneralMessagesEx(messages, timeout);
}

function displayGeneralMessagesEx(messages, timeout){		
	return displayGeneralMessagesEx2(messages, timeout, getGeneralMessageDiv());
}

function displayImportantMsg(msg){
	return displayImportantMsg(msg, default_important_msg_timeout);
}
function displayImportantMsg(msg, timeout){
	var aa=new Array();
	aa.push(msg);
	return displayImportantMsgArray(aa, timeout);
}
function displayImportantMsgArray(msgs, timeout){
	return displayGeneralMessagesEx2(msgs, timeout, document.getElementById('importantInfoDiv'));
}

function displayGeneralMessagesEx2(messages, timeout, msgDiv){
	if(messages==null || messages.length==0)
		return;
		
	var createdAt=null;
	for(var i=0;i<messages.length;i++){
		if(messages[i]=='')
			continue;
		var liMsg=document.createElement("LI");
//		liMsg.appendChild(document.createTextNode(messages[i]));
		liMsg.innerHTML=messages[i];
		
		if(createdAt==null)
			createdAt=(new Date()).getTime();
		liMsg.pcng_createdAt=createdAt;
		msgDiv.appendChild(liMsg);
	}
	if(createdAt!=null){
		msgDiv.style.visibility="visible";
		msgDivList2Clean[createdAt]=msgDiv;
		if(timeout>0){
			setTimeout("clearGeneralMessageDiv("+createdAt+")", timeout);
		}
	}
	
	return createdAt;
}

var msgDivList2Clean=new Object();

function clearGeneralMessageDiv(createdAt){
	if(!createdAt){
		return;
	}
	msgDiv=msgDivList2Clean[createdAt];
	if(msgDiv)
		clearGeneralMessageDiv2(createdAt, msgDiv);
	
	msgDivList2Clean[createdAt]=null;
}

function clearAllGeneralMsg(){
	for(createdAt in msgDivList2Clean){
		clearGeneralMessageDiv(createdAt);
	}
}

function clearGeneralMessageDiv2(createdAt, msgDiv){
	if(msgDiv && msgDiv.childNodes){
		var numberOfOldMessages2Keep=0;
		if(msgDiv.numberOfOldMessages2Keep)
			numberOfOldMessages2Keep=msgDiv.numberOfOldMessages2Keep;
		
		for(var i=0;i<msgDiv.childNodes.length-numberOfOldMessages2Keep;i++){
			if(msgDiv.childNodes[i].pcng_createdAt){
				if(createdAt==null || msgDiv.childNodes[i].pcng_createdAt<=createdAt){
					msgDiv.removeChild(msgDiv.childNodes[i]);
					
					if(msgDiv.showEllipse){
						if(!msgDiv.childNodes[0].ellipseRpw){
							var liMsg=document.createElement("LI");
							liMsg.innerHTML="...";
							liMsg.ellipseRpw=true;
							msgDiv.insertBefore(liMsg, msgDiv.childNodes[0]);
						}
					}
					
					i--;
				}
			}
		}
		
		if(msgDiv.childNodes.length==0){
			msgDiv.style.visibility="hidden";
		}
	}
}


function pcngInitNode(node1){
	walkTree(node1, function(node){
		var pcngInitFunctionsCode=null;
		if(node.getAttribute)
			pcngInitFunctionsCode=node.getAttribute("onInit");

		if(pcngInitFunctionsCode && pcngInitFunctionsCode!=null)
			eval(pcngInitFunctionsCode);

		if(node.helpPage || node.helpText){
			addMouseOverHelp(node);
		}
	});
}

function getElementHeight(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.height;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) { 
			xPos = elem.style.pixelHeight;
		} else {
			xPos = elem.offsetHeight;
		}
		return xPos;
	} 
}

function getElementWidth(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}

function blink(args){
 // Set the color and seconds below, e.g., [args,'COLOR',SECONDS]
       args = (/,/.test(args))?  args.split(/,/):  [args,'#FFD100',10];
       var who = document.getElementById(args[0]);
       var count = parseInt(args[2]);
       if (--count <=0) {
               who.style.backgroundColor = '';
               if(who.focus) who.focus();
       } else {
               args[2]=count+'';
               who.style.backgroundColor=(count%2==0)? '': args[1];
               args='\"'+args.join(',')+'\"';
               setTimeout("blink("+args+")",500);
       }
}

function getKeyCode(e){
	var characterCode; // literal character code will be stored in this variable
	
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}
	
	return characterCode;
}

function checkEnter(e){ //e is event object passed from function invocation
	return getKeyCode(e) == 13;
}

function window_scroll_event(){
		var scrollY=window.pageYOffset || document.body.scrollTop;
		Set_Cookie("pageScroll_"+document.location, scrollY, 3);
}
function setUpScroll(){
	window.onscroll=window_scroll_event;
	var GroupAdminPage_ScrollY=Get_Cookie("pageScroll_"+document.location);
	if(GroupAdminPage_ScrollY){
		document.body.scrollTop=GroupAdminPage_ScrollY;
	}
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function makeAutoFit(node){
	if(node){
		node.onkeyup=function(){
			if(this.size<30 && this.size<this.value.length+1){
				this.size=this.value.length+1;
			}
		};
	}
}


function displayInBrowserWnd(event, title, contentDiv, focusId){
	jt_DialogBox.imagePath='/PC-NG-AA/images/';
	var tmpWnd = new jt_DialogBox(true);
	tmpWnd.setTitle('nexiwave.com - '+title);
	
	tmpWnd.show();
	if(event)
		centerJtWindows(tmpWnd, event);
	else{
		centerJtWindows(tmpWnd);
	}
	
	tmpWnd.contentArea.appendChild(contentDiv);
	if(focusId){
		try{
			var node=findChildById(tmpWnd.contentArea, focusId);
			if(node)
				node.focus();
		}
		catch(err){}
	}
	
	return tmpWnd;
}

function isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
 } 


function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
      while(1) 
      {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.x)
      curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}

function getQueryParameters(){
	// get the current URL
	 var url = window.location.toString();
	 //get the parameters
	 url.match(/\?(.+)$/);
	 var params = RegExp.$1;
	 // split up the query string and store in an
	 // associative array
	 var params = params.split("&");
	 var queryStringList = {};
	 
	 for(var i=0;i<params.length;i++)
	 {
	     var tmp = params[i].split("=");
	     queryStringList[tmp[0]] = unescape(tmp[1]);
	 }
	 return queryStringList;
}

function getLeadingURL(){
	 var url = window.location.toString();
	 if(url.substr(0,4)=='jar:')
		 url=url.substr(4);
	 var index=url.indexOf('/PC-NG-AA');
	 return url.substr(0, index);
}