////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
 Util functions
 */

function isIE() {
    return navigator.appName.indexOf("Explorer") > 0;
}

function limitInputValue(input, maxLen) {
    if (input.value.length > maxLen) {
        input.value = input.value.substring(0, maxLen);
        alert('Максимальное количество символов: ' + maxLen);
    }
}

function swapElementsVisibility(id1, id2) {
    if (document.getElementById(id1).style.display == "block") {
        document.getElementById(id1).style.display = "none";
        document.getElementById(id2).style.display = "block";
    }
    else {
        document.getElementById(id2).style.display = "none";
        document.getElementById(id1).style.display = "block";
    }
}

function nextTabIndOperaFix(event, elem) {
    var TAB_KEY_CODE = 9;
    var keyCode;
    if ("keyCode" in event)
    {// Safari & IE4+
        keyCode = event.keyCode;
    } else if ("keyCode" in window.event)
    {// IE4+
        keyCode = window.event.keyCode;
    } else if ("which" in window.event)
        {
            keyCode = event.which;
        } else {
            alert("the browser don't support");
        }
    //    if (navigator.userAgent.indexOf('Opera') > 0 && keyCode == TAB_KEY_CODE) {
    if (keyCode == TAB_KEY_CODE) {
        var allElems = document.getElementsByClassName("operaTabInd");
        var focusToElem = allElems[0];
        for (var i = 0; i < allElems.length - 1; i++) {
            if (elem == allElems[i]) {
                focusToElem = allElems[i + 1];
                break;
            }
        }
        focusToElem.focus();
    }
    return true;
}

function getTargetElement(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.relatedTarget) targ = e.relatedTarget;
    else if (e.toElement) targ = e.toElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    return targ;
}

function getEvent(e) {
    if (!e) var e = window.event;
    return e;
}

function containsChild(element, child) {
    for (var i = 0; i < element.childNodes.length; i++) {
        var currentChild = element.childNodes[i];
        if (containsChild(currentChild, child)) {
            return true;
        }
    }
    return element == child;
}

function refreshCapchaImage() {
    var capcha = document.getElementById('captImg');
    if (capcha) {
        capcha.src = "/Captcha.jpg?" + Math.random();
    }
}

function arrayLength(arr) {
    var res = 0;
    for (i in arr) {
        res ++;
    }
    return res;
}

function reloadPage() {
    window.location.reload();
}

function getPageOffsetLeft(el) {
    var ol = el.offsetLeft;
    while ((el = el.offsetParent) != null) {
        ol += el.offsetLeft;
    }
    return ol;
}
function getWindowOffsetLeft(el) {
    return getPageOffsetLeft(el) - document.body.scrollLeft;
}
function getPageOffsetTop(el) {
    var ot = el.offsetTop;
    while ((el = el.offsetParent) != null) {
        ot += el.offsetTop;
    }
    return ot;
}
function getWindowOffsetTop(el) {
    return getPageOffsetTop(el) - document.body.scrollTop;
}

function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof( window.pageYOffset ) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && ( document.body.scrollLeft || document.body.scrollTop )) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop )) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
 Order modal window 
 */
function initCpOrderModalWindow(inputIdArr, submitId) {
    for (var i = 0; i < inputIdArr.length; i++) {
        var input = $(inputIdArr[i]);
        Event.observe(input, "keyup", function (event) {
            var disableSubmit = false;
            for (var i = 0; i < inputIdArr.length; i++) {
                var input = $(inputIdArr[i]);
                if (input.value == '') {
                    disableSubmit = true;
                    break;
                }
            }
            if (disableSubmit) {
                $(submitId).setAttribute("disabled", "disabled");
            } else {
                $(submitId).removeAttribute("disabled");
            }
        }
                );
    }
    $(submitId).setAttribute("disabled", "disabled");
}

function sendCpOrder(arrId, submit) {
    submit.setAttribute("disabled", "disabled");
    var strToEval = 'DwrControlPanel.sendOrder(';
    for (var i = 0; i < arrId.length; i++) {
        strToEval += "\"" + $(arrId[i]).value.replace(/"/g, "\\\"") + "\"";
        if (i < arrId.length - 1) {
            strToEval += ", ";
        }
    }
    strToEval += ", cbSendOrder)";
    eval(strToEval);
}

