var canwork = 1;
var opened_popups = new Array();

function popup(url, name, width, height, menubar, toolbar, returnWindow, toAddToOpenedPopups)
{
    if (canwork)
    {
        canwork = 0;

        if (!name)      name    ="popup";
        if (!height)    height  = 500;
        if (!width)     width   = 830;
        if (!menubar)   menubar = "no";
        if (!toolbar)   toolbar = "no";

        if (name != 'popup')
        {
            eval('if (window.' + name + ' && !window.' + name + '.closed) ' + name + '.close();');
        }

        var w = null;
        try {
            w = window.open(url, name,
                            "directories=no,height=" + height +
                            ",width=" + width +
                            ",location=no,menubar=" +  menubar +
                            ",resizable=yes,scrollbars=yes,status=no,toolbar=" + toolbar);
            w.focus();

            if (typeof toAddToOpenedPopups == typeof undefined || // if parameter is not specified
                toAddToOpenedPopups) { // or specified and equals to false
                addPopup(w);
            }
        } catch (e) {
            // Can be thrown when user works offline.
        }

        canwork = 1;

        if (returnWindow && w != null) return w;
    }
}

/*
 * Ads the specified pop-up window to opened pop-up windows collection to close them by closeAllOpenedPopups() function
 * on document unloading.
 *
 * @param popupWindow - the pop-up to add.
 */
function addPopup(popupWindow) {
    opened_popups[opened_popups.length] = popupWindow;
}

/*
 * Closes all opened pop-up windows added to opened_popups collection by addPopup(popupWindow) function. This function
 * should be called by onload handler of the document body.
 */
function closeAllOpenedPopups() {
    for (var i = 0; i < opened_popups.length; i++) {
        var popupWindow = opened_popups[i];
        if (!popupWindow.closed) {
            popupWindow.close();
        }
    }
}

/*
 * @param sessionExpired determines whether flag informing about session expiration should be added to the request or not.
 * It is needed when login page is opened in pop-up window, because in this case information about session expiration is
 * removed from the session when this page is re-opened in main window (see bug 18176).
 */
function show_in_main_window(sessionExpired)
{
    if (window.opener && (window.name == 'popup' || window.name.indexOf('popup') == 0))
    {
        var sessionExpiredParamName = "sessionHasExpired";
        var location = window.location.href;

        if (sessionExpired) {
            location = addRequestParams(window.location.href, sessionExpiredParamName.concat("=true"));
        }
        
        window.opener.location.href = location;
        window.opener.focus();
        window.close();
    }
}

/*
 * Adds the specified params (string like 'param1=value1&param2=value2... etc.') to the specified URL.
 */
function addRequestParams(url, paramsStr) {
    var result = url;

    if (url.indexOf("?") >= 0) {
        result = result.concat("&");
    } else {
        result = result.concat("?");
    }

    return result.concat(paramsStr);
}

function notEmpty(obj, msg)
{
    if ( obj.value.match(/^\s*$/g) )
    {
        if ( msg && msg != '')
        {
            alert(msg)
            obj.focus();
        }
        return false;
    }
    return true;
}

// Select/unselect checkboxes list
// form - form object
// name - checkboxes name
// state - true/false
function setCheckboxesState(form, name, state)
{
    for (i = 0; i < form.length; i++)
    {
        if (form.elements[i].type == "checkbox" &&
            form.elements[i].name.search(name) != -1)
        {
            form.elements[i].checked = state;
        }
    }
}

// Select/unselect options in multiple select
// s - select object
// state - true/false
function setOptionsState(s, state)
{
    for (i = 0; i < s.options.length; i++)
    {
        s.options[i].selected = state;
    }
}

// Get selected value from a selector object
function getVal(el)
{
    if (el.type == "select-one")
        if(el.selectedIndex != undefined)
            return parseInt(el.options[el.selectedIndex].value, 10);
        else
            // Opera 6.x
            return parseInt(el.options[el.value].value, 10);
    else
        return parseInt(el.value, 10);
}

function isEmailValid(email)
{
    return email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/);
}

function isNotEmpty(str)
{
    return !str.match(/^\s*$/g);
}

