/*
Common PUBLIC library with misc routines.
*/

// *****************************************************************************
// Removes leading whitespaces
function LTrim(value) {

    if (value) {
        var re = /\s*((\S+\s*)*)/;
        return value.replace(re, "$1");
    }
    else return '';
}
// *****************************************************************************
// Removes ending whitespaces
function RTrim(value) {

    if (value) {
        var re = /((\s*\S+)*)\s*/;
        return value.replace(re, "$1");
    }
    else return '';
}
// *****************************************************************************
// Removes leading and ending whitespaces
function trim(value) {

    return LTrim(RTrim(value));
}
// *****************************************************************************
function GetDOM(elemID) {
    if (document.getElementById) {
        method = 1;
    } else if (document.all) {
        method = 2;
    } else {
        method = 0;
    }

    return (method == 1) ? document.getElementById(elemID) : document.all[elemID];
}
// *****************************************************************************
function ParentGetDOM(elemID) {
    if (document.getElementById) {
        method = 1;
    } else if (document.all) {
        method = 2;
    } else {
        method = 0;
    }

    return (method == 1) ? window.parent.document.getElementById(elemID) : window.parent.document.all[elemID];
}
// *****************************************************************************
function IsIE5() {
    return document.all && document.getElementById;
}
function IsNS6() {
    return document.getElementById && !document.all;
}
// *****************************************************************************
// Hides an HTML object identified by its ID
function Hide(elementid) {
    var it;

    it = GetDOM(elementid);

    if (it != null)
        it.style.display = 'none';

    return 1;
}
// *****************************************************************************
// Shows an HTML object identified by its ID
function Show(elementid) {
    var it;

    it = GetDOM(elementid);

    if (it != null)
        it.style.display = '';

    return 1;
}
// *****************************************************************************
// Toggles the visiblity of an HTML object identified by its ID. Sometimes this function is not recognized,
// probably because some other library (Scriptaculous?) has one with the same name. Use ToggleVisible() instead. 
function Toggle(elementid) {
    ToggleVisible(elementid)
}

// Toggles the visiblity of an HTML object identified by its ID
function ToggleVisible(elementid) {
    var it;

    it = GetDOM(elementid);

    if (it != null) {
        if (it.style.display == '')
            it.style.display = 'none';
        else
            it.style.display = '';
    }

    return 1;
}

// Toggles the class of an HTML object identified by its ID and assigns a new class depending on the visibility
function ToggleClassOnVisibility(elementid, VisibleClass, HiddenClass) {
    var it;

    it = GetDOM(elementid);

    if (it != null) {
        if (it.style.display == '') {
            it.className = HiddenClass;
        }
        else {
            it.className = VisibleClass;
        }
    }

    return 1;
}

// Toggles the class of an HTML object identified by its ID and assigns a new class depending on another element's visibility
function ToggleClassOnAnotherElementsVisibility(ChangeClassElementId, VisibilityElementId, VisibleClass, HiddenClass) {

    var ChangeClassElement;
    var VisibilityElement;

    ChangeClassElement = GetDOM(ChangeClassElementId);
    VisibilityElement = GetDOM(VisibilityElementId);

    if (ChangeClassElement != null & VisibilityElement != null) {
        if (VisibilityElement.style.display == '') {
            ChangeClassElement.className = VisibleClass;
        }
        else {
            ChangeClassElement.className = HiddenClass;
        }
    }

    return 1;
}

