var b_colors = new Array();
                          // def bg         // over bg      // over border
b_colors['t'] = new Array('#C3DAF9',        '#ffffff',      'ButtonShadow');    // toolbar
b_colors['s'] = new Array('ButtonFace',     '#ffffff',      'ButtonShadow'); // section
b_colors['w'] = new Array('Window',         '#ffffff',      'ButtonShadow');     // tab

function b_hover (scope, cell, state)
{
    if (1 == state)
    {
        // mouse in
        //cell.style.MozOpacity= (cell.style.MozOpacity - 0.6);
        //cell.filters.alpha.opacity= (cell.filters.alpha.opacity - 60);
        cell.style.backgroundColor = b_colors[scope][1];
        cell.style.borderColor = b_colors[scope][2];
    }
    else
    {
        // mouse out
        //cell.style.MozOpacity=1;
        //cell.filters.alpha.opacity=100;
        cell.style.backgroundColor = b_colors[scope][0];
        cell.style.borderColor = b_colors[scope][0];
    }
}

function tb_save (formId)
{
//    document.getElementById('form_' + formId).submit();
    document.forms[0].submit();
}

function tb_enable (button)
{
    document.getElementById('tb_' + button).disabled = false;
}

function tb_begin_new(formId)
{
    var f = document.forms['form_'+formId];
    //f.elements['action'].value = 'new';
    var url = document.location.toString();
    url = url.replace(/&objectID=[0-9]+/,'');
    if(-1 == url.indexOf('action'))
    {
        url = url + '&action=new';
    }
    else
    {
        url = url.replace(/&action=[^&]+/,'&action=new');
    }
    f.action = url;
    f.formID.value = '';
    f.submit();
}

function task_begin_email(formId)
{
    var f = document.forms['form_'+formId];

    var url = document.location.toString();
    url = url.replace(/&module=[^&]+/,'&module=email')
    url = url.replace(/&objectID=[^&]+/,'')
    url = url.replace(/&msg=[^&]+/,'');
    url = url + '&action=new';
    f.action = url;

    f.description.name = 'textbody';
    f.formID.value = '';

    f.submit();
}


function navi (url, popup, size)
{
    if (1 != popup)
    {
        window.location.href = url;
    }
    else
    {
        var width = 780;
        var height = 660;
        if (1 == size)
        {
            // first set of sizes
            height = 550;
        }

        var re = RegExp('[^A-Za-z0-9]*', 'g');
        var name = url.replace(re, '');
        if (0 < name.indexOf('actionnew'))
        {
            // new window, add unique hash
            name += randomString(4);
        }
        w = window.open(url, name,  'scrollbars=0,status=01,menubar=0,location=0,toolbar=0,width=' + width + ',height=' + height +',resizable=1,top=0,left=100');
        if (w.opener == null) w.opener = self;
        w.focus();
    }
}

function randomString (string_length)
{
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i=0; i<string_length; i++)
    {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomstring;
}
function switch_lookups_content (firstLookupID, secondLookupID)
{
	eval('var bufferItems = form_lookup_' + firstLookupID);
	eval('form_lookup_' + firstLookupID + ' = form_lookup_' + secondLookupID);
	eval('form_lookup_' + secondLookupID + ' = bufferItems');
    form_lookup_init(firstLookupID);
    form_lookup_init(secondLookupID);
}
function form_lookup_init (listID, skipBounds)
{
    // empty all previously added items in cell
    document.getElementById('f' + listID).innerHTML = '<br />';
    eval('var items = form_lookup_' + listID); // array of list items
    var str = String(); // future cell HTML
    if (0 < items.length)
    {
        for (var i = 0; i < items.length; i++)
        {
            // compose an HTML list from items array
            if (0 != i)
            {
                // non-first item, add a separator
                str += ', ';
            }
            if ('string' == typeof(items[i]))
            {
                // plain text item without links or icons
                str += '<span><a href="javascript:form_lookup_navi(\'' + listID + '\', ' + i + ')" class="notlinked">' + htmlspecialchars(items[i]) + '</a></span>';
            }
            else
            {
                // an item with icon and link
                str += '<span><a href="javascript:form_lookup_navi(\'' + listID + '\', ' + i + ')">';
                str += '<img src="public/16_' + items[i][2] +'.png" />' + items[i][1];
                str += '</a></span>';
            }
        }
        // assign HTML to list cell
        document.getElementById('f' + listID).innerHTML = str;
    }
    // assign value to form field
    form_lookup_init_value(listID, items);
    // and finally initialize allowed controls
    form_lookup_init_controls(listID, items.length);

    if (row = document.getElementById('r' + listID))
    {
        if ('block' != row.style.display && 0 != items.length)
        {
            // display collapsed field
            row.style.display = 'block';
        }
    }

    if (1 != skipBounds)
    {
        form_lookup_init_bounds(listID);
    }
}

