// $Id: scripts.js 59748 2007-02-16 12:25:01Z fshemetev $

function setTitle(win, title)
{
    win.top.document.title = title;
}


function MM_swapImgRestore()
{ //v3.0
    var i, x, a = document.MM_sr;
	for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
	{
        x.src = x.oSrc;
    }
}

// select chosen tab in the navigator, deselect all others
function navigator_tabSelect(num)
{
    var img = new Array('home', 'tree', 'search', 'prefs');
	for (i = 0; i < 4; i++)
	{
		if (document.images[img[i]])
		{
			if (i == num)
			{
                document.images[img[i]].src = 'images/' + img[i] + '_on.gif';
			} else
			{
                document.images[img[i]].src = 'images/' + img[i] + '_off.gif';
            }
        }
    }
}

// select chosen tab in the main pane, deselect all others
function context_tabSelect(num, total)
{
    var ri, li, cell;
	for (i = 0; i < total; i++)
	{
        li = document.images['tab' + i.toString() + 'l'];
        ri = document.images['tab' + i.toString() + 'r'];
        cell = document.getElementById('tab' + i.toString() + 'c');
		if (i == num)
		{
            li.src = 'images/zon_left.gif';
            ri.src = 'images/zon_right.gif';
            cell.background = "images/zon_fon.gif";
            cell.style.background = "url('images/zon_fon.gif')";
		} else
		{
            li.src = 'images/zoff_left.gif';
            ri.src = 'images/zoff_right.gif';
            cell.background = "images/zoff_fon.gif";
            cell.style.background = "url('images/zoff_fon.gif')";
        }
    }
}

function preventDefaultEventAction(e)
{
	try
	{
        e.preventDefault();
	} catch(exc)
	{
        try
        {
            e.returnValue = false;
        }
        catch (ex)
        {
        }
    }
}

function getDefaultFormWindowFeatures()
{
	return 'directories=0,location=0,menubar=0,toolbar=0,resizable=1,scrollbars=1,status=0';
}

function open_form(e, dest_url, w, h, confirm_msg, reg_win)
{
    var sFeatures = getDefaultFormWindowFeatures();

    if (typeof(w) != "undefined" && w > -1)
    {
        sFeatures = sFeatures + ',width=' + w.toString();
    }
    if (typeof(h) != "undefined" && h > -1)
    {
        sFeatures = sFeatures + ',height=' + h.toString();
    }
    if (typeof(w) != "undefined" && w == screen.availWidth && typeof(h) != "undefined" && h == screen.availHeight)
    {
        sFeatures = sFeatures + ',left=0,top=0';
    }

    if (typeof(confirm_msg) != "undefined" && confirm_msg != '')
    {
        if (window.confirm(confirm_msg))
            openWindow('form' + '|' + dest_url, dest_url, sFeatures, reg_win);
    }
    else
    {
        openWindow('form' + '|' + dest_url, dest_url, sFeatures, reg_win);
    }
    preventDefaultEventAction(e);
}

function open_in_old_form(e, id, dest_url)
{
    var sFeatures = getDefaultFormWindowFeatures();

    var win = openWindow(id, dest_url, sFeatures, 1);

    win.navigate(dest_url)

    preventDefaultEventAction(e);
}

function open_normal(e, dest_url, reg_win)
{
    openWindow('normal' + '|' + dest_url, dest_url, '', reg_win);
    preventDefaultEventAction(e);
}

function open_in_new_window(e, dest_url, win_type, w, h, confirm_msg, url_filter)
{
    var sFeatures;
    if (typeof(url_filter) != "undefined")
    {
       dest_url = url_filter(dest_url);
    }

    if (win_type == 'form')
    {
        open_form(e, dest_url, w, h, confirm_msg);
    }
    else if (win_type == 'normal')
    {
        open_normal(e, dest_url);
    }
    else
    {
        open_normal(e, dest_url);
    }
    preventDefaultEventAction(e);
}

function confirmMsg(e, msg)
{
    if (!window.confirm(msg))
    {
        preventDefaultEventAction(e);
        return false;
    }
    else
    {
        return true;
    }
}

var isFormChanged = false;

// display confirm if form is changed
// you should set global variable isFormChanged
function confirmMsgOnClose(e, msg)
{
    if (isFormChanged && !window.confirm(msg))
    {
        preventDefaultEventAction(e);
        return false;
    }
    else
    {
        return true;
    }
}

