//**********************************************************************
// ThePort Utilities.  
// Author: Steve Soares
//**********************************************************************
// Copyright ThePort Inc.
////////////////////////////////////////////////////////////////////////
// Version History.
////////////////////////////////////////////////////////////////////////
//**********************************************************************
// October 27, 2006 Initial Version.
// (Some small functions grabbed from the top 10 javascripts website 
// and other built along the way...
//**********************************************************************

/*********************************************************************************/
//Detect whether there is a "hello" member in the arguments array:
//var parameter = 'hello' in arguments? arguments : "";
// 
//Detect whether arguments contains at least one argument
//var parameter = typeof arguments[0] != 'undefined'? arguments : "";
// 
//Detect whether the user passed an object(can be array) or a list of arguments
//var parameter = (typeof arguments[0] == 'object')? arguments[0] : arguments;
// 
//Detect whether there is an arguments passed into the function and assign the number of arguments into the variable
//var parameter = arguments.length || "";
//
//function Dup(obj)
//{
//   for (prop in obj) {
//      if (typeof(obj[prop]) == "object") {
//         this[prop] = new Dup(obj[prop])
//      } else {
//         this[prop] = obj[prop];
//      }
//   }
//}
//
//// usage 
//var array = new Array( "alkdsjf", "alksdjflasd" );
//var duplicated = new Dup( array );
//
/*********************************************************************************/

//***********************************************************
// Extend Array class.
//***********************************************************
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

function ThePortURLDecoder(psEncodeString) 
{
try {
  if ((typeof psEncodeString=="undefined")||(psEncodeString==null)) return null;
  var lsRegExp = /\+/g;
  return decodeURIComponent(String(psEncodeString).replace(lsRegExp, " ")); 
 } catch(e) { return null; }
}

function ThePortXMLEncodeString(string) {
	return string.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;').replace('\'','&apos;').replace('"','&quot;');
}

/*
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
*/

//********************************************************************
//
//********************************************************************
if (String.prototype.trim==null) String.prototype.trim = function (){
		if(this.length < 1) return "";
		var retVal = new String("");
		retVal = this.rTrim();
		retVal = retVal.lTrim();
		return retVal;
} 


//********************************************************************
//
//********************************************************************
if (String.prototype.rTrim==null) String.prototype.rTrim = function (){
	var w_space   = String.fromCharCode(32);
	var v_length  = this.length;
	var strTemp   = "";
	if(v_length < 0){
	  return "";
	  }
	var iTemp = v_length -1;
	while(iTemp > -1){
	  if(this.charAt(iTemp) == w_space){
    	  }
	  else{
		strTemp = this.substring(0,iTemp +1);
		break;
		}
	  iTemp = iTemp-1;
	  } //End While
	return strTemp;
} 


//********************************************************************
//
//********************************************************************
if (String.prototype.lTrim==null) String.prototype.lTrim = function(){
	var w_space = String.fromCharCode(32);
	if(v_length < 1){
	  return"";
	  }
	var v_length  = this.length;
	var strTemp   = "";
	var iTemp     = 0;

	while(iTemp < v_length){
	if(this.charAt(iTemp) == w_space){
	    }
	else{
	    strTemp = this.substring(iTemp,v_length);
	    break;
	    }
	iTemp = iTemp + 1;
	} //End While
	return strTemp;
} 


//********************************************************************
//
//********************************************************************
if (String.prototype.left==null) String.prototype.left = function(n){
	if (n <= 0)
	    return "";
	else if (n > this.length)
	    return this;
	else
	    return this.substring(0,n);
}


//********************************************************************
//
//********************************************************************
if (String.prototype.right==null) String.prototype.right = function(n){
    if (n <= 0)
       return "";
    else if (n > this.length)
       return this;
    else {
       var iLen = this.length;
       
       return this.substring(iLen, iLen - n);
      }
}