function form_lookup_navi (listID, item)
{
    eval('var items = form_lookup_' + listID); // array of list items
    var field = document.getElementById('f' + listID);
    if (-1 != field.className.indexOf(' edit'))
    {
        /* Editable field, remove item. */
        items.splice(item, 1);
        form_lookup_init(listID);
    }
    else
    {
        /* Redirect using object link. */
        if (items[item][3])
        {
            if ('files' == listID)
            {
                // No popups for files.
                navi(items[item][3], 0);
            }
            else
            {
                navi(items[item][3], 1);
            }
        }
    }
}

function form_lookup_init_value (listID, items)
{
    if (document.getElementById('f' + listID + '_value').getAttribute('single') &&
        0 < items.length)
    {
        // only single value is allowed
        if ('string' == typeof(items[0]))
        {
            // string value
            document.getElementById('f' + listID + '_value').value = items[0];
        }
        else
        {
            // array with icon and link value
            document.getElementById('f' + listID + '_value').value = items[0][0];
        }
    }
    else if (0 < items.length)
    {
        // array of multiples
        var values = Array(items.length);
        for (var i = 0; i < items.length; i++)
        {
            if ('string' == typeof(items[i]))
            {
                values[i] = items[i];
            }
            else
            {
                values[i] = items[i][0];
            }
        }
        document.getElementById('f' + listID + '_value').value = values.join('|');
    }
    else
    {
        // empty value
        document.getElementById('f' + listID + '_value').value = '';
    }
}

function form_lookup_init_controls (listID, items)
{
    var field = document.getElementById('f' + listID);
    var index = field.className.indexOf(' edit');

    document.getElementById('f' + listID + '_controls').innerHTML = '';
    var str = String();
    if (1 == items && !document.getElementById('f' + listID + '_value').getAttribute('readonly'))
    {
        // single item, delete button
        str = '<img onclick="form_lookup_delete(\'' + listID + '\')" src="public/16_delete.png" />';
    }
    else if (1 < items && !document.getElementById('f' + listID + '_value').getAttribute('readonly'))
    {
        // more then one item, edit button
        str = '<img onclick="form_lookup_edit(\'' + listID + '\')" src="public/16_delete.png" />';
    }
    else if (-1 != index)
    {
        /* Close field for editing. */
        field.className = field.className.substring(0, index);
    }

    document.getElementById('f' + listID + '_controls').innerHTML = str;
}

function form_lookup_edit (listID)
{
    var field = document.getElementById('f' + listID);
    var index = field.className.indexOf(' edit');
    if (-1 != index)
    {
        /* Close field for editing. */
        field.className = field.className.substring(0, index);
    }
    else
    {
        /* Open for editing. */
        field.className += ' edit';
    }
}


function form_lookup_add (listID, item)
{
    if(-1 != item.indexOf('||'))
    {
        item = unescape(item).split('||');
    }
    if (document.getElementById('f' + listID + '_value'))
    {
        // lookup value
        eval('var items = form_lookup_' + listID);
        if (document.getElementById('f' + listID + '_value').getAttribute('single'))
        {
            // only single item is allowed, replace first one
            items[0] = item;
        }
        else
        {
            // multiple allowed, add new one
            items[items.length] = item;
        }
        form_lookup_init(listID);
    }
    else if ('replacementID' == listID)
    {
        // a hack used only for object replacement
        document.location += '&replacementID=' + item[0];
    }
}

function form_lookup_delete (listID, item)
{
    eval('items = form_lookup_' + listID);
    if (0 < item)
    {
        // delete selected item from list
        alert('here');
    }
    else
    {
        // delete all items
        items = new Array();
    }
    eval('form_lookup_' + listID + ' = items');
    form_lookup_init(listID);
}