// *****************************************************************************
// Toggles the visiblity of the child objects of an HTML object identified by its ID.
// The visiblity of all child elements is set to the same value, which is determined
// from the current state of the first child element.
// A child object is only altered if it is the specified tag type and its ID 
// begins with a specified prefix.
function ToggleSimpleChildrenVisible(elementid, tagname, prefix, ignoreitems) {
    var it = GetDOM(elementid);
    if (it != null) {
        var x = it.getElementsByTagName(tagname);
        if (x.length > 0) {
            var newdisplay = '';
            var found = false;
            var ignore = '';

            if (ignoreitems)
                ignore = ignoreitems.split(',');  // Loads an array with the items to be ignored

            for (i = 0; i < x.length; i++)
                if (x[i].id.substring(0, prefix.length) == prefix) {
                // The item matches the prefix but is it in the ignore list?
                if (GetArrayElementIndex(ignore, x[i].id) < 0) {
                    if (!found) {
                        if (x[i].style.display == '')
                            newdisplay = 'none';
                        else
                            newdisplay = '';
                        found = true;
                    }
                    x[i].style.display = newdisplay;
                }
            }
        }
    }
}
function ToggleChildrenVisible(elementid, tagname, prefix, ignoreitems, sender) {
    var it = GetDOM(elementid);
    if (it != null) {
        var x = it.getElementsByTagName(tagname);
        if (x.length > 0) {
            var newdisplay = '';
            var found = false;
            var ignore = '';

            if (ignoreitems)
                ignore = ignoreitems.split(',');  // Loads an array with the items to be ignored
            var isGroupHeader = ((((document.getElementById(sender)).getElementsByTagName('td'))[0]).className == 'GroupHeader');
            for (i = 0; i < x.length; i++) {
                if (x[i].id.substring(0, prefix.length) == prefix) {
                    var isGroupHeaderInner = (((x[i].getElementsByTagName('td'))[0]).className == 'GroupHeaderInner');
                    // The item matches the prefix but is it in the ignore list?

                    if (isGroupHeader) {
                        if (isGroupHeaderInner) {
                            if (x[i].style.display == '')
                                newdisplay = 'none';
                            else
                                newdisplay = '';
                            x[i].style.display = newdisplay;
                        }
                        else {
                            x[i].style.display = 'none';
                        }
                    }
                    else {
                        if (GetArrayElementIndex(ignore, x[i].id) < 0) {
                            if (!found) {
                                if (x[i].style.display == '')
                                    newdisplay = 'none';
                                else
                                    newdisplay = '';
                                found = true;
                            }
                            x[i].style.display = newdisplay;
                        }
                    }
                }
            }
        }
    }
}
//*******************************************************************************
function DeleteArrayElement(array, iwhich) {
    size = array.length;
    delindex = iwhich;
    validNo = (iwhich != "NaN");
    inRange = ((iwhich >= 0) && (iwhich <= array.length));

    if (validNo && inRange) {

        for (var j = iwhich; j < size - 1; j++)
            if (j != size)
            array[j] = array[j + 1];

        array.length = size - 1;
    }
}
/************************************************************************************************/
// Removes an element with the given value from an array 
function DeleteArrayElementByValue(array, value) {
    DeleteArrayElement(array, GetArrayElementIndex(array, value));
}
/************************************************************************************************/
// Returns the index of an element within an array
function GetArrayElementIndex(array, value) {
    for (var j = 0; j < array.length; j++)
        if (array[j] == value)
        return j;

    return -1;
}
/************************************************************************************************/
//adds onLoadEvent
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
/************************************************************************************************/
//not used - Javascript does not allow declaring method of the same name with different number of parameters?
function email(to, domain) {
    emailE = (to + '@' + domain);
    document.write('<A href="mailto:' + emailE + '">' + emailE + '</a>');
}
/************************************************************************************************/
function email(to, domain, text) {
    emailE = (to + '@' + domain);
    if (text == undefined)
        document.write('<A href="mailto:' + emailE + '">' + emailE + '</a>');
    else
        document.write('<A href="mailto:' + emailE + '">' + text + '</a>');
}
/************************************************************************************************/
//Javascript to copy to clipboard
function ClipBoard(text, cell) {
    var browser = navigator.appName;
    if (browser == 'Microsoft Internet Explorer')
        window.clipboardData.setData('Text', text);
    select(document.getElementById(cell));
}
var select = function(el) {
    if (window.getSelection) { // FF, Safari, Opera
        var sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
        alert('Please press Ctr + C to copy the link');
    }
    else if (document.selection) { // IE
        document.selection.empty();
        var range = document.body.createTextRange();
        range.moveToElementText(el);
        range.select();
        alert('The link is copied');
    }
}
/************************************************************************************************/
function getElementsByClassName(classname, node) {
    if (!node)
        node = document.getElementsByTagName("body")[0];

    var a = [];

    var re = new RegExp('\\b' + classname + '\\b', 'i');  // i: Ignore case
    var els = node.getElementsByTagName("*");

    for (var i = 0, j = els.length; i < j; i++)
        if (re.test(els[i].className)) a.push(els[i]);

    return a;
}
/************************************************************************************************/
function findPosX(obj) {
    var curleft = 0;

    if (obj) {
        if (obj.offsetParent)
            while (1) {
            curleft += obj.offsetLeft;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
        else if (obj.x)
            curleft += obj.x;
    }

    return curleft;
}
// *** See note above *** //
function findPosY(obj) {
    var curtop = 0;

    if (obj) {
        if (obj.offsetParent)
            while (1) {
            curtop += obj.offsetTop;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
        else if (obj.y)
            curtop += obj.y;
    }

    return curtop;
}

/************************************************************************************************/
// Position an element relatively to another control. sParent indicates the control that acts as coords 0,0 for the elements.
function PositionRelative(sPositionElem, sRelativeTo, sParent, iLeftOffset, iTopOffset) {

    return PositionRelative(sPositionElem, sRelativeTo, sParent, iLeftOffset, iTopOffset, '');
}

function PositionRelative(sPositionElem, sRelativeTo, sParent, iLeftOffset, iTopOffset, jQuerySelector) {

    var PositionElem = GetDOM(sPositionElem);
    var RelativeTo = GetDOM(sRelativeTo);
    var Parent = GetDOM(sParent);

    if (PositionElem != null) {
        // If PositionElem is hidden, show now
        if (PositionElem.style.display == 'none') {

            if ((typeof (jQuery) != 'undefined') && (jQuerySelector)) {
                jQuery.noConflict();
                //jQuery(jQuerySelector).show('slow');
                jQuery(jQuerySelector).fadeIn();
                //jQuery(jQuerySelector).slideDown();    
            }
            else
                Show(sPositionElem);

            var RelativeTo_X = findPosX(RelativeTo);
            var RelativeTo_Y = findPosY(RelativeTo);

            PositionElem.style.left = RelativeTo_X + iLeftOffset + "px";
            PositionElem.style.top = RelativeTo_Y + iTopOffset + "px";

            // In case Postionelem has a positioned ancestor (wrapper), we reassign it to the document form (body won't work)
            // so that it's nearest positioned ancestor will be the document body itself.
            document.forms[0].appendChild(PositionElem);

            //alert("Rel.To_Y=" + RelativeTo_Y + "; Offset=" + iTopOffset + "; final style.top = " + PositionElem.style.top);        
        }
        else
            Hide(sPositionElem);

    }
    return false;
}
/**************************************************************************************************/
// Bursts the "Propagation bubble" that occurs when you have nested elements with their own onclick
// events (a link in a TD element for example). This function stops the event bubbling to the parent
// elements event.

// Microsoft Model uses cancelBubble, where the W3C model doesn't support this and uses stopPropagation()
// instead. The following function is therefore cross-browswer compatible

function BurstBubble(e) {
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}


/************************************************************************************************/
