﻿/* IT Event Management JavaScript Library Version 2.0 */

var DHTML = (document.getElementById || document.all || document.layers);

/* Gets an object on a page */
/* Returns an entire html object and expects one parameter: */
/*      name = object's ID : string */
/* Usage Example: var obj = new GetObj("name"); */
function GetObj(name)
{
    if (document.getElementById)
    {
        this.obj = document.getElementById(name);
        this.style = document.getElementById(name).style;
    }
    else if (document.all)
    {
        this.obj = document.all[name];
        this.style = document.all[name].style;
    }
    else if (document.layers)
    {
        this.obj = document.layers[name];
        this.style = document.layers[name];
    }
}

/* Checks the visibility of an object */
/* Returns a boolean value and expects one paramater: */
/*        name = object's ID : string */
/* Usage Example: alert(IsVisible("name")); */
function IsVisible(name)
{
    if (!DHTML) return;
    var x = new GetObj(name);
    //If the visibility style has not been set, then it is by default visible.
    return (x.style.visibility == 'visible' || x.style.visibility == '');
}

/* Toggles an object's visiblity */
/* Expects one parameter: */
/*      name = object's ID : string */
/* Usage Example: ToggleVisibility("name"); */
function ToggleVisibility(name)
{
    if (!DHTML) return;
    var x = new GetObj(name);
    SetBlockVisibility(name, (x.style.visibility == 'hidden'));
}

/* Sets the visibility based on developer's discretion */
/* Expects two paramaters: */
/*      name = object's ID : string */
/*      flag = IsVisible : boolean */
/* Usage Example: SetVisibility("name", true); */
function SetInlineVisibility(name, flag)
{
    if (!DHTML) return;
    var x = new GetObj(name);
	x.obj.className = (flag) ? 'visible_inline' : 'invisible';
}

/* Sets the visibility based on developer's discretion */
/* Expects two paramaters: */
/*      name = object's ID : string */
/*      flag = IsVisible : boolean */
/* Usage Example: SetVisibility("name", true); */
function SetBlockVisibility(name, flag)
{
    if (!DHTML) return;
    var x = new GetObj(name);
    x.obj.className = (flag) ? 'visible_block' : 'invisible';
}

/* Checks if text is numeric                            */
/* Updated: 15/03/2009 - Clarice Billowes               */
/* Returns a boolean value and expects one parameter:   */
/*      text = text to be checked : string              */
/* Usage Example: alert(IsNumeric("12345"));            */
function IsNumeric(text)
{
    var validChars = "0123456789";
    var currentChar;
    
    for (var i = 0; i < text.length - 1; i++)
    {
        currentChar = text.charAt(i);
        if (validChars.indexOf(currentChar) == -1)
        {
            return false;
        }
    }
    return true;
}

/* Checks if text is a phone number */
/* Returns a boolean value and expects one parameter: */
/*      text = text to be checked : string */
/* Usage Example: alert(IsPhone("+27 011 4563")); */
function IsPhone(text)
{   
    //Allow spaces
    text = text.replace(" ","");
    if (text.charAt(0) == "+")
    {
        text = text.substring(1, text.length);
    }
    return IsNumeric(text);
}

/* Trim all trailing whitespaces */
/* Usage Example: myString.trim() */
String.prototype.trim = function() 
{
	return this.replace(/^\s+|\s+$/g,"");
}

/* Trim left hand side trailing whitespaces */
/* Usage Example: myString.ltrim()*/
String.prototype.ltrim = function() 
{
	return this.replace(/^\s+/,"");
}

/* Trim right hand side trailing whitespaces */
/* Usage Example: myString.rtrim() */
String.prototype.rtrim = function() 
{
	return this.replace(/\s+$/,"");
}

/* Only allows numbers to be entered */
/* Updated: 15/03/2009: Clarice */
/* Usage Example: onkeydown="return IsNumberKey(event);" onkeypress="return IsNumberKey(event);" */
function IsNumberKey(evt)
{
    var key;
    var keychar;

    if (window.event)
       key = window.event.keyCode;
    else if (evt)
       key = evt.which;
    else
       return true;
    keychar = String.fromCharCode(key);
    
    // control keys
    if ((key==null) || (key==0) || (key==8) || 
        (key==9) || (key==13) || (key==27) || 
        (key==35) || (key==36) || (key==37) || 
        (key==39) || (key==46))
        return true;
    
    return (("0123456789").indexOf(keychar) > -1);
}

/* Only allows numbers to be entered along with country code indicator (+) */
/* Usage Example: onkeypress="IsNumberKey(event);" */
function IsCellKey(evt, obj)
{
    var sel, rng, rng2, i = -1;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    //Check if the charCode is a + sign
    if (charCode == 43)
    {
        if (obj.value.length == 0)
        {
            return true;
        }
        else
        {
            if (typeof obj.selectionStart == "number")
            {
                i = obj.selectionStart;
            }
            else if (document.selection && obj.createTextRange)
            {
                sel = document.selection;
                if (sel)
                {
                    rng2 = sel.createRange();
                    rng = obj.createTextRange();
                    rng.setEndPoint("EndToStart", rng2);
                    i = rng.text.length;
                }
            }
            
            for (var j = 0; j < obj.value.length; j++)
            {
                if (obj.value.charAt(j).toString == "+")
                {
                    return false;
                }
            }
            return (i == 0);
        }
    }
    else
    {
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }
}