/*function _calcSearchKoeff(str, substr)
{
    var fin_substr = '';
    var fin_index = -1;
    for (var j = substr.length; j > 0 ; j--)
    {
        var curr_substr = substr.substring(0, j);
        fin_index = str.indexOf(curr_substr);
        if (fin_index == -1) { continue; }
        fin_substr = curr_substr;
        break;
    }
    if (fin_index == -1)
    {
        return -1;
    }

    //max value = 1800
    var k1 = fin_substr.length * 1000 / substr.length;
    var k2 = (str.length - fin_index) * 1000 / str.length;
    var v1 = 1;
    var v2 = 0.8;
    var K = v1 * k1 + v2 * k2;
    return K;
}

function SearchStrInSelect(str, select)
{
    var strn=0;
    var max_k = -1, max_k_i = 0;
    //select must be sorted to make it nice work
    for (var i = 0; i < select.length; i++)
    {
        select.options[i].selected=false;
        var inpStr=str.toUpperCase();
        var selStr=select.options[i].text.toUpperCase();
        try
        {
            selStr=select.options[i].nonshifted.toUpperCase();
        }
        catch(err) { }
        K = _calcSearchKoeff(selStr, inpStr);
        // max value
        if ( K == 1800 )
        {
            strn=i;
            break;
        }
        if ( K > max_k )
        {
            max_k = K;
            strn=i;
        }
    }
    if ((!select.multiple || str.length) && select.length)
    {
        select.options[strn].selected=true;
    }
}*/
function FillStrInSelect(event, select, input)
{
    var key = event.keyCode;
    var ch = event.charCode;
    var ch_str = new String(ch);
    if  (ch!=0 && ch_str!="undefined")
    {
        var character=String.fromCharCode(ch);
    }
    else if (key!=0)
    {
        if (key==27 || key == 8)
        {
            var val = new String(input.value);
            input.value = val.substring(0, val.length-1);
            SearchStrInSelect(input.value, select);
            event.keyCode=0;
            event.charCode=0;
            return;
        }
        var character=String.fromCharCode(key);
    }
    var new_value = input.value+character;
    input.value = new_value;
    SearchStrInSelect(new_value, select);
}

function ProcessDelInSelect(event, select, input)
{
    var key = event.keyCode;
    if (key == 27)
    {
        var val = new String(input.value);
        var strlen = val.length;
        input.value = val.substring(0, strlen-1);
        SearchStrInSelect(input.value, select);
        event.keyCode=0;
        event.charCode=0;
    }
    return false;
}

function trim(str)
{
    while (str.charAt(0) == ' ' || str.charCodeAt(0) == 160)
        str = str.substring(1);
    return str;
}
function SearchStrInSelect(str, select)
{
    var ind = 0, eqPart = 0;
    str = str.toUpperCase();
    for (var i = 0; i < select.length; i++)
    {
        var selectItem = trim(select.options[i].text.toUpperCase());
        var len = selectItem.length;
        if (len > str.length) len = str.length;
        for (var j = 0; j < len; j++)
            if (str.charAt(j) != selectItem.charAt(j))
                break;

		if (j == len && len == str.length)
		{
            ind = i;
            break;
        }
		if (eqPart < j)
		{
            eqPart = j;
            ind = i;
        }
    }
    if (select.length)
        select.selectedIndex = ind;
}


//
// Detect user agent type, version and features
//
function browserType()
{
    //var s = '';
    //for (k in navigator)
    //  s += k+'="'+navigator[k]+'"\n';
    //alert(s);
    var ua = new Object;
    var version = navigator.appVersion;
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
        ua.type = 'IE';
        ua.version = parseFloat(version.substr(version.indexOf('MSIE') + 4));
        ua.hasCoveredBug = true;
	} else if (navigator.product == 'Gecko')
	{
        ua.type = 'MZ';
        ua[ 'NS6' ] = true;
	} else if (navigator.appName == 'Netscape')
	{
        ua.type = 'NS';
        if (navigator.vendor == 'Netscape6')
            ua.version = 6;
    }
    if (! ua.version)
        ua.version = parseFloat(version);
    ua.major = parseInt(ua.version);
	if (ua.type)
	{
        ua[ ua.type ] = true;
        ua[ ua.type + ua.major ] = true;
        ua[ ua.type + ua.version ] = true;
    }

    ua.hasComputedStyle = !! (window.document.defaultView &&
                              window.document.defaultView.getComputedStyle);
    ua.frameWidth = frameWidth;
    return ua;
}

//
// Get actual width of the given frame object
//
function frameWidth(frame)
{
    if (this.IE)
    {
        if (this.version < 5.5)
            return frame.document.body.offsetWidth;

        // TODO: use frame index
        else if (this.version < 6)
            return parseInt(frame.parent.document.body.cols) &&
                   frame.document.body.offsetWidth;
        else
            return parseInt(frame.parent.document.body.cols);
    }
    return frame.innerWidth;
}


