/*
    Call the specified function onload.
*/
function common_old_style_onload(call_func, old_onload)
{
    window.onload = function(ev)
    {
        call_func(ev);

        if(old_onload)
            old_onload(ev);
    }
}

function common_onload(func)
{
    if(window.addEventListener)
    {
        window.addEventListener('DOMContentLoaded', func, false);
    }
    else if (window.attachEvent)
    {
        window.attachEvent('onload', func);
    }
    else
    {
        common_old_style_onload(func, window.onload);
    }
}

/*
    Attach the specified function to the named event for the element.
*/
function common_attach_event(elem, evname, func)
{
    if(elem.attachEvent)
    {
        elem.attachEvent('on' + evname, func);
    }
    else
    {
        elem.addEventListener(evname, func, false);
    }
}


/*
    Common function for working with classes for elements.
    Have a look at common_setup_class_funcs.
*/

COMMON_TRIM_SPACES = " \n\r\t	";

function common_trim(token)
{
    var begin = 0;
    var end = 0;
    var len = token.length - 1;
    while(begin <= len && COMMON_TRIM_SPACES.indexOf(token[begin]) >= 0)
    {
        ++begin;
    }
    if(begin > len)
        return '';
    while(end <= len && COMMON_TRIM_SPACES.indexOf(token[len - end]) >= 0)
    {
        ++end;
    }
    return token.substring(begin, len + 1 - end);
}

function common_has_class(className, clazz)
{
    return className.length > 0 && (' ' + className + ' ').indexOf(' ' + clazz + ' ') >= 0;
}

function common_add_class(className, clazz, enable)
{
    classNameEx = ' ' + common_trim(className) + ' ';
    clazzEx = ' ' + common_trim(clazz) + ' ';
    var pos;
    while((pos = classNameEx.indexOf(clazzEx)) >= 0)
    {
        classNameEx = classNameEx.substring(0, pos)
                    + ' '
                    + classNameEx.substring(pos + clazzEx.length, classNameEx.length);
    }
    if(enable)
    {
        classNameEx = common_trim(classNameEx + ' ' + clazz);
    }
    return classNameEx;
}

function common_setup_class_funcs(element)
{
    element.has_class = function(clazz) {
        return common_has_class(element.className, clazz);
    }
    element.add_class = function(clazz) {
        element.className = common_add_class(element.className, clazz, true);
    }
    element.remove_class = function(clazz) {
        element.className = common_add_class(element.className, clazz, false);
    }
}