function form_lookup_pump (sourceID, formID)
{
    if (document.frames[sourceID].document.forms[formID].items.length)
    {
        // many items in list
        for (var i=0; i<document.frames[sourceID].document.forms[formID].items.length; i++)
        {
            if (document.frames[sourceID].document.forms[formID].items[i].checked)
            {
                if ('listlinkedID' == callbackField)
                {
                    // email link action
                    opener.frames[0].document.forms[1].list_action.value = 'link';
                    var linkedID = document.frames[sourceID].document.forms[formID].items[i].value;
                    linkedID = unescape(linkedID).split('||');
                    opener.frames[0].document.forms[1].linkedID.value = linkedID[0];
                    opener.frames[0].document.forms[1].submit();
                }
                else
                {
                    opener.form_lookup_add(callbackField, document.frames[sourceID].document.forms[formID].items[i].value);
                }
            }
        }
    }
    else if (document.frames[sourceID].document.forms[formID].items.value)
    {
        // single one
        if ('listlinkedID' == callbackField)
        {
            // email link action
            opener.frames[0].document.forms[1].list_action.value = 'link';
            var linkedID = document.frames[sourceID].document.forms[formID].items.value;
            linkedID = unescape(linkedID).split('||');
            opener.frames[0].document.forms[1].linkedID.value = linkedID[0];
            opener.frames[0].document.forms[1].submit();
        }
        else
        {
            opener.form_lookup_add(callbackField, document.frames[sourceID].document.forms[formID].items.value);
        }
    }
    window.close();
}

/* adds single list values to callback filed and submits target from */
function form_single_pump (sourceID, formID)
{
    var valueArr = Array();
    var values = 0;
    for (var i=0; i<document.frames[sourceID].document.forms[formID].elements.length; i++)
    {
        if ('items[]' == document.frames[sourceID].document.forms[formID].elements[i].name)
        {
            if (document.frames[sourceID].document.forms[formID].elements[i].checked)
            {
                var arr = unescape(document.frames[sourceID].document.forms[formID].elements[i].value).split('||');
                valueArr[values] = arr[0];
                values ++;
            }
        }
    }
    eval('opener.document.forms[0].' + callbackField + '.value = valueArr;');
    opener.document.forms[0].submit();
    window.close();
}

function form_lookup_pump_email ()
{
    opener.form_lookup_add(callbackField, document.getElementById('freetext').value);
    window.close();
}

function form_lookups_init_bounds ()
{
    notbound_lookups = notbound_lookups.split(',');
    for (var i = 0; i < notbound_lookups.length; i ++)
    {
        form_lookup_init_bounds(notbound_lookups[i]);
    }
}

/* Ajusts widths of items container and edit's one. */
function form_lookup_init_bounds (listID)
{
    var container = document.getElementById(listID + '-Container');
    if (container)
    {
        var containerItems = document.getElementById('f' + listID);
        var containerEdit = document.getElementById(listID + '-ContainerEdit');

        containerEdit.width = '100%';
        containerItems.style.whiteSpace = 'nowrap';
        var itemsWidth = containerItems.offsetWidth;
        containerItems.style.whiteSpace = 'normal';

        if (itemsWidth > 0)
        {
            var minEditWidth = 50;
            if (itemsWidth > parseInt(container.offsetWidth) - minEditWidth)
            {
                containerItems.width = '';
                containerEdit.style.width = minEditWidth + 'px';
                containerItems.style.whiteSpace = 'normal';
            }
            else
            {
                containerItems.width = '';
                containerItems.style.whiteSpace = 'nowrap';
                containerEdit.width = '100%';
            }
        }
    }
}

function prepare_datetime (field)
{
    var date = document.getElementById('f' + field + '_date').value;
    var time = document.getElementById('f' + field + '_time').value;
    if (date.length > 0 && time.length > 0)
        document.getElementById('f' + field).value = date + ' ' + time;
    else
        document.getElementById('f' + field).value = '';
    setTimeout('prepare_datetime(\'' + field + '\')');
}

function prepare_period ()
{
    prepare_datetime('begins');
    prepare_datetime('ends');
}

function prepare_dateperiod ()
{
    //    Visible fields.
    var vis_begins = document.getElementById('f_begins');
    var vis_ends = document.getElementById('f_ends');

    //    Hidden fields.
    var hid_begins = document.getElementById('fbegins');
    var hid_ends = document.getElementById('fends');

    hid_begins.value = vis_begins.value;
    hid_ends.value = vis_ends.value;
    setTimeout('prepare_dateperiod()');
}

function tb_activate ()
{
}

function tb_delete ()
{
}

function tb_help ()
{
}

function tb_print ()
{
}

