/***************************************************************
@$
Description: Get a DOM element by its id.
Input:  element: The element id.
Notes: This function is safe to use nested within itself.
	   THIS FUNCTION MUST BE REMOVED IF PROTOTYPE.JS IS USED!
***************************************************************/
if (typeof this.$ == "undefined") {
	var $ = function(element) {
		if (typeof element == "string") {
			element = document.getElementById(element);
		}
		return element;
	};
}


// Define the global function object 
if(typeof this.gwwa == "undefined") { 
	var gwwa = {}; 
}


/***************************************************************
@gwwa.ns
Description: Ensures that a specified package exists in the namespace.
Input:  package: String representing the package name and scope.
Example:
    gwwa.ns("gwwa.foo.bar");
	gwwa.foo.bar.doSomething = function() {};
***************************************************************/
gwwa.ns = function(/*String*/ pkg)
{
	var scope = gwwa;
    var i = 0;
    var items = pkg.split(".");
	if (items[0] != "gwwa") {
		return;
	}
	for (i = 1; i < items.length; i++) {
		if (scope[items[i]] === undefined) {
			scope[items[i]] = {};
		}
		scope = scope[items[i]];
	}
};


/***************************************************************
@gwwa.formatQueryString
Description: Format the key/value pairs of an object as a query string.
Input:  args: An object containgin key/value pairs for translation.
        formatter (optional): A function for formatting argument values 
		                      (defaults to escape()).
Output: The formatted query string.
Notes: THIS FUNCTION PEFORMS ENCODING! No need to call escape().
Example:
    // typical usage
    var qs = gwwa.formatQueryString({
	    "foo": 10,
		"bar": "Hello"
	});
	// use a passthrough function to prevent the string from being encoded.
	var qs = gwwa.formatQueryString(myObj, function(val){return val});
***************************************************************/
gwwa.formatQueryString = function(/*Object*/ args, /*Function*/ formatter)
{
	formatter = (formatter === undefined) ? escape : formatter;
	var items = [];
    var key;
    for (key in args) {
		items.push(key + "=" + formatter(args[key]));
	}
	return items.join("&");
};