//
// Adds a new option to the list
//
function addOptionTo(list, text, value)
{
    var len = list.length;
    var opt;

    if (userAgent.IE)
        opt = list.document.createElement("OPTION");
    else
        opt = new Option();
    opt = list.options[len] = opt;
    opt.text = text;
    opt.value = value;
    return opt;
}

//
// Add the selected items from the source to destination list
//
function addSelectionToList(src_list, dest_list)
{
    var len = dest_list.length;
    for (var i = 0; i < src_list.length; i++)
    {
        if ((src_list.options[i] != null) && (src_list.options[i].selected))
        {
            //Check if this value already exist in the dest_list or not
            //if not then add it otherwise do not add it.
            var found = false;

            for (var count = 0; count < len; count++)
            {
                if (dest_list.options[count] != null)
                {
                    if (src_list.options[i].value == dest_list.options[count].value)
                    {
                        found = true;
                        break;
                    }
                }
            }

            if (found != true)
            {
                addOptionTo(dest_list, src_list.options[i].text, src_list.options[i].value);
                len++;
            }
        }
    }
}

//
// Deletes from the destination list
//
function deleteSelectionFromList(dest_list)
{
    var len = dest_list.options.length;

    for (var i = (len - 1); i >= 0; i--)
    {
        if ((dest_list.options[i] != null) && (dest_list.options[i].selected == true))
        {
            dest_list.options[i] = null;
        }
    }
}


//
// Clear list contents
//
function clearList(list)
{
    var len = list.options.length;
	for (var j = (len - 1); j >= 0; j--)
	{
        if (list.options[j] != null)
            list.options[j] = null;
    }
}

//
// Select all items of the list
//
function selectAll(list)
{
    if( list )
    {
        var len = list.length;
        for (var i = 0; i < len; i++)
        {
            list.options[i].selected = true;
        }
    }
}

//
//Set item selected in list
//
function selectItem(list, value)
{
    var len = list.length;
    for (var i = 0; i < len; i++)
    {
        if (list.options[i].value == value)
        {
            list.options[i].selected = true;
        }
        else
        {
            list.options[i].selected = false;
        }
    }
}

//
// Count selected items of the list
//
function countSelectedItems(list)
{
    var len = list.length;
    var cnt = 0;
    for (var i = 0; i < len; i++)
    {
        if (list.options[i].selected == true) cnt++;
    }
    return cnt;
}

//
// Returns record of element's dimensions and position in a window.
//
function getAbsolutePos(element)
{
    var pos = { x1: element.offsetLeft, y1: element.offsetTop };
	if (element.offsetParent)
	{
        var par = getAbsolutePos(element.offsetParent);
        pos.x1 += par.x1;
        pos.y1 += par.y1;
    }
    pos.x2 = pos.x1 + ( pos.w = element.offsetWidth  ) - 1;
    pos.y2 = pos.y1 + ( pos.h = element.offsetHeight ) - 1;
    return pos;
}

//
// Toggle expanded navigator view
//

function toggleExpand(event)
{

}

function OverMenu()
{
    clearTimeout(menu_timer);
}

function OutMenu()
{
    clearTimeout(menu_timer);
    menu_timer = setTimeout("hideAllMenu()", 500);
}

function hideAllMenu()
{
    var tables = document.getElementsByTagName('table');
	for (var i = 0; i < tables.length; i++)
	{
        var table = tables[i];
		if (table.className == 'menu')
		{
            table.style.display = 'none';
        }
    }
}

function showMenu(id, target, x_offset, y_offset)
{
    OverMenu();
    var menu = document.getElementById(id);
	if (menu)
	{
        if (typeof(x_offset) == "undefined")
            x_offset = 0;
        if (typeof(y_offset) == "undefined")
            y_offset = 5;
        pos = getAbsolutePos(target);
        menu.style.top = pos.y2 + y_offset;
        menu.style.left = pos.x1 + x_offset;
        hideAllMenu();
        menu.style.display = 'block';
    }
}

function showMenuWithFocus(id, focus_id, target, x_offset, y_offset)
{
    showMenu(id, target, x_offset, y_offset);
    var sel = document.getElementById(focus_id);
    if (sel)
        sel.focus();
}

function openWindow(id, url, params, reg_win)
{
    if (typeof(reg_win) == "undefined")
    {
        reg_win = 0;
    }

    if (reg_win)
    {
        var win = windowManager[id];
		if (win)
		{
			try
			{
                win.focus();
                return win;
            }
			catch (e)
			{
            }
        }
    }

    win = window.open(url, '_blank', params);
    win.moveTo(0,0);

    var ACTIVE_COMPONENT_PARAM = "activeComponent=";

    var i = id.indexOf(ACTIVE_COMPONENT_PARAM);

	if (i != -1)
	{
        var component_id = new String(id);
        component_id = component_id.substring(component_id.indexOf(ACTIVE_COMPONENT_PARAM) + ACTIVE_COMPONENT_PARAM.length);

        var j = component_id.indexOf("&");

		if (j != -1)
		{
            component_id = component_id.substring(0, j);
        }
        win.name = component_id;
    }

    if (reg_win)
    {
        registerWindow(id, win)
    }

    return win
}