/* Determines if the user is holding in the shift key */
/* Usage Example: document.onkeypress=IsShiftKey; 
                  onkeypressed="IsShifKey(event);" */
function IsShiftKey(evt)
{
    var evtObj = window.event ? event : evt;
    return evtObj.shiftKey;    
}

/* Determines if the user is holding in the ctrl key */
/* Usage Example: document.onkeypress=IsCtrlKey; */
/*                onkeypressed="IsCtrlKey(event);"*/
function IsCtrlKey(evt)
{
    var evtObj = window.event ? event : evt;
    return evtObj.ctrlKey;    
}

/*Determines if the user is holding in the alt key*/
/*Example: document.onkeypress=IsAltKey; 
           onkeypressed="IsAltKey(event);"*/
function IsAltKey(evt)
{
    var evtObj = window.event ? event : evt;
    return evtObj.altKey;    
}

/* Allows the object to contain only the number of characters that has been initially set. */
/* NOTE: Please ensure to set the "maxlength" attribute of the object in your code. */
/* Usage Example: onkeyup="IsMaxLength(this); SetCharsRemaining(this, "name"); */
function IsMaxLength(obj)
{
    var mLength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : 255;
    if (obj.getAttribute && obj.value.length > mLength)
    {
        obj.value = obj.value.substring(0, mLength);
    }
}

/* Displays the amount of characters that the user has left due to max length attribute */
/* NOTE: Please ensure to set the "maxlength" attribute of the object in your code. */
/* Usage Example: onkeyup="IsMaxLength(this); SetCharsRemaining(this, "name"); */
function SetCharsRemaining(obj, labelName, labelText)
{
    var mLength = obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : 255;
    var cLength = parseInt(obj.value.length);
    var lbl = new GetObj(labelName)
    lbl.obj.innerText = String.format(labelText, (mLength - cLength).toString())
    //lbl.obj.innerText = '(' + (mLength - cLength).toString() + ') char(s) remaining.';
}

/* Checks if a value is present in an Array */
/* Usage Example: myArray.inArray("test"); */
Array.prototype.inArray = function (value) 
{
    for (var i = 0; i < this.length; i++)
    {
        if (this[i] == value)
        {
            return true;
        }
    }
    return false;
}

/* Allows for support as some older browsers cannot use latest split() function */
/* Usage Example: 
        var strvalue = "abc##123##zzz##$$$";
        var returnArraySize = Split(strvalue, "##", "NewArray");
        The above will create the following:
        NewArray[0] has value "abc"
        NewArray[1] has value "123"
        NewArray[2] has value "zzz"
        NewArray[3] has value "$$$"
        returnArraySize      has value "4"
*/
function Split(value, separator, arrayName)
{
    var n = 0;
    if (separator.length != 0)
    {
        while (value.indexOf(separator) != -1)
        {
            eval("arr" + n + " = value.substring(0, value.indexOf(separator));");
            value = value.substring(value.indexOf(separator) + separator.length, value.length + 1);
            n++;
        }
        eval("arr" + n + " = value;");
        arraySize = n + 1;
    }
    else
    {
        for (var i = 0; i < value.length; i++)
        {
            eval("arr" + n + " = \"" + value.substring(i, i+1) + "\"'");
            n++;
        }
        arraySize = n;
    }
    eval(arrayName + " = new MakeArray(arraySize);");
        
    for (var i = 0; i < arraySize; i++)
    {
        eval(arrayName + "[" + i + "] = arr" + i + ";");
    }
    return arraySize;
}

/* Create an array object */
/* Expects one parameter: */
/*      iArraySize = length of the array to be created : integer */
/* Usage Example: newArray = new MakeArray(3); */
function MakeArray(iArraySize)
{
    for (var i = 0; i < iArraySize; i++)
    {
        this[n]= "";
    }
    return this;
}

/* Print the floating point number with certain decimal point. */
/* Expects three paramters:
        value = the floating point number which will be formatted : number
        addZero = determines whether to add 0 at end of floating point number of not : boolean
        nDecimal = number of decimals (default 2) : decimal */        
/* Usage Example: FormatDecimal("123.233333333", true, 2) */
function FormatDecimal(value, addZero, nDecimal)
{
    var numOfDecimal = (nDecimal == null) ? 2 : nDecimal;
    var number = Math.pow(10, numOfDecimal);
    value = Math.round(parseFloat(value) * number) / number;
    value = value.toString();
    
    if (value.indexOf(".") == 0)
        value = "0" + value;
    if (addZero)
    {
        if (value.indexOf(".") == -1)
            value = value + "."
            
        while ((value.indexOf(".") + 1) > (value.length - numOfDecimal))
            value = value + "0";
    }
    return value;
}

/* Allows for the formatting of text */
/* Usage Example: String.format("Hello {0}", "Tester"); -->Result: Hello Tester */
String.format = function(text)
{
    //check if there are two arguments in the arguments list
    if ( arguments.length <= 1 )
    {
        //if there are not 2 or more arguments there’s nothing to replace
        //just return the original text
        return text;
    }
    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for( var token = 0; token <= tokenCount; token++ )
    {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ), arguments[token + 1] );
    }
    return text;
};