// Common Used Functions Go Here

function Trim(str) {
	var out = str;
	
	while( out.charAt(0) == ' ' ) out = out.substring(1);
	while( out.charAt(out.length - 1) == ' ' ) out = out.substring(0, out.length - 2);
	
	return out;
}

//- isObject ------------------------
function isObject(obj) {
	return (typeof(obj) == "object") && (obj != null);
} //:isObject

function printHidden(sUrl) {
	if (window.navigator.userAgent.indexOf("MSIE ")!=-1 && navigator.appVersion.substr(0, 1) >= 4){
		document.body.insertAdjacentHTML("beforeEnd", 
			"<iframe name='printHiddenFrame' width='0' height='0'></iframe>");
		doc = printHiddenFrame.document;
		doc.open();
		doc.write(
			"<frameset onload='parent.printFrame(printMe);' rows=\"100%\">" +
			"<frame name=printMe src=\"" + sUrl + "\">" +
			"</frameset>");
		doc.close();
	}
	else{
		document.location.href=sUrl;
	}
}

function printFrame(frame) {
  frame.focus();
  frame.print();
  return;
}

/**************** Open Window ****************************/
var applicationPath = "";

function openWin(url, width, height, name, params) {
	var left, top;
	
	// inside the application
	if(
	    (url.toLowerCase().indexOf("http") == -1)
	    && !url.startsWith("/")
	    && (url.indexOf("..") == -1)
	)
		url		= applicationPath + url;

	// dimentions
	if(width == null) width = "500";
	if(height == null) height = "480";
	
	// window name
	if(name == null) name = "XPop_" + Math.round(Math.random() * 1000) + "_" + Math.round(Math.random() * 100);
	
	// params
	if(params == null) {
		left	= (screen.width - width)/2;
		top		= (screen.height - height)/2;
	
		params	= "left=" + left + ",top=" + top + ",width=" + width + ", height=" + height + ", scrollbars=yes, menubar=yes, toolbar=yes, resizable=yes";
	}
	else {
		params	= "width=" + width + ", height=" + height + ", " + params;	
	}

	x = window.open(
		url, 
		name, 
		params);
	try{
		x.focus();	
	}catch(e){};
}

function goMod(module, params) {
	var url = applicationPath + module;
	
	if(params != null) url += "?" + params;
	
	document.location.href	= url;
}

/*-----------------------------------------------------------------------*/
/*-	 Function : SetDefaultButton
/*-----------------------------------------------------------------------*/
var x_defaultButton	= "";

function registerDefaultButton(f) {
	try {
		if(event.keyCode == 13) {
			// prevent the default submission buttion get clicked
			if(canCancelBubble()) {
				event.cancelBubble = true;
				event.returnValue = false;
			}
			
			try{
				if(typeof(x_defaultButton) == "string" && x_defaultButton != "" && canSubmit() ) f.all[x_defaultButton].click();			
			}catch(e){
			}
		}
	}catch(e){
	}
}

function getSrcElementType() {
	if(isObject(event.srcElement) && typeof(event.srcElement.type) == "string")
		return event.srcElement.type;
	else
		return null;
}

function canSubmit() {
	var eleType = getSrcElementType();

	if(eleType == "textarea" || eleType == "reset" || eleType == null)
		return false;
	else
		return true;
}

function canCancelBubble() {
	if(getSrcElementType() == "textarea")
		return false;
	else
		return true;
}
/*-----------------------------------------------------------------------*/

/*-----------------------------------------------------------------------*/
/*-	 Function : Toggle the 'check all' check boxes
/*-----------------------------------------------------------------------*/
function xfn_checkAll(oChkAll, parentID, itemID) {
	var chkAllID = oChkAll.id;
	var bChecked = oChkAll.checked;
	var oInputs	 = xfn_getParent_(parentID).getElementsByTagName("INPUT");

	for(var i=0; i<oInputs.length; i++) {
		if(oInputs[i].type == "checkbox" && 
			oInputs[i].id != chkAllID &&
			oInputs[i].id.indexOf(itemID) != -1) {
			
			oInputs[i].checked = bChecked;
		}
	}
}