function registerWindow(id, win)
{
    windowManager[id] = win;

    win.onload = function()
    { // XXX but without didn`t work, win call onUnload handler then it loaded
        registerCallback(win, 'onUnload', unregisterWindow, null, id);
    }
    registerCallback(window, 'onUnload', _closeWindowCallback, null, win);

    return win;
}

function unregisterWindow(event, id)
{
    delete windowManager[ id ];
}

function _closeWindowCallback(ev, win)
{
    if (win && ! win.closed)
        win.close();
}

//
// Registers callback.
//
// Arguments:
//
//     'object' -- object on which to watch for events
//     'type' -- name of the event, with 'on' prefix
//     'callback' -- callback function object
//     'retval' -- required callback result (optional)
//
// Additional arguments are passed to the callback function as-is.
//
function registerCallback(object, type)
{
    type = type.toLowerCase()
    object[ type ] = runCallbacks;

    var items = object[ type + '__callbacks__' ];
    if (items == null)
        items = object[ type + '__callbacks__' ] = new Array();

    items[ items.length ] = appendSlice(null, registerCallback, 2);
}

//
// Executes registered callbacks.
//
// The first argument of the function is the object that fired
// the event, the second is current Event object, and the rest
// are custom arguments passed to callback registration.
//
// The callback function is called with 'this' set to the object
// that fired the event (XXX does not work in MSIE 5.0).
//
// If 'retval' was specified and the return value of the function
// differs from it, the callbacks queue processing is interruptted
// and that value is returned as a result if the event handler.
//
function runCallbacks(event, object)
{
    var type;
	if (typeof(event) == 'string')
	{
        type = event.toLowerCase();
	} else
	{
        event = event || window.event;
        type = 'on' + event.type.toLowerCase()
    }

    if (object == null)
        object = this;

    var items = object[ type + '__callbacks__' ];
    if (items == null)
        return true;

    // mandatory arguments of the callback
    var margs = new Array(event);

	for (var i = 0; i < items.length; i++)
	{
        // item is [ callback, retval, args... ]
        var item = items[i];
        var args = item.length <= 2 ? margs : margs.concat(item.slice(2));

        // now run the callback
        var retval = item[0].apply(object, args);

        if (item[1] != null && retval != item[1])
            return retval;
    }

    return true;
}

//
// Appends a slice of array-like object to the target array.
//
function appendSlice(target, array, start, length)
{
    target = target || new Array();

    if (typeof(array) == 'function')
        array = array.arguments;

    var end = length ? start + length : array.length;

    for (var i = start; i < end && i < array.length; i++)
        target[ target.length ] = array[i];

    return target;
}

//
// Returns the checked option of the radio buttons set
//
function getCheckedRadioButton(radio)
{
    if (!radio)
        return;

    len = radio.length;
    if (len)
        for (var i = 0; i < len; i++)
        {
            var option = radio[i];
            if (option.checked)
                return option;
        }
    else
        return radio.checked ? radio : null;
}

//
// reset radio buttons set
//
function resetRadioButton(radio)
{
    if (!radio)
        return;

    if (radio.length)
        for (var i = 0; i < radio.length; i++)
            radio[i].checked = false;
    else
        radio.checked = false;
}

//
// Set query parameter in the url string
//
function setParam(url, name, value)
{
    if (value instanceof Array)
    {
        var newValue = "";
        var len = value.length;
        for (var i = 0; i < len; ++i)
        {
            if (i > 0)
            {
                newValue += "&";
            }
            newValue += (escapeURL(name) + '=' + escapeURL(value[i]));
        }
        value = newValue;
    }
    else
    {
        value = escapeURL(name) + '=' + escapeURL(value);
    }
    if (url.indexOf('?') == -1)
        return url + '?' + value;

    url = url.replace(new RegExp('([?&])' + escapeURL(name) + '=[^&]*&*', 'g'), '$1');

    var len = url.length;
    var lastChar = url.charAt(len-1);
    return url + ('?' != lastChar ? '&' : '') + value;
}


function removeParam(url, name)
{
	if (url.match(new RegExp('([?&])' + escapeURL(name) + '=[^&]*', 'g')))
	{
	    var left = RegExp.leftContext;
		var right = RegExp.rightContext;
		var match = RegExp.lastMatch;
		if(match[0]=='?' && right.length!=0)
			right = '?' + right.substr(1,right.length);
		return left+right;
	}
	return url;
}