//********************************************************************
//
//********************************************************************
var ThePortUtils = {  // Javascript 'Namespace'.

ThePortPopupWindow:null,

OpenThePortPopupWindow:   function (url,w,h) { 
    try {
      if (window.ThePortPopupWindow) {
        window.ThePortPopupWindow.close();
        window.ThePortPopupWindow = null;
        }
    } catch(e){}
    try {
      var mh = h;
      var mw = w;
      var vertpos = (mw/2);
      var horpos = (mh/2);
      var swcalc = (screen.width/2);
      var shcalc = (screen.height/2);
      var tlt = (swcalc-vertpos);
      var tll = (shcalc-horpos);
      ThePortPopupWindow = window.open(url,"","height="+mh+",width="+mw+",top="+tll+",left="+tlt+",screenx="+tll+",screeny="+tlt+",scrollbars=1,resizable=no,dependent=yes,z-lock=yes");
    } catch(e){}
  },

getOuterXML: function (tree) {
  var text = "";
      if((tree.hasChildNodes())||((tree.attributes)&&(tree.attributes.length>0))) {
        text = '<'+tree.tagName;
        if ((tree.attributes)&&(tree.attributes.length>0)) {
          for(var i=0; i<tree.attributes.length; i++) {
            var attr = tree.attributes[i];
            text += " "+attr.nodeName+"='"+getValueFromNode(attr)+"' ";
            }
          }
        text += '>';
          
        //var nodes=tree.childNodes.length;
          if (tree.childNodes.length>0) {
            for(var i=0; i<tree.childNodes.length; i++)
              text+= ThePortUtils.getOuterXML(tree.childNodes[i]);
//            text += tree.text;
            text += '</'+tree.tagName+'>';
            }
        else text += '</'+tree.tagName+'>';
    }
    else {
          var txt = new String(getValueFromNode(tree));
          //txt     = tree.text;
          text   += txt.escapeHTML();
          //text += tree.text.escapeHTML();
         }
  return text;
},

//********************************************************************
//
//********************************************************************
findChildId: function(node, id) {
  try {
    var temp;
    if (node == null) {
      return null;
      }
    node = node.firstChild;
    while (node != null){
      if (node.id == id) {
        return node;
        }
      temp = this.findChildId(node, id);
      if (temp != null){
        return temp;
        }
      node = node.nextSibling;
      }
  }catch(e) { }    
  return null;
},


//********************************************************************
// String replace strange characters like '\n'
//********************************************************************
replace: function (str, from, to) {
    var i = str.indexOf(from);
    if (!from || !str || i == -1) return str;
    var newstr = str.substring(0, i) + to;
    if (i+from.length < str.length)
    newstr += replace(str.substring(i+from.length,str.length),from,to);
    return newstr;
},


//********************************************************************
//
//********************************************************************
toggleSummary: function(moduleGuid,itemId) {
  var instance;
  instance = ThePortModule.getInstance(moduleGuid);
  if (instance)
    instance.toggleSummaryItem(itemId);
},

//********************************************************************
// Handy little obj to pass vars by reference...
//********************************************************************
parm: function(value){this.value = value;},

//********************************************************************
// Clone and object...
//********************************************************************
clone: function(src) {for(i in src){this[i] = src[i];}},

//********************************************************************
// ~derived from  http://www.quirksmode.org/js/findpos.html#
//********************************************************************
findPosXY: function(obj,x,y)
{
  x.value = 0;
  y.value = 0;
  if (obj.offsetParent) {
	while (obj.offsetParent) {
	  x.value += obj.offsetLeft;
	  y.value += obj.offsetTop;
	  obj = obj.offsetParent;
  	  }
  	}
  else {
        if (obj.x)
		  x.value += obj.x;
        if (obj.y)
		  y.value += obj.y;
	   }
  return;
},


//*********************************************************************
//
//*********************************************************************
createIframeArea: function (url,parentNode)
{
  var x1 = new parm();
  var y1 = new parm();
  this.findPosXY(parentNode,x1,y1);

  var IFrameDoc;
  if (!document.createElement) {alert('cannot create element');return true};
  if (!this.m_IFrameObj && document.createElement) {
    // create the IFrame and assign a reference to the
    try {
        this.m_tempIFrame=document.createElement('iframe');
        this.m_tempIFrame.setAttribute('id',this.m_guid);
        this.m_tempIFrame.style.border='0px';
        this.m_tempIFrame.style.width='210px';
        this.m_tempIFrame.style.height='900px';
        this.m_IFrameObj = parentNode.appendChild(this.m_tempIFrame);
        this.m_tempIFrame.src = url;
      } catch(exception) {
        // This is for IE5 PC, which does not allow dynamic creation
        // and manipulation of an iframe object. Instead, we'll fake
        // it up by creating our own objects.
        alert('creation route #2');
        iframeHTML='\<iframe id="'+this.m_guid+'" style="';
        iframeHTML+='border:0px;';
        iframeHTML+='width:100px;';
        iframeHTML+='height:200px;';
        iframeHTML+='"><\/iframe>';
        document.body.innerHTML+=iframeHTML;
        this.m_IFrameObj = new Object();
        this.m_IFrameObj.document = new Object();
        this.m_IFrameObj.document.location = new Object();
        this.m_IFrameObj.document.location.iframe = document.getElementById(this.m_guid);
        this.m_IFrameObj.document.location.replace = function(location) {
          this.iframe.src = location;
          }
        }
    }
  return false;
},


//***********************************************************
//grabbed from the top 10 javascripts website
//***********************************************************
insertAfter: function (parent, node, referenceNode) 
{
  parent.insertBefore(node, referenceNode.nextSibling);
},


//***********************************************************
// grabbed from the top 10 javascripts website
//***********************************************************
addEvent: function (elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
},


//***********************************************************
// grabbed from the top 10 javascripts website
//***********************************************************
addLoadEvent: function (func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
},


//***********************************************************
// grabbed from the top 10 javascripts website
//***********************************************************
getElementsByClass: function (searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
},


//***********************************************************
// grabbed from the top 10 javascripts website
//***********************************************************
toggle: function (obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
},

//***********************************************************
// port function...
//***********************************************************
openWindow: function (u,title,options)
  {
  var win;
  var o=""
  if (tp_openWin.arguments[2]){o=options;}
  var t = "linkwin"
  if (tp_openWin.arguments[1]){t=title;}
  win=window.open(u,t,o);
  win.focus()
 }
 

//***********************************************************
// port function
//***********************************************************
/*
setDivDisplay: function (sDivID,imgsrc)
  {
  if (document.all(sDivID)) {
    if (document.all(sDivID).style.display == "none") {
      document.all(sDivID).style.display = "";
      if (sDivID == 'summary') 
        document.all.hdnOptStyle.value = "SHOW"
      }
    else{      
        document.all(sDivID).style.display = "none";
        if (sDivID == 'summary') 
          document.all.hdnOptStyle.value = "HIDE"
        }
    }
  if (document.all(imgsrc)) {      
    var sImg;
    sImg = document.all(imgsrc).src;
    if (sImg.indexOf("plus") > 0)
      document.all(imgsrc).src = "/images/minus.gif";
    else document.all(imgsrc).src = "/images/plus.gif";
    }
  }
*/
} // End  Namespace declaration...