function activity_completion (checkbox, responsible)
{
    if (document.getElementById('f' + responsible + 'ID_value').value == document.getElementById('fownerID_value').value &&
        checkbox.checked)
    {
        // responsible is the same as owner and activity is completed
        // mark it as checked also
        document.getElementById('fchecked').checked = true;
    }
    else
    {
        document.getElementById('fchecked').checked = false;
    }
}

function desktop_search ()
{
    var search = document.forms['search'];
    navi(search.text.getAttribute('url') + '&text=' + search.text.value + '&object=' + search.object[search.object.selectedIndex].value, 1, 1);
}

// replace html special chars to codes
function htmlspecialchars(str)
{
    str = str.replace('<','&lt;');
    str = str.replace('>','&gt;');
    str = str.replace('"','&quot;');

    return str;
}

function check_boxes(formID, check)
{
    var e = document.forms[formID].elements;
    for (var i = 0; i < e.length; i++)
    {
        if('items[]' == e[i].name)
        {
            e[i].checked = check;
        }
    }
}

function list_submit (list_action, val)
{
    if ('acl' == list_action)
    {
        document.frames[list_formID].document.forms[list_formID].aclID.value = val;
    }
    document.frames[list_formID].document.forms[list_formID].list_action.value = list_action;
    document.frames[list_formID].document.forms[list_formID].submit();
}

function toggle_frame(frameID,minh,but,open_str,close_str)
{
    var obj = document.getElementById(frameID);

    var curx = parseInt(obj.offsetTop) + parseInt(obj.height);
    if(0 == frame_status)
    {
        frame_status = 1;
        obj.height = wheight - curx + 40;
        but.value = close_str;
    }
    else
    {
        frame_status = 0;
        obj.height = minh;
        but.value = open_str;
    }
}

/* List holder controls */
function listholder_param (keyword, value)
{
    listholder[keyword] = value;
    listholder_update();
}

function listholder_sort (keyword, direction)
{
    listholder['sort_'] = keyword;
    listholder['in'] = direction;
    listholder_update();
}

/* Walks through list header filters and adds filter values to listholder array */
function listholder_update ()
{
    // exctract data from base current url
    var currentUrl = document.location.href;
    currentUrl = currentUrl.replace(/.*\?/, '');
    var vars = currentUrl.split('&');
    for (i = 0; i < vars.length; i ++)
    {
        param = vars[i].split('=');
        if ('session' == param[0] || 'section' == param[0] || 'tab' == param[0] ||
            'module' == param[0] || 'objectID' == param[0] ||
            'lookup' == param[0] || 'field' == param[0] || 'text' == param[0] ||
            'object' == param[0] || 'software_type' == param[0])
        {
            // save param among listholder parameters
            listholder[param[0]] = param[1];
        }
    }

    var listholderForm = document.forms['listholder_filtering'];
    if(listholderForm.elements)
    {
        for (var i = 0; i < listholderForm.elements.length; i++)
        {
            var e = listholderForm.elements[i];
            if (listholder[e.name] || listholder[e.name] != e.value)
            {
                listholder[e.name] = e.value;
            }
        }
    }

    var headerForm = document.frames[0].document.forms[0];
    for (var i = 0; i < headerForm.elements.length; i++)
    {
        // pump header filters into listholder array
        if ((listholder[headerForm.elements[i].name] != headerForm.elements[i].value &&
                listholder[headerForm.elements[i].name] && headerForm.elements[i].value) ||
            (listholder[headerForm.elements[i].name] && !headerForm.elements[i].value) ||
            (!listholder[headerForm.elements[i].name] && headerForm.elements[i].value) &&
            'selectall' != headerForm.elements[i].name)
        {
            // reset page if any filtering parameter changes
            listholder['page'] = 1;
        }

        if (headerForm.elements[i].value)
        {
            // add non-empty filter value
            listholder[headerForm.elements[i].name] = headerForm.elements[i].value;
        }
        else if (listholder[headerForm.elements[i].name])
        {
            // removed filter value from header
            delete listholder[headerForm.elements[i].name];
        }
    }

    // prepare new base url string from all parameters
    var url = new String();
    for (keyword in listholder)
    {
        if ('Inherits' == keyword)
        {
            continue;
        }

        k = keyword;
        if ('sort_' == keyword)
        {
            // replace hacked keyword
            k = 'sort';
        }
        if (0 < url.length)
        {
            url += '&';
        }
        url += k + '=' + encodeURIComponent(listholder[keyword]);
    }
    top.document.location.href = '?' + url;
}

function listholder_set(keyword, value)
{
    listholder[keyword] = value;
}