function changeJsp(url, page)
{
	if(url.match(new RegExp('/fx/.{1,}_jsp', 'g')))
		return RegExp.leftContext+'/fx/'+ page + RegExp.rightContext;
	return url;
}

//
// Escape special characters in the HTML string
//
function escapeHTML(str, nlbr)
{
    for (var c in escapeHTMLMap)
        str = str.replace(new RegExp(c, 'g'), escapeHTMLMap[c]);
    if (nlbr)
        str = str.replace(new RegExp('\r*\n', 'g'), '<br />\n');
    return str;
}

//
// Escape special characters in the URL string
//
function escapeURL(str)
{
    var plusRegexp = new RegExp('\\+', 'g');
    return escape(str).replace(plusRegexp, '%2B');
    // XXX: why escape ignores +?
}

var userAgent = browserType();
var windowManager = new Object();
var menu_timer = null;

function toggleNavigator()
{
    var navVisible = document.getElementById('navigator_div_visible');
    var nav_td = document.getElementById('nav_td');
    var pub_td = document.getElementById('pub_td');
	if (navVisible.style.display == 'none')
	{
        navVisible.style.display = 'block';
        navVisible.style.visibility = 'visible';
        setCookie('nav_cookie', '1');
        nav_td.style.width = '22%';
        pub_td.style.width = '78%';
	} else
	{
        navVisible.style.display = 'none';
        navVisible.style.visibility = 'hidden';
        setCookie('nav_cookie', '0');
        nav_td.style.width = '0';
        pub_td.style.width = '100%';
    }
}

function maximizeNavigator()
{
    var brws = getBrowser();
    var navigator_div = document.getElementById('publisher_div');
    var pub_td = document.getElementById('pub_td');
    var nav_td = document.getElementById('nav_td');
	if (navigator_div.style.display == 'none')
	{
        navigator_div.style.display = 'block';
        navigator_div.style.visibility = 'visible';
        setCookie('navigator_cookie', '1');
        pub_td.style.width = '78%';
        nav_td.style.width = '22%';
	} else
	{
        navigator_div.style.display = 'none';
        navigator_div.style.visibility = 'hidden';
        setCookie('navigator_cookie', '0');
        pub_td.style.width = '0%';
        nav_td.style.width = '100%';
    }
}


function toggleSelectAllButton(selectAllButtonName, unselectAllButtonName)
{
    var selectAllButton = document.getElementById(selectAllButtonName);
    var unselectAllButton = document.getElementById(unselectAllButtonName);
	if (selectAllButton.style.display == 'none')
	{
        selectAllButton.style.display = 'block';
        selectAllButton.style.visibility = 'visible';
        unselectAllButton.style.display = 'none';
        unselectAllButton.style.visibility = 'hidden';
	} else
	{
        selectAllButton.style.display = 'none';
        selectAllButton.style.visibility = 'hidden';
        unselectAllButton.style.display = 'block';
        unselectAllButton.style.visibility = 'visible';
    }
}

function getCookie(_name)
{
    if (document.cookie.length > 0)
    {
        // if there are any cookies
        var _search = _name + "=";
        var _offset = document.cookie.indexOf(_search);
        if (_offset != -1)
        {
            // if cookie exists
            _offset += _search.length;
            // set index of beginning of value
            var _end = document.cookie.indexOf(";", _offset);
            // set index of end of cookie value
            if (_end == -1)
                _end = document.cookie.length;
            return unescape(document.cookie.substring(_offset, _end));
        }
        else
            return null;
    }
    else
        return null;
}

function setCookie(_name, _value)
{
    //expires at the end of the session
    document.cookie = _name + "=" + escape(_value);
}


//
// Constructor for a dictionary-like object.
//
function Mapping(source)
{
    if (source)
        this.update(source);
}

Mapping.prototype.update = function (source, keep)
{
    var proto = this.constructor.prototype;
    for (var n in source)
        if (proto[n] == null && (!keep || this[n] == null))
            this[n] = source[n];
};

var fieldEditHandler = new Mapping();

//
// Returns a copy of a given javascript object.
// XXX  cannot patch prototype in MS IE 5.0 because
//      it would break 'for (.. in ..)' loops
//
//Object.constructor.prototype.cloneObject =
function cloneObject(source, deep)
{
    //var source = this;
    var clone = new source.constructor();
    for (var property in source)
        if (typeof source[property] == 'object' && deep)
            clone[property] = cloneObject(source[property], deep);
        else
            clone[property] = source[property];

    return clone;
}

// CheckboxColumn support structures & functions

var checkBoxColumnCacheNames = new Array();
var checkBoxColumnCacheValues = new Array();

function getCheckColCachedItem(name)
{
    for (i = 0; i < checkBoxColumnCacheNames.length; ++i)
    {
		if (checkBoxColumnCacheNames[i] == name)
		{
            return checkBoxColumnCacheValues[i];
        }
    }
}