function cbSendOrder() {
    Modalbox.show("/cp/OrderSent.html", {title: 'Сообщение', width: 300, height:140});
}

function dwrCheckEmail() {
    email = document.getElementById('emailInput').value;
    msg = document.getElementById('msg');
    msg.innerHTML = '<img src="/images/cp/spinner.gif" alt="*" height="30" width="30"/> Проверка';
    DwrEmailCheck.isEmailExist(email, checkEmailCallback);
}

function checkEmailCallback(isExist) {
    if (isExist) {
        Modalbox.show('RetrieveSend.html', {title: 'Восстановление пароля', width: 400, params:Form.serialize('fId') });
    } else {
        msg = document.getElementById('msg');
        msg.innerHTML = '<font color="red">ОШИБКА: e-mail отсуствует в базе!</font>';
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
 Item page. Characteristics block
 */
function initCharacteristicEffects() {
    Effect.OpenUp = function(element) {
        element = $(element);
        new Effect.BlindDown(element, arguments[1] || {});
    };

    Effect.CloseDown = function(element) {
        element = $(element);
        new Effect.BlindUp(element, arguments[1] || {});
    };

    Effect.Combo = function(element) {
        element = $(element);
        if (element.style.display == 'none') {
            new Effect.OpenUp(element, arguments[1] || {});
        }
        else {
            new Effect.CloseDown(element, arguments[1] || {});
        }
    };
}

function switchCharacteristics(linkId, blockId) {
    Effect.Combo(blockId, {duration: 0.5, scaleX: false, scaleContent: true});
    var link = $(linkId);
    if (link.innerHTML != link.getAttribute('text1')) {
        link.innerHTML = link.getAttribute('text1');
    } else {
        link.innerHTML = link.getAttribute('text2');
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
 Login DWR functions
 */
function loginDwr() {
    var email = $('loginWindowUid').value;
    var pwd = $('loginWindowPwd').value;
    DwrLogin.authorize(email, pwd, loginDwrCallBack);
}

function loginDwrCallBack(errors) {
    if (errors != null && errors.length > 0) {
        var errBlock = $('loginWindowErrors');
        errBlock.innerHTML = '';
        for (var i = 0; i < errors.length; i++) {
            var err = errors[i];
            var elem = document.createElement('li');
            elem.innerHTML = err;
            errBlock.appendChild(elem);
        }
    } else {
        document.location = '/cp/ShowInformation.html';
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
 For news block
 */
var last_obj = null;
var active_tooltip = null;

/*
function showTooltip(obj) {
    if (obj == last_obj) return;
    var p = obj;
    if (p) {
        var divlist = p.getElementsByTagName('div');

        for (var i = 0; i < divlist.length; ++i) {
            var io = divlist.item(i);
            if (io.className.toLowerCase().indexOf('hiddentooltip') != -1) {
                active_tooltip = io;
            }
        }
    }
    if (active_tooltip) {
        active_tooltip.style.display = 'block';
    }
    last_obj = p;
}

function hideTooltip() {
    if (active_tooltip) {
        active_tooltip.style.display = 'none';
        active_tooltip = null;
    }
    last_obj = null;
}
*/

function setActive(ctrl_id, tab, data_div_id) {
    var p = document.getElementById(ctrl_id);
    var d = document.getElementById(data_div_id);
    var tabNodes = null;
    if (p && tab && d) {
        for (var childItem in p.childNodes) {
            if (p.childNodes[childItem].nodeType == 1) {
                var node = p.childNodes[childItem];
                if (node.className.toLowerCase().indexOf('tabitems') != -1) {
                    tabNodes = node;
                } else {
                    node.style.display = 'none';
                }
            }
        }

        if (tabNodes) {
            for (var childItem in tabNodes.childNodes) {
                if (tabNodes.childNodes[childItem].nodeType == 1) {
                    if (tabNodes.childNodes[childItem].className.toLowerCase().indexOf('tabitem') != -1)
                        tabNodes.childNodes[childItem].className = 'tabItem inactive';
                }
            }
        }

        tab.className = 'tabItem active';
        d.style.display = 'block';
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
 Functions for gallery displaying
 */
var showFlag;
var showTimeout;
var hideTimeout;

function showGalleryWindow(img) {
    gallerySetup(img);

    var position = getElementPosition(img.id);

    var galleryWindow = document.getElementById('galleryWindow');

    galleryWindow.style.top = position.top + "px";
    galleryWindow.style.left = position.left + "px";

    clearTimeout(hideTimeout);
    showTimeout = setTimeout("show()", 1200);
}

function hideGalleryWindow() {
    clearTimeout(showTimeout);
    hideTimeout = setTimeout("hide()", 500);
}

function holdGalleryWindow() {
    clearTimeout(hideTimeout);
}

function show() {
    var galleryWindow = document.getElementById('galleryWindow');

    galleryWindow.style.display = "block";

    showFlag = true;

    clearTimeout(showTimeout);
    clearTimeout(hideTimeout);
}

function hide() {
    var galleryWindow = document.getElementById('galleryWindow');
    galleryWindow.style.display = "none";

    clearTimeout(hideTimeout);
}

function getElementPosition(elemId) {
    var elem = document.getElementById(elemId);

    var w = elem.offsetWidth;
    var h = elem.offsetHeight;

    var l = 0;
    var t = 0;

    while (elem) {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }

    if (parseInt(l + 490) < parseInt(document.body.clientWidth)) {
        l = l + w / 2;
        document.getElementById("arrowLeft").style.display = "block";
        document.getElementById("arrowRight").style.display = "none";
    } else {
        l = l + w / 2 - 490;
        document.getElementById("arrowLeft").style.display = "none";
        document.getElementById("arrowRight").style.display = "block";
    }

    var galeryHeight = 415;
    if (t - h / 2 < 0) {
        var x = t - h / 2 - 10;
        t = t - t + 10;
        document.getElementById("imgArrowLeft").style.top = x + "px";
        document.getElementById("imgArrowRight").style.top = x + "px";
    } else if (t - h / 2 + galeryHeight > parseInt(document.body.clientHeight)) {
        var y = 0;
        t = document.body.clientHeight - galeryHeight;
        document.getElementById("imgArrowLeft").style.top = y + "px";
        document.getElementById("imgArrowRight").style.top = y + "px";

    } else {
        t = t - galeryHeight / 2 + h / 2;
        document.getElementById("imgArrowLeft").style.top = 0;
        document.getElementById("imgArrowRight").style.top = 0;
    }

    return {"left":l, "top":t, "width": w, "height":h};
}

function gallerySetup(img) {

    positionReset();

    document.getElementById("mainImage").src = document.getElementById(img.id + "_mainImg").src;

    var galleryDiv = document.getElementById(img.id + "_gallImg");
    var imgGallery = document.getElementById("imageGallery");
    var childNodes = galleryDiv.childNodes;

    imgGallery.innerHTML = "";

    for (var i = 0; i < childNodes.length; i++) {
        if (childNodes[i].nodeName == "IMG") {
            imgGallery.appendChild(childNodes[i].cloneNode(true));
        }
        if (childNodes[i].nodeName == "BR") {
            imgGallery.appendChild(childNodes[i].cloneNode(true));
        }
    }
}

// Partner blocks function
function showItemDetails(announceTitle, announceSubtitle, imageSrc, companyName, itemPrice, companyInfoHref) {
    var code = '<table style=\'background-color:white; border: thin solid #000000\' height=\'500\' width=\'300\' align=\'center\'>' +
               '<tr><td><b>' + announceTitle + '</b></td></tr><tr><td align=\'center\' height=\'400\' width=\'300\' style=\'border: thin solid #999999\'>' +
               '<img src=\' ' + imageSrc + '\'/></td></tr><tr><td><table width=\'98%\' border=\'0\' cellspacing=\'0\' cellpadding=\'3\'>' +
               '<tr height=\'5\'><td></td></tr><tr><td width=\'60%\' valign=\'top\' style=\'text-align:left\'><font size=\'2\'>' +
               announceSubtitle + '</font></td><td width=\'40%\' style=\'border-left:thin #666666 solid;text-align:left\' valign=\'top\'>' +
               '<table><tr><td><b><font size=\'2\'>' + companyName + '</font></b></td></tr><tr  height=\'50px\' valign=\'bottom\'>' +
               '<td align=\'right\'><font class=\'ws12\' color=\'#ff6600\'><b>' + itemPrice + ' грн</b></font><br/><a href=\' ' + companyInfoHref + '\'>Далее</a> </td></tr></table>     </td></tr></table></td></tr></table>';
    return overlib(code, STICKY, DELAY, 500, HEIGHT, 500, NOCLOSE, VAUTO);
}

//Functions for gallery viewing

var interval;
var sizesHack = new Array();
function hack() {
    if (document.body.clientHeight > sizesHack['height'] || document.body.clientWidth > sizesHack['width']) {
        alert('hack!');
    }
}

function showGallery(images) {
    if (images.length > 0) {
        var firstImage = images[0];
        var code = '<div style="border-bottom:1px solid #979c98; border-right:1px solid #979c98;"><div style="border:1px solid #336699; width:460px; height:412px; background-color:#eef7ff"><div style="margin:5px; background-color:#ffffff; width:450px; height:402px;"><div style="width:448px; height:400px; text-align:center; vertical-align:middle;"><table style="width:100%; height:100%;" border="0"><tr height="400px"><td style="text-align:center; vertical-align:middle;" width="200px">'
                + '<img id="mainImage" src="' + firstImage + '" alt="" border="0">' +
                   '</td><td style="vertical-align:top;" width="100px"><div style="position:relative;"><img style="cursor:pointer;" src="/images/up.gif" alt="" onmouseover="scrollForward();" onmouseout="stopMoover();" onmousedown="fastScrollForward();" onmouseup="scrollForward();"/><br/></div><div style="height:370px; overflow-y:hidden; overflow-x:visible;position:relative; vertical-align:top;"><table id="imagesList" align="center" cellpadding="5" cellspacing="0" border="0" style="position:relative; top:0;"><tr><td id="imageGallery">';
        for (i = 0; i < images.length; i++) {
            code += '<img style="cursor:pointer; margin:4px;" width="60" height="120" src="' + images[i] + '" alt="' + images[i] + '" onclick="previewImage(this);"/><br/>';
        }
        code += '</td></tr></table></div><div style="position:relative;"><img style="cursor:pointer;" src="/images/down.gif" alt="" onmouseover="scrollBackward();" onmouseout="stopMoover();" onmousedown="fastScrollBackward();" onmouseup="scrollBackward();"/><br/></div></td></tr></table></div></div></div></div>';
        //        sizesHack['height'] = document.body.clientHeight;
        //        sizesHack['width'] = document.body.clientWidth;
        var delay = 500;
        var res = overlib(code, STICKY, DELAY, delay, HEIGHT, 400, NOCLOSE, VAUTO);
        //        setTimeout(hack, delay + 10);
        return res;
    } else {
        return null;
    }
}

function previewImage(img) {
    document.getElementById("mainImage").src = img.src;
}

function scrollForward() {
    clearInterval(interval);
    interval = setInterval("forwardMoover()", 1);
}

function fastScrollForward() {
    clearInterval(interval);
    interval = setInterval("fastForwardMoover()", 1);
}

function scrollBackward() {
    clearInterval(interval);
    interval = setInterval("backwardMoover()", 1);
}

function fastScrollBackward() {
    clearInterval(interval);
    interval = setInterval("fastBackwardMoover()", 1);
}

function forwardMoover() {
    if (parseInt(document.getElementById("imagesList").style.top) <= 0) {
        document.getElementById("imagesList").style.top = parseInt(document.getElementById("imagesList").style.top) + 3 + "px";
    }
}

function backwardMoover() {
    if (parseInt(document.getElementById("imagesList").style.top) > 370 - parseInt(document.getElementById("imagesList").offsetHeight)) {
        document.getElementById("imagesList").style.top = parseInt(document.getElementById("imagesList").style.top) - 3 + "px";
    }
}

function fastForwardMoover() {
    if (parseInt(document.getElementById("imagesList").style.top) <= 0) {
        document.getElementById("imagesList").style.top = parseInt(document.getElementById("imagesList").style.top) + 6 + "px";
    }
}

function fastBackwardMoover() {
    if (parseInt(document.getElementById("imagesList").style.top) > 370 - parseInt(document.getElementById("imagesList").offsetHeight)) {
        document.getElementById("imagesList").style.top = parseInt(document.getElementById("imagesList").style.top) - 6 + "px";
    }
}

function stopMoover() {
    clearInterval(interval);
}

function positionReset() {
    document.getElementById("imagesList").style.top = 0;
}
//----------------------------------------------------------------------------------------------------------------------
/*
 SelectOptionWindow functions
 */
function selectOptionWindowShow(event, srcMap, idForDstHtmlId, idForDstTitle, windowTitle, callbackFunction) {
    //srcMap: htmlId => title
    var rowsCount = parseInt(arrayLength(srcMap) / 2);
    if (arrayLength(srcMap) % 2 != 0) {
        rowsCount++;
    }
    var contentDiv = $('selectOptionWindowContent');
    if (arrayLength(srcMap) > 50) {
        contentDiv.style.height = "300px";
        contentDiv.style.overflowY = "scroll";
    } else {
        contentDiv.style.height = "auto";
        contentDiv.style.overflowY = "hidden";
    }
    document.getElementById("selectOptionWindowTitle").innerHTML = windowTitle;
    var html = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"wpmd\"><tr valign=\"top\">\n";
    var index = 0;
    html += "<td>";
    var keys = new Array();
    for (var key in srcMap) {
        keys[keys.length] = key;
    }
    keys.sort();
    var optionHtmlIdPrefix = "radio" + idForDstHtmlId;
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var radioId = optionHtmlIdPrefix + i;
        //        html += "<input type='radio' name='popupWindowRadioOption' value='' id='" + radioId + "' onclick='selectOptionWindowOptionClick(\'" + srcMap[key] + "\', \'" + key + "\', \'" + idForDstHtmlId + "\', \'" + idForDstTitle + "\', " + callbackFunction + ")' />";
        html += "<input type='radio' name='popupWindowRadioOption' value='" + srcMap[key] + "' id='" + radioId + "' />";
        html += "<label for='" + radioId + "'>" + key + "</label><br/>\n";
        index++;
        if (index == rowsCount) {
            html += "</td>";
            html += "<td>";
        }
    }
    html += "</td></tr></table>";
    var windowContent = document.getElementById("selectOptionWindowContent");
    windowContent.innerHTML = html;

    for (var j = 0; j < keys.length; j++) {
        var key = keys[j];
        var radioId = optionHtmlIdPrefix + j;
        $(radioId).onclick = selectOptionWindowOptionClick;
        $(radioId).setAttribute("title", key);
        $(radioId).setAttribute("idForDstHtmlId", idForDstHtmlId);
        $(radioId).setAttribute("idForDstTitle", idForDstTitle);
        $(radioId).setAttribute("cb", callbackFunction);
    }
    var windowDiv = document.getElementById('selectOptionWindow');
    var dstDiv = $(idForDstTitle);

    var windowTop = getScrollXY()[1];
    var windowLeft = getScrollXY()[0];
    windowDiv.style.left = (getPageOffsetLeft(dstDiv) - windowLeft + 15) + "px";
    windowDiv.style.top = (getPageOffsetTop(dstDiv) - windowTop + 15) + "px";
    $('selectOptionWindowLayer').style.left = windowLeft + "px";
    $('selectOptionWindowLayer').style.top = windowTop + "px";
    windowDiv.style.display = 'block';
    document.getElementById('selectOptionWindowLayer').style.display = 'block';
}

function selectOptionWindowOptionClick() {
    var htmlId = this.getAttribute("value");
    var title = this.getAttribute("title");
    var idForDstHtmlId = this.getAttribute("idForDstHtmlId");
    var idForDstTitle = this.getAttribute("idForDstTitle");
    var cb = this.getAttribute("cb");
    document.getElementById(idForDstHtmlId).value = htmlId;
    var elem = document.getElementById(idForDstTitle);
    elem.innerHTML = title;
    setTimeout('document.getElementById("selectOptionWindow").style.display = "none";', 300);
    setTimeout('document.getElementById("selectOptionWindowLayer").style.display = "none";', 300);
    if (cb != null) {
        eval(cb + "(htmlId)");
    }
}

/*
 function selectOptionWindowOptionClick(htmlId, title, idForDstHtmlId, idForDstTitle, cb) {
 document.getElementById(idForDstHtmlId).value = htmlId;
 var elem = document.getElementById(idForDstTitle);
 elem.innerHTML = title;
 setTimeout('document.getElementById("selectOptionWindow").style.display = "none";', 300);
 setTimeout('document.getElementById("selectOptionWindowLayer").style.display = "none";', 300);
 if (cb != null) {
 cb(htmlId);
 }
 }
 */

function selectOptionWindowClose(event, ignoreChild) {
    var windowDiv = document.getElementById('selectOptionWindow');
    var target = event.target;
    if (!target) {
        target = window.event.srcElement;
    }
    if (!containsChild(windowDiv, target) || ignoreChild) {
        windowDiv.style.display = 'none';
        document.getElementById('selectOptionWindowLayer').style.display = 'none';
    }
}


// CP REQUEST CHECKER
var myMegaId;
function onSubmitRequestChecker(msg) {
    Modalbox.show('<table><tr><td width=\'60px\'><img src=\'/images/cp/spinner.gif\'></td><td width=\'330px\'>' + msg + '</td></tr></table>', {title: 'Загрузка', height: 150});
    myMegaId = window.setInterval("checkRequestState()", 500);
}

function onSubmitRequestCheckerPrice() {
    onSubmitRequestChecker("Ожидайте, идет загрузка и разбор прайс-листа.");
}

function onSubmitRequestCheckerService() {
    onSubmitRequestChecker("Ожидайте, идет загрузка данных услуги");
}

function onSubmitRequestCheckerProduct() {
    onSubmitRequestChecker("Ожидайте, идет загрузка данных товара");
}

function checkRequestState() {
    DwrRequestChecker.redirectNeeded(checkRequestStateCallback);
    window.clearInterval(myMegaId);
}

function checkRequestStateCallback(url) {
    if (url.length > 0) {
        window.location.href = url;
    }
}

function compareItemsClick(htmId, uid) {
    var elem = $(uid);
    if (elem.className.indexOf('selectedForCompare') > 0) {
        DwrSelectForCompare.deselectItem(htmId, uid);
        elem.className = elem.className.substring(0, elem.className.indexOf(' selectedForCompare'));
    } else {
        DwrSelectForCompare.selectItem(htmId, uid);
        //        elem.className = elem.className + ' selectedForCompare';
    }
    DwrSelectForCompare.getSectedItems(htmId, compareItemsMarkElements);
}

function compareItemsMarkElements(uids) {
    compareWindowDiv = document.getElementById('compareWindow');
    compareWindowDivSubmit = document.getElementById('compareWindowSubmit');
    for (i = 0; i < uids.length; i++) {
        elem = document.getElementById(uids[i]);
        if (elem != null) {
            elem.className = elem.className + ' selectedForCompare';
        }
    }

    if (uids.length > 0) {
        compareWindowDiv.style.display = "block";
        selectedTd = document.getElementById('compareWindowTdSelected');
        leftTd = document.getElementById('compareWindowTdLeft');
        selectedTd.innerHTML = uids.length;
        leftTd.innerHTML = 5 - uids.length;
    } else {
        compareWindowDiv.style.display = "none";
    }

    if (uids.length > 1) {
        compareWindowDivSubmit.disabled = "";
    } else {
        compareWindowDivSubmit.disabled = "true";
    }
}

function changeTab(oldTabTitleId, newTabTitleId, oldTabContentId, newTabContentId) {
    $(oldTabTitleId).className = 'inactive';
    $(newTabTitleId).className = 'active';
    $(oldTabContentId).style.display = 'none';
    $(newTabContentId).style.display = 'block';
}

function changeTabOf3(oldTabTitleId_1, oldTabTitleId_2, newTabTitleId, oldTabContentId_1, oldTabContentId_2, newTabContentId) {
    $(oldTabTitleId_1).className = 'inactive';
    $(oldTabTitleId_2).className = 'inactive';
    $(newTabTitleId).className = 'active';
    $(oldTabContentId_1).style.display = 'none';
    $(oldTabContentId_2).style.display = 'none';
    $(newTabContentId).style.display = '';
}

var tmout, boyantime, nint;
function RunBoyan(obj) {
    tmout = window.setTimeout(function() {
        OpenBoyanFor(obj);
    }, 300);
}

function CancelBoyan() {
    window.clearTimeout(tmout);
}

function OpenBoyanFor(obj) {
    var toOpen = obj.firstChild.nextSibling.nextSibling.nextSibling;
    var toClose = obj.firstChild.nextSibling;
    if (toOpen.className.indexOf('shown') == -1) {
        toOpen.className = 'shown';
        toClose.className = 'hidden';
    }
}

function HideBoyan(obj) {
    boyantime = window.setTimeout(function() {
        CloseBoyan(obj);
    }, 1500);
}

function DontHideBoyan() {
    window.clearTimeout(boyantime);
}

function CloseBoyan(obj) {
    var toClose = obj.firstChild.nextSibling.nextSibling.nextSibling.firstChild.nextSibling.nextSibling.nextSibling;
    var toOpen = obj.firstChild.nextSibling.nextSibling.nextSibling.firstChild.nextSibling;
    toClose.className = 'hidden';
    toOpen.className = 'shown';
}



// REGIONS NEW
function createRegionsWindows(regionsUa, regionsRu, allRegionsPresent, selectedRegion, dstInputId, dstTitleId, callback) {
    var rowsUa = parseInt(arrayLength(regionsUa) / 2) - 1;
    if (regionsUa.length % 2 != 0) {
        rowsUa ++;
    }

    var rowsRu = parseInt(arrayLength(regionsRu) / 2) - 1;
    if (regionsRu.length % 2 != 0) {
        rowsRu ++;
    }

    var i;

    i = 0;
    var srcUa = '';
    var showUa = false;
    for (var name in regionsUa) {
        i++;

        var title = regionsUa[name];

        srcUa += '<input id="radioRegionUa_' + i + '" type="radio" value="' + name + '" name="region" title="' + title + '"';

        if (selectedRegion == name) {
            showUa = true;
            srcUa += ' checked';
        }

        srcUa += ' onchange="clickRegionsWindowRadio(this, \'' + dstInputId + '\', \'' + dstTitleId + '\', \'' + callback + '\');"';
        srcUa += '/>';
        srcUa += '<label for="radioRegionUa_' + i + '">' + title + '</label>';
        srcUa += '<br/>';

        if (i == rowsUa) {
            srcUa += '</td><td>';
        }
    }


    i = 0;
    var srcRu = '';
    var showRu = false;
    for (var name in regionsRu) {
        i++;

        var title = regionsRu[name];

        srcRu += '<input id="radioRegionRu_' + i + '" type="radio" value="' + name + '" name="region" title="' + title + '"';

        if (selectedRegion == name) {
            showRu = true;
            srcRu += ' checked';
        }

        srcRu += ' onchange="clickRegionsWindowRadio(this, \'' + dstInputId + '\', \'' + dstTitleId + '\', \'' + callback + '\');"';
        srcRu += '/>';
        srcRu += '<label for="radioRegionRu_' + i + '">' + title + '</label>';
        srcRu += '<br/>';

        if (i == rowsRu) {
            srcRu += '</td><td>';
        }
    }

    srcUa = '<tr id="regionsUa" valign="top" ' + (!showUa ? 'style="display: none;"' : '') + '><td style="width: 50%">' + srcUa + '</td></tr>';

    srcRu = '<tr id="regionsRu" valign="top" ' + (!showRu ? 'style="display: none;"' : '') + '><td style="width: 50%">' + srcRu + '</td></tr>';

    var head = '<table cellspacing="0" cellpadding="0" border="0" class="wpmd" style="width: 100%;">';

    if (allRegionsPresent) {
        head += '<tr><td colspan="2">';
        head += '<input type="radio" title="Все регионы" name="country" value="" id="radioRegionAll"' + (!showUa && !showRu ? 'checked' : '');
        head += ' onclick="clickRegionsWindowRadio(this, \'' + dstInputId + '\', \'' + dstTitleId + '\', \'' + callback + '\');"';
        head += '/>';
        head += '<label for="radioRegionAll">Все регионы</label>';
        head += '</td></tr>';
    }

    head += '<tr><td style="width: 50%">';
    head += '<input type="radio" title="Украина" name="country" value="Украина" id="radioRegionUa" onclick="showRegionsTr(this);" ' + (showUa ? 'checked' : '') + '/>';
    head += '<label for="radioRegionUa">Украина</label>';
    head += '</td><td style="width: 50%">';
    head += '<input type="radio" title="Украина" name="country" value="Россия" id="radioRegionRu" onclick="showRegionsTr(this);" ' + (showRu ? 'checked' : '') + '/>';
    head += '<label for="radioRegionRu">Россия</label>';
    head += '</td></tr>';
    head +=  '<tr><td colspan="2" style="height: 10px;"></td></tr>';

    var divOpen = '<tr><td colspan="2"><div style="width: 450px; max-height: 300px; overflow: auto;">';
    var divClose = '</div></td></tr>';

    var foot = '</table>';

    return head + divOpen + '<table style="width: 430px;">' + srcUa + srcRu + '</table>' + divClose + foot;
}

function showRegionsWindow(regionsUa, regionsRu, selectedRegion, allRegionsPresent, dstInputId, dstTitleId, callback) {
    var src = createRegionsWindows(regionsUa, regionsRu, allRegionsPresent, selectedRegion, dstInputId, dstTitleId, callback);

    var div = document.getElementById('selectOptionWindowContent');
    div.innerHTML = src;
    div.style.display = '';


    var dstDiv = document.getElementById(dstTitleId);
    var windowDiv = document.getElementById('selectOptionWindow');
    var layerDiv = document.getElementById('selectOptionWindowLayer');

    var windowTop = getScrollXY()[1];
    var windowLeft = getScrollXY()[0];

    windowDiv.style.left = (getPageOffsetLeft(dstDiv) - windowLeft + 15) + "px";
    windowDiv.style.top = (getPageOffsetTop(dstDiv) - windowTop + 15) + "px";

    layerDiv.style.left = windowLeft + "px";
    layerDiv.style.top = windowTop + "px";

    windowDiv.style.display = 'block';

    layerDiv.style.display = 'block';
}

function hideRegionsWindow(event, ignoreChild) {
    var windowDiv = document.getElementById('selectOptionWindow');
    if (event == null) {
        document.getElementById('selectOptionWindowLayer').style.display = 'none';
        return;
    }

    var target = event.target;
    if (!target) {
        target = window.event.srcElement;
    }
    if (!containsChild(windowDiv, target) || ignoreChild) {
        windowDiv.style.display = 'none';
        document.getElementById('selectOptionWindowLayer').style.display = 'none';
    }
}

function clickRegionsWindowRadio(radio, dstInputId, dstTitleId, callback) {
    var region = radio.value;
    var regionTitle = radio.title;

    var dstInput = document.getElementById(dstInputId);
    var dstTitle = document.getElementById(dstTitleId);

    dstInput.value = region;
    dstTitle.innerHTML = regionTitle;

    if (callback != '') {
        eval(callback);
    }
}

function showRegionsTr(srcRadio) {
    if ('radioRegionUa' == srcRadio.id) {
        document.getElementById('regionsRu').style.display = 'none';
        document.getElementById('regionsUa').style.display = '';
    } else if ('radioRegionRu' == srcRadio.id) {
        document.getElementById('regionsRu').style.display = '';
        document.getElementById('regionsUa').style.display = 'none';
    }
}