function xfn_checkOne(oChkOne, parentID, checkAllID, itemID) {
	var oInputs	 = xfn_getParent_(parentID).getElementsByTagName("INPUT");
	var bChecked = oChkOne.checked;
	
	if(bChecked) {
		// determine the checked state
		for(var i=0; i<oInputs.length; i++) {
			if(oInputs[i].type == "checkbox" && 
				oInputs[i].id.indexOf(itemID) != -1 &&
				!oInputs[i].checked) {
				
				bChecked	= false;
				break;
			}		
		}
	}

	// set 'check all' checkboxes
	for(var i=0; i<oInputs.length; i++) {
		if(oInputs[i].type == "checkbox" && 
			oInputs[i].id.indexOf(checkAllID) != -1) {
			
			oInputs[i].checked	= bChecked;			
		}		
	}
}

function xfn_getParent_(parentID) {
	var oParent = document.all(parentID);

	if(parentID != null && isObject(oParent))
		return oParent;
	else
		return document.body;
}
/*-----------------------------------------------------------------------*/

// get parent element
function getParentElementByTagName(obj, tagName, id, checkStartsWith) {
	var oParent = obj.parentElement;
	
	if(id == null) {
		// don't check the object id
		while( isObject(oParent) && (oParent.tagName != "HTML") && (oParent.tagName != tagName)) 
			oParent = oParent.parentElement;
	}
	else if(checkStartsWith) {
		// check the object id with 'starts with pattern'
		while( isObject(oParent) && (oParent.tagName != "HTML") && !((oParent.tagName == tagName) && ( StartsWith(oParent.id, id) || StartsWith(oParent.name, id) ))  ) 
		oParent = oParent.parentElement;
	}
	else {
		// check the object id match exactly with specified id
		while( isObject(oParent) && (oParent.tagName != "HTML") && !((oParent.tagName == tagName) && ( oParent.id == id || oParent.name == id))  ) 
			oParent = oParent.parentElement;
	}
	
	if(isObject(oParent) && (oParent.tagName != "HTML")) {
		return oParent;
	}
	else {
		return null;
	}
}

// get element(s) by tagname  
// -  id: integer, to return the object by index in the collection
//		  string   to return the object by the object's name or id (first occurrence)
//		  omitted  return the collection
function getElementsByTagName(obj, tagName, id, checkStartsWith) {
	if( (isObject(obj) == false) || (typeof(obj.getElementsByTagName) == "undefined") ) 
		return null;

	var coll = obj.getElementsByTagName(tagName);

	if(id == null) {
		// 'id' param omitted
		return coll
	}
	else {
		if(coll.length == 0) return null;
	
		if(typeof(id) == "number") {
			// get object by index
			return coll[id];				
		}
		else {
			var idLen = id.length;
		
			for(var i=0; i<coll.length; i++) {
				// name attr presents
				if( (typeof(coll[i].name) == "string") && ( (/* check starts with */checkStartsWith && coll[i].name.substr(0,idLen) == id) || (coll[i].name == id) ) )
					return coll[i];
				else if( (typeof(coll[i].id) == "string") && ( (/* check starts with */checkStartsWith && coll[i].id.substr(0,idLen) == id) || (coll[i].id == id) ) )
					return coll[i];
			}			
		}	
	}	
	return null;
}

function Collection()
{
	function Item(Index)
	{
		var Obj = null;
		if(Index != null)
		{
			var realIndex = parseInt(Index);
			if (!isNaN(realIndex) && realIndex >= 0 && realIndex < this.length)
				Obj = this[realIndex];
		}
		return Obj;
	}
	function Find(Object)
	{
		var i;
		var obj = null;
		for (i=0; i<this.length; i++)
		{
			if (this[i] == Object)
			{
				obj = this[i];
				break;
			}
		}
		return obj;
	}
	function FindByName(Name, Qualifier)
	{
		var i;
		var obj = null;
		for (i=0; i<this.length; i++)
		{
			if (this[i].Name == Name && this[i].Qualifier == Qualifier)
			{
				obj = this[i];
				break;
			}
		}
		return obj;
	}
	function Add(Object)
	{
		var ArraySize = this.length;
		this[ArraySize] = Object;
		return this[ArraySize];
	}
	function Remove(Index)
	{
		var i;
		var realIndex = parseInt(Index);
		if (isFinite(realIndex) && realIndex >= 0 && realIndex < this.length)
		{
			for (i=realIndex; i<this.length-1; i++)
				this[i] = this[i+1];
			this.length--;
		}
	}
	function RemoveObject(Object)
	{
		var i;
		for (i=0; i<this.length; i++)
		{
			if (this[i] == Object)
			{
				this.Remove(i);
				break;
			}
		}
	}
	function Count()
	{
		return this.length;
	}
	var obj = Array();
	obj.Item = Item;
	obj.Count = Count;
	obj.Add = Add;
	obj.Remove = Remove;
	obj.Find = Find;
	obj.FindByName = FindByName;
	obj.RemoveObject = RemoveObject;
	return obj;
}