function addCheckColCachedItem(name, item)
{
    checkBoxColumnCacheNames.push(name);
    checkBoxColumnCacheValues.push(item);
}

// Enable or disable all INPUT/BUTTON elements inside the specified element
function enableContainedControls(elem, enable)
{
    var i = 0;
    var kids;

    if (elem.nodeName == 'INPUT' || elem.nodeName == 'BUTTON')
    {
		if (enable)
		{
            elem.disabled = false;
        }
		else
		{
            elem.disabled = true;
        }
    }

    kids = elem.childNodes;

	if (kids == null)
	{

    }
	else if (kids.length != null)
	{
		for (i = 0; i < kids.length; i++)
		{
            enableContainedControls(kids[i], enable);
        }
    }
}

// Checkbox OnClick handler; enables or disables all INPUT/BUTTON elements inside all the elements
// having the specified ID
// checkId: ID of the checkbox
// target: ID of the element to enable/disable
// invert: if true, enable target elements when the checkbox is disabled
function checkboxColumnClicked(checkId, target, invert)
{
    var i = 0;
    var checkId;
    var checkBoxes;
    var isChecked;
    var targets;

    checkBoxes = getCheckColCachedItem(checkId);

	if (checkBoxes == null)
	{
        checkBoxes = new Array();
		inputs = document.getElementsByTagName('INPUT');
		for (i = 0; i < inputs.length; ++i)
		{
			if (inputs[i].id == checkId)
			{
                checkBoxes.push(inputs[i]);
            }
        }
        addCheckColCachedItem(checkId, checkBoxes);
    }

    isChecked = false;

	for (i = 0; i < checkBoxes.length; ++i)
	{
        isChecked = checkBoxes[i].checked;
		if (isChecked)
		{
            break;
        }
    }

    targetElement = document.getElementById(target);

	if (targetElement != null)
	{
		if (invert != null && invert)
		{
            isChecked = !isChecked;
        }
        enableContainedControls(targetElement, isChecked);
    }
}

function checkboxMarked(checkId)
{
    var i = 0;
    var checkId;
    var checkBoxes;
    var isChecked;
    var targets;

    checkBoxes = new Array();
	inputs = document.getElementsByTagName('INPUT');
	for (i = 0; i < inputs.length; ++i)
	{
		if (inputs[i].id == checkId)
		{
            checkBoxes.push(inputs[i]);
        }
    }

    isChecked = false;

	for (i = 0; i < checkBoxes.length; ++i)
	{
        isChecked = checkBoxes[i].checked;
		if (isChecked)
		{
            break;
        }
    }

    return isChecked;
}

function selectAllCheckBoxes(columnName, checkValue)
{
	allCheckBoxes = document.getElementsByTagName('INPUT');
    for (i = 1; i < allCheckBoxes.length; i++)
    {
        if (allCheckBoxes[i].name == columnName)
        {
            allCheckBoxes[i].checked = checkValue;
        }
    }
}

function selectAllCheckBoxesInElement(columnName, parentId, checkValue)
{
	parentElement = document.getElementById(parentId);
	inputsArray = parentElement.getElementsByTagName("INPUT");
    for (i = 0; i < inputsArray.length; i++)
    {
		if (inputsArray[i].getAttribute("name") == columnName)
		{
			if (inputsArray[i].disabled == false)
	            inputsArray[i].checked = checkValue;
        }
    }
}

function appendCheckboxValuesUrlFilter(element, url, columnName, paramName)
{
    var theForm = null;
    while(element != null)
    {
        if (element.tagName == 'FORM')
        {
            theForm = element;
            break;
        }
        element = element.parentNode;
    }
    if (theForm == null)
    {
        return url;
    }

    var inputsArray = theForm.getElementsByTagName("INPUT");
    var result = new Array();

    for (i = 0; i < inputsArray.length; i++)
    {
    	var inp = inputsArray[i];
        if (inp.getAttribute("name") == columnName && inp.checked)
        {
            result.push(inputsArray[i].value);
        }
    }
    return setParam(url, paramName, result);
}

function inverseOthersCheckBoxes(columnName, sourceValue)
{
	allCheckBoxes = document.getElementsByTagName('INPUT');
	for (i = 0; i < allCheckBoxes.length; ++i)
	{
		if (allCheckBoxes[i].name == columnName && allCheckBoxes[i].value == sourceValue)
		{
			if (allCheckBoxes[i].checked)
			{
				for (j = 0; j < allCheckBoxes.length; ++j)
				{
					if (allCheckBoxes[j].name == columnName && allCheckBoxes[j].value != sourceValue)
					{
						allCheckBoxes[j].checked = !allCheckBoxes[i].checked;
					}
				}
			} else
			{
				allCheckBoxes[i].checked = !allCheckBoxes[i].checked;
			}
			break;
		}
	}
}