/***************************************************************
@gwwa.parseJSON
Description: Evaluate a JSON string safely.
Input:  text: String containing JSON formatted data.
Output: The evaluated object or undefined if the text could not be processed.
Notes: Text MUST contain strict JSON as defined in RFC 4627.
Example:
    var obj = gwwa.parseJSON("{\"foo\":0,\"bar\":\"Hello World!\"}");
    if (obj !== undefined)
        alert(obj.bar);
***************************************************************/
gwwa.parseJSON = function(/*String*/ text)
{
	// Safari 1.3.2 regular expressions don't work for strings
	// containing extended characters.  Ignoring this safety mechanism
	// should allow features that rely on XHR and JSON to function
	// but may also cause unexpected behavior in some cases.
	if (gwwa.browser.flavor == "SAFARI" && parseInt(gwwa.browser.flvMjrVer, 10) < 400) {
		return eval('(' + text + ')');
	}
	
	// as defined in RFC 4627
	if (!((/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/).test(text.replace(/"(\\.|[^"\\])*"/g, '')))) {
		return eval('(' + text + ')');
	}
	var win = getMainWindow();
	win.location.href = "/gw/webacc";
};


/***************************************************************
@gwwa.normalizeObject
Description: Normalize a JSON object processed by njweb.  Relocates ARR and VAL 
             elements to the parent.  Makes arrays index from 0 instead of 1.
Input:  obj: The object to normalize.
        preserveArrayOffset (optional): Preserve original array indexing.
Output: The normalized object.
Notes: USE WITH CAUTION!  Use of this function on some objects processed by 
       njweb could result in data loss--specifically where objects are the 
       direct parents of multiple data types including arrays, objects, and 
	   scalar values.
Example:
	var obj = gwwa.parseJSON(response.responseText);
    var foo = gwwa.normalizeObject(obj.Foo);
	alert(obj.ARR[1]) // display message
    alert(foo[0]) // same message
***************************************************************/
gwwa.normalizeObject = function(/*Object*/ obj, /*Boolean*/ preserveArrayOffset)
{
	if (!obj) {
		return obj;
	}

	if (obj.VAL !== undefined) {
		return obj.VAL;
	}
	
	var oFlag = preserveArrayOffset === undefined || !preserveArrayOffset ? 0 : 1;
	
	if (obj.ARR !== undefined) {
		var nArr = [];
        var i;
        for (i in obj.ARR) {
			if (i == "0" && !oFlag) {
				continue;
			}
			nArr.push(gwwa.normalizeObject(obj.ARR[i], oFlag));
		}
		return nArr;
	}
	
	var nObj = {};
    var key;
    for (key in obj) {
		nObj[key] = gwwa.normalizeObject(obj[key], oFlag);
	}
	return nObj;
};

/***************************************************************
@gwwa.getEvent
Description: A cross-browser wrapper to get the event object
Input:  Event object if it's valid (on IE it's not)
Output: A valid event object on all browsers
Notes: 
Example:
***************************************************************/
gwwa.getEvent = function(e)
{
	return ( window.event !== null ) ? window.event : e;
};

/***************************************************************
@gwwa.getEventTarget
Description: A cross-browser wrapper to get the target object
				for any event
Input:  event object if it exists (on IE it does not)
Output: A valid target object on all browsers
Notes: 
Example:
***************************************************************/
gwwa.getEventTarget = function(e)
{
	return ( window.event !== null ) ? window.event.srcElement : e.currentTarget;
};


/***************************************************************
@gwwa.killEvent
Description: This method will suppress the event from propagation
				and prevent the default operation from taking place
Input:  event object
Output: boolean - false
Notes: This method suppresses events on all major browsers
Example:
***************************************************************/
gwwa.killEvent = function(evt)
{
	var e = gwwa.getEvent(evt);

	if( e.preventDefault )
	{
		e.preventDefault();
	}

	if( e.stopPropagation )
	{
		e.stopPropagation();
	}

	if( window.event )
	{
		window.event.cancelBubble = true;

		window.event.returnValue = false;
	}

	return false;
};

/***************************************************************
@gwwa.isVisible
Description: Determines if an element is visible on the page
Input:  elem: a document element (reference or id string)
Output: boolean - true if the element is visible
***************************************************************/
gwwa.isVisible = function(elem)
{
	if( typeof(elem))
		elem = $(elem);
	
	if (elem && elem.style.visibility == "visible" && elem.style.display != "none") {
		return true;
	}
	return false;
};

/***************************************************************
@gwwa.hideElement
Description: Hides an element by setting its display to 'none'
Input:  elem: a document element (reference or id string)
***************************************************************/
gwwa.hideElement = function(elem)
{
	elem = $(elem);
	
	//----------------------------------------------------------
	// Defect# 332301, 332308 (spalagiri): Script Error appears 
	// when "Properties"/"Advanced Properties" is selected on an
	// item. HTML Compose was assuming to find valid DOM nodes
	// for "idPlainTextTool" and "idHtmlTextTool". But they are
	// valid under "Mail" tab but not "Properties" and "Advanced 
	// Properties" tabs. So, before toggling the display of 
	// HTML/plain text message bodies, check for valid DOM node.
	//----------------------------------------------------------
	if( elem )
	{
		elem.style.display = "none";
	}
};

/***************************************************************
@gwwa.showElement
Description: Hides an element by setting its display to 'none'
Input:  elem: a document element (reference or id string)
        display: the display value to use (usually "block" or 
                 "inline"). Defaults to "block".
***************************************************************/
gwwa.showElement = function(elem, display)
{
	elem = $(elem);
	
	//----------------------------------------------------------
	// Defect# 332301, 332308 (spalagiri): Script Error appears 
	// when "Properties"/"Advanced Properties" is selected on an
	// item. HTML Compose was assuming to find valid DOM nodes
	// for "idPlainTextTool" and "idHtmlTextTool". But they are
	// valid under "Mail" tab but not "Properties" and "Advanced 
	// Properties" tabs. So, before toggling the display of 
	// HTML/plain text message bodies, check for valid DOM node.
	//----------------------------------------------------------
	if( elem )
	{
		display = display !== undefined ? display : "block";
		elem.style.display = display;
		elem.style.visibility = "visible";
	}
};

/*****************************************************
*
*****************************************************/
gwwa.showError = function( /*String*/ sErrorText )
{
	var errorMsg = inc_errGenericMsg;

	//--------------------------------------------
	// Alert the error message if a specific text
	// is available. Otherwise, use default text.
	//--------------------------------------------
	if( sErrorText )
	{
		errorMsg = sErrorText;
	}

	alert( errorMsg );
};