// checks form field and shows alert in case of error
// validationFunc - pointer to a string that gives one
// string parameter and returns true in case of valid
// value else false
function checkField(field, msg, validationFunc)
{
    eval("var isValid = " + validationFunc + "(field.value)");

    if (isValid)
        return true;

    alert(msg);
    field.focus();
    return false;
}

// Function trims specified value
function trim(str)
{
    if(str == "") return str;
    return str.replace(/^\s+/, "").replace(/\s+$/, "");
}

// Function normalizes specified string
function normalize(str)
{
    var re = /\s{2,}/;

    while (re.test(str))
    {
        str = str.replace(re, " ");
    }

    return str;
}

// Function trims all text form fields
function trimAllTextFields(f)
{
    for (i = 0; i < f.length; i++)
    {
        if (f.elements[i].type == 'text')
        {
            f.elements[i].value = trim(f.elements[i].value);
        }
    }
}

// Function normalizes all text form fields
function normalizeAllTextFields(f)
{
    for (i = 0; i < f.length; i++)
    {
        if (f.elements[i].type == 'text')
        {
            f.elements[i].value = normalize(f.elements[i].value);
        }
    }
}

// Function normalizes specified string
function toUnixLineFeeds(str)
{
    return str.replace(/\r/g, '');
}

function shiftTo(obj, x, y) {
    var units = (typeof obj.style.left == "string") ? "px" : 0;
    obj.style.left = x + units;
    obj.style.top = y + units;
}

function isMSIE() {
    return ((navigator.appVersion.indexOf("MSIE")!= -1)&&!window.opera)? true : false;
}

function calculateCoords(event) {
    var targetEl = event.srcElement;
    if (!targetEl)
        targetEl = event.target;
    return calculateObjectCoords(targetEl);
}

function calculateObjectCoords(obj) {
    return {x:findPosX(obj) - 100, y:findPosY(obj) + 25};
}

function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function scrollWindowIfNeeded(object) {
    var leftUpperCorner = { x:object.offsetLeft, y:object.offsetTop };
    var rightBottomCorner = { x:object.offsetLeft + object.clientWidth, y:object.offsetTop + object.clientHeight };
    var viewportLeftUpperCorner = { x:document.body.scrollLeft, y:document.body.scrollTop };
    var viewportRightBottomCorner = { x:document.body.scrollLeft + document.body.clientWidth, y:document.body.scrollTop + document.body.clientHeight };

    var scrollX = 0;
    if (leftUpperCorner.x < viewportLeftUpperCorner.x)
        scrollX = leftUpperCorner.x - viewportLeftUpperCorner.x;

    var scrollY = 0;
    if (rightBottomCorner.y > viewportRightBottomCorner.y)
        scrollY = rightBottomCorner.y - viewportRightBottomCorner.y;

    if (scrollX != 0 || scrollY != 0) {
/*        alert("VIEWPORT\ntop-left.x = " + viewportLeftUpperCorner.x + ", top-left.y = " + viewportLeftUpperCorner.y +
              "; bottom-right.x = " + viewportRightBottomCorner.x + ", bottom-right.y = " + viewportRightBottomCorner.y + "\n\n" +
              "object\ntop-left.x = " + leftUpperCorner.x + ", top-left.y = " + leftUpperCorner.y +
              "; bottom-right.x = " + rightBottomCorner.x + ", bottom-right.y = " + rightBottomCorner.y + "\n\n" +
              "SCROLL BY\nscrollX = " + scrollX + ", scrollY = " + scrollY); */
        window.scrollBy(scrollX, scrollY);
    }
}

/*
 * Unifies new line symbol in the specified string. It is needed for unified string length determining in various
 * browsers, because in some browser (e.g. IE) new line symbol is '\r\n', but in others (e.g. Firefox) new line symbol
 * is '\n'. Because of these differences length of a string can vary in various browsers. To avoid differences this
 * function should be called before a string length determining.
 *
 * @param str a string where new line symbol should be unified.
 * @return string with unified new line symbol.
 */
function getStringWithUnifiedNewLineSymbol(str) {
    return str.replace(/(\r?\n)|(\r\n?)/g, '\r\n');
}