function getBrowser()
{
    var browser = "None";
	if (navigator.appName.indexOf("Netscape") >= 0 && parseFloat(navigator.appVersion) >= 4)
	{
        browser = "NS4";
        version = 4;
    }
	if (document.getElementById)
	{
        browser = "NS6";
		if (navigator.userAgent.indexOf("6.01") != -1 || navigator.userAgent.indexOf("6.0") != -1)
		{
            version = 6;
		} else
		{
            version = 6.1;
        }
    }
	if (document.all)
	{
		if (document.getElementById)
		{
            version = 5;
		} else
		{
            version = 4;
        }
        browser = "IE";
    }
	if (navigator.userAgent.indexOf("Opera") != -1)
	{
        browser = "Opera";
		if (navigator.userAgent.indexOf("7.") != -1)
		{
            version = 7;
		} else
		{
            version = 6;
        }
    }
    return browser;
}
;

function popupWindow(url, width, height, flags, event)
{
	var params = 'menubar=0,toolbar=0,resizable=1,scrollbars=1' + ',width='+width+',height='+height;
	var flagsArray = flags.split('|');
	while ((flag = flagsArray.pop()) != null)
	{
		if (flag.length > 0)
		{
			if (flag == 'centered')
			{
				var xpos = (window.screen.width - width) / 2;
				var ypos = (window.screen.height - height) / 2;
				params += ',left='+xpos+',top='+ypos;
			}
	    }
  	}
	window.open(url, '_blank', params);
}

function multiPageJump(pageParamName, msg, curPage, maxPage)
{
	newPage = prompt(msg + maxPage, curPage + 1);
	if (newPage > 0 && newPage != curPage + 1)
		window.location.href = setParam(window.location.href, pageParamName, newPage - 1);
}
function postFormToWindow(element, windowName, actionName)
{
    var theForm = null;
    while(element != null)
    {
        if (element.tagName == 'FORM')
        {
            theForm = element;
            break;
        }
        element = element.parentNode;
    }
    if (theForm == null)
    {
        return;
    }

	var oldAction = theForm.action;
	var oldMethod = theForm.method;
	var oldTarget = theForm.target;

	try
	{
		theForm.method = 'POST';
		theForm.action = actionName;
		theForm.target = windowName;
		theForm.submit();
	}
	finally
	{
		theForm.action = oldAction;
		theForm.method = oldMethod;
		theForm.target = oldTarget;
	}
}
function getUpperForm(element)
{
    var theForm = null;
    while(element != null)
    {
        if (element.tagName.toLowerCase() == 'form')
        {
            theForm = element;
            break;
        }
        element = element.parentNode;
    }
    return theForm;
}

//-------------------------------------------------------------------------------------------
//
//	Here are scripts used by objecttree.jsp and raw of UIListBase-derived components' jsp
//
//--------------------------------------------------------------------------------------------

//
// Creates custom exception object
//
function Exception(name, message, kw)
{
    var exception = {};

    exception.name = name;
    exception.message = message;
    exception.toString = function () { return message };

    if (kw != null)
        for (var k in kw) exception[k] = kw[k];

    return exception;
}