function getClientAreaWidth()
{
	var myWidth = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		myWidth = window.innerWidth;
	} else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
		myWidth = document.documentElement.clientWidth;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}

function getClientAreaHeight()
{
	var myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		myHeight = document.body.clientHeight;
	}
  return myHeight;
}

//******************************************************************
// We need to use this function to get the value out of a node.
// because it works differently in different browsers.
// This function does NOT rely on any internal vars of the object
// so it can be extracted or called from anywhere without problems.
//******************************************************************
function getValueFromNode(node) 
{
  if (typeof node.text != 'undefined') 
	  return node.text;
  else if (typeof node.textContent != 'undefined') 
		  return node.textContent;
		else if (typeof node.innerText != 'undefined') 
				return node.innerText;
			else {
				  switch (node.nodeType) { 
					  case 3:		// Node Text
					  case 4:		// Node CData
						  return node.nodeValue;
					  break;
					  case 1:		// Node Element
					  case 11:	// Document fragment
					  var retVal = new String();
					  for (var i = 0; i < node.childNodes.length; i++) 
						  retVal += getNodeValue(node.childNodes[i]);
					  return retVal;
					  default: return "";
					  }
				}
}

//*****************************************************
// 
//*****************************************************
function getAttrValueFromNode(node,attr)
{
  try {
 	for (l=0;l<node.attributes.length;l++) {
	  if (node.attributes[l].nodeName == attr)
        return(node.attributes[l].nodeValue);
      }
  } catch(e) { return null;}
  return null;
}