/***************************************************
** StartsWith
****************************************************/
function StartsWith(str, strStart) {
	if(str == null || strStart == null) return false;

	var lenStr = str.length;
	var lenStrStart = strStart.length;

	if(lenStrStart > lenStr) return false;
	
	return str.substr(0, lenStrStart) == strStart;
} // StartsWith

function StartsWith_(str) {
	return StartsWith(this, str);
} // StartsWith_


/***************************************************
** EndsWith
****************************************************/
function EndsWith(str, strEnd) {
	if(str == null || strEnd == null) return false;

	var lenStr = str.length;
	var lenStrEnd = strEnd.length;

	if(lenStrEnd > lenStr) return false;
	
	return str.substr(lenStr - lenStrEnd) == strEnd;
} // EndsWith

function EndsWith_(str) {
	return EndsWith(this, str);
} // EndsWith_

/*********************************************************/
// Add a extention functions to String constructor.

String.prototype.trim = function()
{
    // Use a regular expression to replace leading and trailing 
    // spaces with the empty string
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.startsWith = StartsWith_;
String.prototype.endsWith = EndsWith_;
/***********************************************/

//---------------------------------------------------------------
// disableOnPostBack
//---------------------------------------------------------------
var optDisabled_DefinedOnly		= 0x01;		/* check property 'disabledOnPostBack' if it's true */
var optDisabled_AlsoOnServer	= 0x02;		/* do not send the data to server */
var disabledAtClient	= "client";			/* disable the elements at client only. Only usable when 'optDisabled_AlsoOnServer' flag is being used. */

var gFrmActive = null;
var gFrmPosting = false;

function disableOnPostBack(oFrm, options, bDisabled) {
	var bDisableDefinedOnly  = false;
	var bDisableAlsoOnServer = false;
	
	// get options
	gFrmActive	= oFrm;
	
	bDisabled	= bDisabled != false;
	if(bDisabled == false) gFrmPosting = false;

	// change cursor
	document.body.style.cursor	= (bDisabled) ? "wait" : "auto";

	// exit here if the posting is in progress
	if(gFrmPosting) return false;
	
	// flag posting in progress		
	gFrmPosting	= true;

	if(!isNaN(options)) {
		bDisableDefinedOnly		= (options & optDisabled_DefinedOnly) == optDisabled_DefinedOnly;
		bDisableAlsoOnServer	= (options & optDisabled_AlsoOnServer) == optDisabled_AlsoOnServer;
	}

	// disable now
	if(bDisableAlsoOnServer) 
		// disable elements immediately, so the data WONT BE SENT to server
		disableOnPostBack_(bDisableDefinedOnly, true, bDisabled);

	// delay disable elements to ALLOW TO SEND the data to server
	setTimeout("disableOnPostBack_(" + bDisableDefinedOnly + ", false, " + bDisabled + ")", 1);
	
	return true;
}

function disableOnPostBack_(bDisableDefinedOnly, bDisableAtServer, bDisabled) {
	// Looking for non-input elements in the form
	for(var i=0; i<gFrmActive.elements.length; i++){
		if((gFrmActive.elements[i].tagName != "INPUT") && canDisable(gFrmActive.elements[i], bDisableDefinedOnly, bDisableAtServer))
			gFrmActive.elements[i].disabled = bDisabled;
	}
	
	// Input Elements
	var oInputs = gFrmActive.getElementsByTagName("INPUT");
	for(var i=0; i<oInputs.length; i++) {
		if(canDisable(oInputs[i], bDisableDefinedOnly, bDisableAtServer))
			oInputs[i].disabled = bDisabled;
	}
} // disableOnPostBack

function canDisable(obj, bDisableDefinedOnly, bDisableAtServer) {
	if(typeof(obj.disabled) == "undefined") return false;

	var sDisabledFlagValue = obj.disabledOnPostBack;
	var bDisabledFlagDefined = (typeof(sDisabledFlagValue) != "undefined");
	
	// flag not defined
	if( bDisabledFlagDefined == false ) {
		// eliminate if the flag is required but not present
		if( bDisableDefinedOnly ) return false;
			
		// set the flag value to 'disabledAtClient' if not defined. ie send to server as it is.
		sDisabledFlagValue = disabledAtClient;
	}

	// format the flag
	sDisabledFlagValue = sDisabledFlagValue.toLowerCase();
	
	// element type
	var type = (typeof(obj.type) == "undefined") ? "" : obj.type;
	
	if(bDisableAtServer) {
		// disable at server
		return sDisabledFlagValue == "true";
	}
	else {
		// disable at client
		if(type == "hidden") 
			// ignore hidden fields
			return false;
		else
			return (sDisabledFlagValue == "true") || (sDisabledFlagValue == disabledAtClient);
	}
} // canDisable
//---------------------------------------------------------

// RadioButtonList
function RadioButtonList(id, value, serverType) {
	var _checked = false;
	var _value = null;
	var _item = null;
	var me = this;

	var oInputs;
	if(serverType == true){
		if(typeof(id) == "string"){
			oInputs = document.getElementsByName(id);
			if(oInputs.length == 1) oInputs = oInputs[0].getElementsByTagName("INPUT");
		}
		else {
			oInputs = id.getElementsByTagName("INPUT");
		}
	}
	else {
		oInputs	 = (typeof(id) == "string") ? document.getElementsByName(id) : id;
	}

	if(value == null) {
		// get value
		refresh_()
	}
	else {
		// set value
		setValue_(value);
	}
	
	this.refresh	= refresh_;
	this.setValue	= setValue_;
	
	function setValue_(value) {
		_checked = false;
		_value = null;
		_item = null;

		for(var i=0; i<oInputs.length; i++)
			if(oInputs[i].value == value) {
				oInputs[i].checked = true;
				_checked	= true;
				_value		= oInputs[i].value;
				_item		= oInputs[i];
			}
			else{
				oInputs[i].checked = false;
			}

		me.checked	= _checked;
		me.value		= _value;	
		me.item		= _item;
	}
	
	function refresh_() {
		_checked = false;
		_value = null;
		_item = null;

		for(var i=0; i<oInputs.length; i++)
			if(oInputs[i].checked) {
				_checked	= true;
				_value		= oInputs[i].value;
				_item		= oInputs[i];
			}

		me.checked	= _checked;
		me.value		= _value;	
		me.item		= _item;
	}	
}

function viewDoc(docId){
    var frmViewDoc = document.forms["_viewDoc"];

    event.returnValue = false;

    // prepare form
    if(!isObject(frmViewDoc)){
        document.body.insertAdjacentHTML(
            "afterBegin", 
            "<form name='_viewDoc' method='post' action='/portal/modules/documents/download.aspx'>" +
                "<input type='hidden' name='docID' />" +
            "</form>"
            );
       frmViewDoc = document.forms["_viewDoc"];
    }          
    
    frmViewDoc.docID.value = docId;   
    frmViewDoc.submit();
}

function viewStats(appId, appName) {
	openWin('/demosites/it/appusage/usagereport.asp?ApplicationId=' + appId + '&ApplicationName=' + escape(appName),760,500,'usage');
}


// Example:
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.
function writeCookie(name, value, hours)
{
  var expire = "";
  if(hours != null)
  {
    expire = new Date((new Date()).getTime() + hours * 3600000);
    expire = "; expires=" + expire.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expire;
}

// Example:
// alert( readCookie("myCookie") );
function readCookie(name)
{
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0)
  { 
    offset = document.cookie.indexOf(search);
    if (offset != -1)
    { 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}

function isCookieEnabled() {
	try {
		writeCookie("test_", "1");
		return (readCookie("test_") == "1");
	}catch(e){
		return false;
	}
} // isCookieEnabled

function ensureCookieEnabled(showInMsgBox) {
	var isEnabled = isCookieEnabled();

	if(isEnabled == false) {
		var sMsg = "Your browser's cookie functionality is turned off. Please turn it on.";
		
		if(showInMsgBox == true)
			alert(sMsg);
		else
			document.write("<div class=tb style=\"color:red\">" + sMsg + "</div>");
	}
	
	return isEnabled;
} // ensureCookieEnabled