// Trim
function trimAll(sString)    
{
    while (sString.substring(0,1) == ' ')
    {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ')
    {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
};

// Arrays
function ExistsInArray(arr, obj)
{
    for(var i=0;i<arr.length;i++)
    {
        if(arr[i] == obj)
        {
            return true;
        }
    }
    return false;
};

function RemoveFromArray(arr, obj)
{
    for(var i=0;i<arr.length;i++)
    {
        if(arr[i] == obj)
        {
            // Found the item to remove
            arr.splice(i, 1);
            return true;
        }
    }
    return false;
};

function RemoveFromArrayByIndex(arr, index)
{
    if(index > arr.length - 1 || index < 0) return arr;
    var ret = new Array();
    
    for(var i=0;i<arr.length;i++)
    {
        if(i != index)
        {
            ret.push(arr[i]);
        }
    }
    return ret;
};

function IndexOf(array, obj)
{
    var ret = -1;
    
    for(var i = 0; i < array.length; i++)
    {
        if(array[i] == obj)
        {
            ret = i;
            break;
        }
    }
    return ret;
};

function ArrayFromStr(str, divideStr)
{
    if (str == null || trimAll(str) == "")
    {
        return new Array();
    }
    var strArray = str.split(divideStr);
    var ret = new Array();
    for(var i=0; i<strArray.length; i++)
    {
        var s = trimAll(strArray[i]);
        ret.push(s);
    }
    return ret;
};

function StrFromArray(arr, divideStr)
{
    if(arr.length == 0) return "";
    
    var ret = "";
    for(var i=0;i<arr.length;i++)
    {
        // Found the item to remove
        ret+= arr[i].toString() + divideStr;
    }
    
    ret = ret.substring(0, ret.length - divideStr.length); // remove trailing item e.g. ", "
    return ret;
};

function ArrayFromCsv(csv) { return ArrayFromStr(csv, ","); };
function CsvFromArray(arr) { return StrFromArray(arr, ", "); };

function ArrayFromClassNames(cNames) { return ArrayFromStr(cNames, " "); };
function ClassNamesFromArray(arr) { return StrFromArray(arr, " "); };

function AddClass(cClass, className)
{
    var arr = ArrayFromClassNames(cClass);
    if(!ExistsInArray(arr, className))
    {
        arr.push(className);
    }
    return ClassNamesFromArray(arr);
};

function ReplaceClass(cClass, newClassName, oldClassName)
{
    if(cClass.indexOf(oldClassName) != -1)
    {
        return cClass.replace(oldClassName, newClassName);
    }
    else return AddClass(cClass, newClassName);
};

function RemoveClass(cClass, className)
{
    var arr = ArrayFromClassNames(cClass);
    RemoveFromArray(arr, className);
    return ClassNamesFromArray(arr);
};

function RemoveClasses(cClass, classes)
{
    var arr = ArrayFromClassNames(cClass);
    for(var i=0;i<classes.length;i++)
    {
        RemoveFromArray(arr, classes[i]);
    }
    return ClassNamesFromArray(arr);
};

// Href (_target) Links
function setTarget(e, target)
{
	//Get source element...
	var eSrc;
     if( !e )
     {
         eSrc = window.event.srcElement;
     }
     else
     {
         eSrc = e.srcElement;
         if( !eSrc )
             eSrc = e.target;
     }
	
	//Walk up tree until we get to an A. 
	while(eSrc.tagName != "A" && String(eSrc) != "undefined" )
	{
		if(eSrc.parentElement)
			eSrc = eSrc.parentElement;
		else
			eSrc = eSrc.parentNode;
	}
	
	//Set the target.
	eSrc.target=target;
	
	return false;
};

// Html Elements
function getElement(eID)
{
	var ret = null;
	
	if( document.layers )	//NS method.
	{
		try
		{
			ret = document.layers(eID);
		}
		catch(e){}
	}
	else if( document.getElementById )			   //W3C method.
	{
		try
		{
			ret = document.getElementById(eID);
		}
		catch(e){}
	}
	else if( document.all )			   //IE method.
	{
		try
		{
			ret = document.all(eID);
		}
		catch(e){}
	}
	//else element not found.
	return ret;
};

function $(id) { return getElement(id); };

function getFormElement(eID)
{
	var ret = null;
	if( document.forms[0].all != null ) //IE method.
	{		
		try
		{
			ret = document.forms[0].all(eID);
		}
		catch(e){}		

		if (ret == null) 
			ret = $(eID); 
	}
	else if( document.forms[0].elements != null ) //IE method.
	{			
		try
		{
			ret = document.forms[0].elements[eID]; // Mozilla method.
		}
		catch(e){}
				
		if (ret == null) 
			ret = $(eID); 
	}
	else
	{
		alert('getFormElement required for this browser');
	}
	return ret;
};

function $$(eID) { return getFormElement(eID); };

// Forms
function blankInput(n, t)
{
	var el = getElement(n);
	
	if(el.value == t)
		el.value = "";
};

function restoreDefault(n, t)
{
	var el = getElement(n);
	if(el.value == "")
		el.value = t;
};

function actionControlClick(e, ActionControlId, methodName)
{
    try
	{
        var result = eval(methodName + "();");
        if(!result)
        {
            window.event.cancelBubble = true;
            return false;
        }
	}
	catch(err){}
	return true;
};

function textBoxKeyPress(e, ActionControlId)
{	
	try
	{
	    var ie = (document.all)?true:false;
        var nn = (document.layers)?true:false;
	    var icode, ncode, key;
	
		if(ie)
		{
			icode = event.keyCode;
			ncode = 0;
			key = String.fromCharCode(event.keyCode);
		}
		else if(nn)
		{
			icode = 0;
			ncode = e.which;
			key = String.fromCharCode(e.which);
		}
		else
		{ 
			icode = e.charCode
			ncode = e.which;
			key = String.fromCharCode(e.which);	
		}
		
		if(icode == 13 || ncode == 13)
		{
		    // Find the actioncontrol
		    var aControl = getFormElement(ActionControlId);
		    if(aControl != null)
		    {
		        aControl.click();
                return false; // cancel this event
		    }
		}
	}
	catch(err){}
	return true;
};

function PopupWindow(URL,Width,Height)
{
	PopupWindowScrollbars(URL,Width,Height,true);
};

function PopupWindowScrollbars(URL,Width,Height,Scrollbars)
{
	try
	{
		// support a default size
		if (Width == "" || Width == null) Width =486;
		if (Height == "" || Height == null) Height =500;
		
		var features= 'directories=0,location=0,menubar=0,status=0,toolbar=0,resizable=1,screenX=15,screenY=15,top=15,left=15' +
		',width=' + Width +
		',height=' + Height;
		
		if(Scrollbars)
		{
			features += ',scrollbars=1';
		}
		else
		{
			features += ',scrollbars=0';
		}
		URL = URL.replace(/\s/,'%20');
		var w=window.open (URL, '', features);
		w.focus();
	}
	catch(e){}
};

function CancelEvent()
{
    window.event.cancelBubble = true;
    return false;
};

// Call with variable no of arguments
function PreloadImages()
{
	var lenArg = arguments.length;
	if (lenArg > 0)
	{
		var imgArr = new Array();
		for (var i = 0; i < lenArg; i++)
		{
			if(arguments[i] != null)
			{
				imgArr[i] = new Image();
				imgArr[i].src = arguments[i];
			}
		}
	}
};

function ptrEvt(id) 
{
    try 
    { 
        if(document.dispatchEvent)  // For W3 / FF 
            window.open($(id).href, "_parent");
        else 
            $(id).click();          // For IE 
    } 
    catch (ex) 
    {
        return false; 
    }   
};

function FindChildRecursive(obj, tag, attrName, attrVal)
{
	var ret = null;
	
	// Find the text link using the DOM
	for(var i=0; i < obj.children.length; i++)
	{
		var child = obj.children[i];
		if(child.tagName == tag)
		{
			if(attrName != null && attrVal != null)
			{
				if(eval('child.' + attrName) == attrVal)
				{
					ret = child;
				}
			}
			else
			{
				// This supports just looking for a tag
				ret = child;
			}
		}
		
		if(ret == null)
		{
			ret = FindChildRecursive(child, tag, attrName, attrVal);
		}
	}
	return ret;
};

function addEvent(object, eventName, functionPtr)
{
    if(window.addEventListener)
    {
        object.addEventListener(eventName, functionPtr, false);
    }
    else if(window.attachEvent)
    {
        object.attachEvent("on" + eventName, functionPtr);
    }
};

function AddFavourite(title, url)
{
	if (window.sidebar)
	{
		// Mozilla Firefox Bookmark
		window.sidebar.addPanel(unescape(title), unescape(url), '');
	}
	else if( window.opera && window.print )
	{
		var mbm = document.createElement('a');
		mbm.setAttribute('rel','sidebar');
		mbm.setAttribute('href',unescape(url));
		mbm.setAttribute('title',unescape(title));
		mbm.click();
    }
	else if( window.external )
	{
		// IE Favorite
		window.external.AddFavorite(unescape(url), unescape(title));
	}
	else
	{
		alert("Sorry adding a bookmark is not supported on this browser. You will have to add the bookmark/favourite manually.");
	}
};