function html2text(str)
{
    // remove newlines
    str = str.replace(/\n*/g,'');
    // <br> to newlines
    str = str.replace(/<br[^>]*>/gi,"\n");
    // </p> to double newlines
    str = str.replace(/<\/p>/gi,"\n\n");
    // remove html tags
    str = str.replace(/<\/?[^>]+>/g,'');

    return str;
}

function text2html(str)
{
    // newlines to <br>
    str = str.replace(/\n/gi,"<br />\n");
    // &nbsp to spaces
    str = str.replace(/&nbsp;/, ' ');

    return str;
}

function hide_message (init)
{
    var message = document.getElementById('message');
    var msgTop = message.offsetTop;
    var bodyHeight = document.body.offsetHeight;

    if (true == init)
    {
        // first initalisation
        message.style.position = 'absolute';
        message.style.width = document.body.offsetWidth;
    }
    if (bodyHeight > msgTop)
    {
        message.style.top = msgTop + 1;
        setTimeout('hide_message()', 20);
    }
    else
    {
        message.style.display = 'none';
    }
}

function calendar_navi(frameId, go)
{
    var f = frames[0].document.forms['calendar_navi'];
    var begins = f.begins.value.split('|');
    begins = begins[go].toString();
    var url = f.url.value;
    url = url.replace(/begins=[^&]*/,'begins='+begins);
    document.location = url;
}

function selectTaskModule(obj, module)
{
    document.frames[0].document.forms['caltask'].module.value = module;
}

function changeCalUser(userID)
{
    var url = document.location.toString();
    if(-1 != url.indexOf('userID'))
    {
        url = url.replace(/&userID=[^&]*/, '&userID='+userID);
    }
    else
    {
        url += '&userID='+userID;
    }
    document.location = url;
}

function email_showattachments ()
{
    var collapse = 27; // closed-opened difference
    row = document.getElementById('rfiles');
    if ('block' != row.style.display && document.getElementById('htmldiv'))
    {
        row.style.display = 'block';
        resize_htmlarea(-27);
    }
}

function tb_menu_button (button, align)
{
    button = document.getElementById('tb_' + button + '_holder');
    if ('block' == button.style.display)
    {
        // hide submenu
        button.style.display = 'none';
    }
    else
    {
        // show submenu
        button.style.display = 'block';
        button.style.zIndex = 1000;

        if (0 < align && true != button.aligned)
        {
            // Align menu vertically
            button.style.top = button.offsetTop - 3;
            button.style.left = button.offsetLeft - 3;
            button.aligned = true;
        }
    }
}

//    Functions returns month number. From "Feb" to "2" and so on.
//    unixTimeToDatetime uses this.
function get_month_num(txtMonth)
{
    var arrMon = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
    for (i = 0; i < arrMon.length; i++)
    {
        if(txtMonth == arrMon[i])
        return i + 1;
    }
}

//    Function converts unix timestamp to datetime (dd.mm.yyy hh:ii).
//    Needs getMonthNum to be included.
function unix_time_to_datetime(unix_timestamp)
{
    //    Add two hours, because of toGMTString and we have live in GMT + 2.
    // And what about other people that live in other regions?! WTF?!
    var offset = new Date();
    var theDate = new Date(unix_timestamp * 1000 - (offset.getTimezoneOffset() * 1000 * 60));
    var dateString = theDate.toUTCString();
    var arrDateStr = dateString.split(' ');
    month = get_month_num(arrDateStr[2]);
    day = arrDateStr[1];
    year = arrDateStr[3];
    hour = arrDateStr[4].substr(0, 2);
    minute = arrDateStr[4].substr(3, 2);
    //second = arrDateStr[4].substr(6,2);

    //    Zeros fix.
    month = month + '';
    if (month.length == 1)
    {
        month = '0' + month;
    }
    if (day.length == 1)
    {
        day = '0' + day;
    }

    return day + '.' + month + '.' + year + ' ' + hour + ':' + minute;
}

/**
 * On window closing checks if it's content has been changed and if yes - yelds
 * a confirmation message to save changes first.
 *
 * @return  void
 * @access  public
 **/
function trackWindowChanges ()
{
    if (window_updated)
    {
        var saveFirst = confirm(window_updated_confirmation);
        if (saveFirst)
        {
            document.getElementById('tb_save').click();
        }
    }
}

/**
 *
 * @access public
 * @return void
 **/
function window_changed ()
{
    window_updated = true;
    return true;
}