//
// Constructor for the treeUserAgent object.
// Detects user agent type, version and features.
//
function treeUserAgent()
{
    //var s = '';
    //for (k in navigator)
    //  s += k+'="'+navigator[k]+'"\n';
    //alert(s);

    var version = navigator.appVersion;
    var error;

    if (navigator.appName == 'Microsoft Internet Explorer') {
        this.type = 'IE';
        this.version = parseFloat( version.substr( version.indexOf('MSIE') + 4 ) );
        this.hasCoveredBug = true;
        this.brokenSetMultiple = true;

        var xmlhttp_classes = ['msxml2.XMLHTTP.4.0', 'Microsoft.XMLHTTP'];
        for (var i = 0; i < xmlhttp_classes.length; i++)
            try {
                new ActiveXObject(xmlhttp_classes[i]);
                this.hasXMLHTTP = true;
                // XXX: actually decoding bug was fixed between msxml 3.0 SP1 and SP3,
                //      but we cannot detect that some service pack was installed
                this.hasDecodingBug = (i != 0);
                break;
            } catch (error) {
                // pass
            }
    } else if (navigator.product == 'Gecko') {
        this.type = 'MZ';
        this[ 'NS6' ] = true;
        try {
            new XMLHttpRequest();
            this.hasXMLHTTP = true;
        } catch (error) {
            // pass
        }
    } else if (navigator.appName == 'Netscape') {
        this.type = 'NS';
        if (navigator.vendor == 'Netscape6')
            this.version = 6;
    }

    if (! this.version)
        this.version = parseFloat(version);

    this.major = parseInt( this.version );

    if (this.type) {
        this[ this.type ] = true;
        this[ this.type + this.major ] = true;
        this[ this.type + this.version ] = true;
    }

    this.hasComputedStyle = !! (window.document.defaultView &&
                                window.document.defaultView.getComputedStyle);
}
//
// Downloads contents of page located by url.
//
// When ready_callback function specified download runs in async mode.
//
// Arguments:
//
//     'ready_callback' -- callback function that receives page contents in
//                         async mode.
//
//     'error_callback' -- callback function that receives exceptions in
//                         async mode.
//
// Exceptions:
//
//     'NotImplemented' -- XMLHTTP is not supported by user agent.
//
//     'DownloadError' -- response status differ from OK. Status code passed
//                        via 'status' attribute, page contents in 'text'.
//
treeUserAgent.prototype.downloadURLLight = function(url, ready_callback, error_callback)
{
    var async = (ready_callback != null),
        hasDecodingBug = this.hasDecodingBug,
        request;

    if (async && error_callback == null) error_callback = function() {};

    if (! this.hasXMLHTTP) {
        var error = Exception('NotImplemented', "XMLHTTP is not supported by your browser");

        if (async) {
            error_callback(error);
            return;
        } else
            throw error;
    }

    if (this.IE) // IE MSXML object
        request = new ActiveXObject('Microsoft.XMLHTTP');
    else // Mozilla ob1ject
        request = new XMLHttpRequest();

    function processResponse()
    {
        if (async && request.readyState != 4) return;

        var responseText = '';

        if (! hasDecodingBug || true ) //possible decoding bugs!!!
            responseText = request.responseText;
        else
        {
            // workaround of msxml charset decoding bug (code was taken from
            // http://relib.com/forums/topic.asp?id=751103)

            var rs = new ActiveXObject('ADODB.Recordset');

            rs.Fields.Append('ru', 200, 100000);
            rs.Open();
            rs.AddNew();
            rs.Fields.Item(0).AppendChunk(request.ResponseBody);
            responseText += rs.Fields.Item(0);
            rs.Close();
        }

        if (request.status == 200)
        {
            if (async) ready_callback(responseText);
            else return responseText;
        }
        else
        {
            var error = Exception( 'DownloadError'
                                 , request.status + ' ' + request.statusText
                                 , {'status': request.status, 'text': responseText}
                                 );

            if (async) error_callback(error);
            else throw error;
        }
    }

    if (async) request.onreadystatechange = processResponse;

    if (this.IE) // XXX
        url = setParam(url, '_T', (new Date().getTime()));

	return request;
};

treeUserAgent.prototype.downloadURL = function(url, ready_callback, error_callback)
{
	var async = (ready_callback != null);
	var request = this.downloadURLLight(url, ready_callback, error_callback);
	url = setParam(url, 'changeState', false);
    request.open('GET', url, async);
    request.send(null);
    if (! async) return processResponse();
};

var treeUserAgent = new treeUserAgent();

function showError(error, where)
{
    var error_text = "ERROR: ",
        error_element = document.createElement('SPAN');

    error_text += error;

    error_element.appendChild(document.createTextNode(error_text));
    error_element.style.color = 'red';
    error_element.style.fontWeight = 'bold';

    while (where.hasChildNodes()) where.removeChild(where.firstChild);
    where.appendChild(error_element);
}
function addCharSequence(lowChar, upChar)
{
    var sequence = new Array();
    for (var i = lowChar.charCodeAt(0); i <= upChar.charCodeAt(0); i++)
    {
        sequence.push(String.fromCharCode(i));
    }
    return sequence;
}

function generateRandomPassword(form, fieldName, passwordLength)
{
    var alphabet = new Array();
    alphabet = addCharSequence("A", "Z").concat(addCharSequence("a", "z"), addCharSequence("0", "9"));
    var password = "";
    for (var i = 0; i < passwordLength; i++)
    {
        password += alphabet[Math.round(Math.random() * (alphabet.length - 1))];
    }
    fieldName.value = password;

}

function pastePassword(form)
{
    var outputField = arguments[1];
    for (var i = 1; i < arguments.length; i++)
    {
        var inputField = arguments[i];
        if (inputField)
            inputField.value = outputField.value;
    }
}

function resizeKBFrame()
{
    docHeight = article_text.document.body.scrollHeight;
    document.getElementById('article_text').style.height = docHeight + 'px';
    //MSIE fix
    if(treeUserAgent.type == "IE"){
        var oDiv = document.getElementById('Card_root').getElementsByTagName("div")[0];
        oDiv.style.visibility = "visible";
    }
}

