dojo.require("dojo.style");
dojo.require("dojo.event");
dojo.require("dojo.html.*");

var NO_RESPONSE_TIMEOUT = 40000;
var PHOTOVIEW_NO_RESPONSE_TIMEOUT = 30000;
var RESPONSE_JS_ERRORS_TIMEOUT = 10000;

var dialogWidthOffset = 42;
var dialogHeightOffset = 51;
var dialogBorderWidthOffset = 40;
var dialogBorderHeightOffset = 26;

function getDialogObjectById(dialogId) {
    if (popupDialog.secondLevelActive && popupDialog.secondLevelActive.dialog.id == dialogId ||
            popupDialog.active && popupDialog.active.dialog.id == dialogId) {
        return popupDialog;
    }
    return infoDialog;
}

function changeDialogTabCaption(dialogId, tabIndex, newCaption) {
    if (dojo.byId(dialogId+"TabCaption"+tabIndex)) {
        dojo.byId(dialogId+"TabCaption"+tabIndex).innerHTML = newCaption;
    } else {
        console.error("Can't find element: '" + dialogId+"TabCaption"+tabIndex +"'");
    }
}

//update tabs classes
function updateClasses (dialogId, newCurTabIndex) {
    var tabs = dojo.byId(dialogId + 'TabSet').getElementsByTagName("table");
    var dialog = dojo.byId(dialogId);
    newCurTabIndex = parseInt (newCurTabIndex);
    for (var i = 0; i < tabs.length; i++)
    {
        var curTab = dojo.byId(dialogId+"Tab"+i);
        if (dojo.html.hasClass(tabs[i],'activeDialogTab')) {
            dojo.html.setClass(tabs[i], 'inactiveDialogTab');
            var tabIndex = i;
            curTab.onclick = function() {
                switchTabs (dialogId, tabIndex, dialog.getAttribute("nonAjaxTabs"));
            }
        }
        if (i == newCurTabIndex) {
            dojo.html.setClass(tabs[i], 'activeDialogTab');
            curTab.onclick = function() { }
        }
    }
}

function switchTabs (dialogId, newCurTabIndex, nonAjaxTab) {
    var dialogObject = getDialogObjectById(dialogId);
    var active = dialogObject.getActiveByDialogId(dialogId);
    if (active.tabSwitchInProgress || active.dialogShowInProgress ||
        !dojo.byId(dialogId+"Tab"+newCurTabIndex) )
        return;
    updateClasses (dialogId, newCurTabIndex);
    if (nonAjaxTab) {
        var curTabIndex = active.dialog.getAttribute("currentTabIndex") ? parseInt(active.dialog.getAttribute("currentTabIndex")) : 0;
        dojo.byId(dialogId+'TabBlock'+curTabIndex).style.display="none";
        dojo.byId(dialogId+'TabBlock'+newCurTabIndex).style.display="block";
    } else {
        var nvs = new Array();
        nvs.push('display_dialog_id');
        nvs.push(dialogId);
        var fnc = eval('document.ajax_call_' + dialogId + 'updateContent');
        setDialogHeight(active.dialog, "auto");
        fnc.apply(this, [newCurTabIndex.toString(), '', false, nvs]);
        active.tabSwitchInProgress = true;
    }
    active.dialog.setAttribute("currentTabIndex", newCurTabIndex);
    active.currentTabIndex = newCurTabIndex;
    dialogObject.fireEvent('onTabSwitch', active, newCurTabIndex);
}

function showDialog (dialogId, newCurTabIndex) {
    popupDialog.getActive().currentTabIndex = newCurTabIndex;
    updateClasses (dialogId, newCurTabIndex);
    var nvs = new Array();
    nvs.push('display_dialog_id');
    nvs.push(dialogId);
    nvs.push('display_dialog');
    nvs.push('true');
    var fnc = eval('document.ajax_call_' + dialogId + 'updateContent');
    fnc.apply(this, [newCurTabIndex.toString(), '', false, nvs]);
    popupDialog.getActive().dialogShowInProgress = true;
}


//  Initializing tabset. Adjusting widthes
function adjustWidthes (dialogId) {
    var maxWidth = 0;
    var tabs =  dojo.byId(dialogId + "TabSet").getElementsByTagName("table");
    for (i = 0; i < tabs.length; i++) {
        tabs[i].style.width = "auto";
        if (tabs[i].offsetWidth > maxWidth)
            maxWidth = tabs[i].offsetWidth;
    }
    if (maxWidth==0) {
        return;
    }
    for (i = 0; i < tabs.length; i++) {
        var tabName = dojo.byId(dialogId+"Tab"+i).innerHTML.toLowerCase();
        if (tabName.indexOf("help") != -1 || tabName.indexOf("info") != -1)
            tabs[i].style.width = "auto";
        else
            tabs[i].style.width = maxWidth + "px";
    }
}

function dialogAfterLoadListener(dialog) {
    dialog = dojo.byId(dialog);
    var textareas = dialog.getElementsByTagName('textarea');
    for (i=0; i<textareas.length; i++) {
        dojo.event.connect (textareas[i],"onfocus",function() {
            document.dialogTextAreaFocused = true;
        });
        dojo.event.connect (textareas[i],"onblur",function() {
            document.dialogTextAreaFocused = false;
        });
    }
    if (dojo.html.hasClass(dialog, "Dialog") && dialog.getAttribute("isLightWeight")!="true") {
        var modalSubstLayer = dojo.byId("modalSubstLayer");
        if (modalSubstLayer)
            dojo.event.connect(modalSubstLayer, "onmousedown", popupDialog, "hide");
        popupDialog.getActive().allowHidingDialog = true;
        if (popupDialog.getActive() && !popupDialog.getActive().disableAutoSizing) {
            var dialogWidth = parseInt(dialog.getAttribute("dialogWidth"));
            var dialogHeight = parseInt(dialog.getAttribute("dialogHeight"));
            var inscribeSize = inscribeDialogContentWidth(dojo.byId(dialog.id+"content"), dialogWidth - dialogWidthOffset,
                    dialogHeight - dialogHeightOffset, "Dialog");
            dialog.style.width = (inscribeSize.width ? (inscribeSize.width + dialogWidthOffset) : dialogWidth) + 'px';
            setDialogHeight(dialog, inscribeSize.height + dialogHeightOffset);
        }
    }
    if (popupDialog.getActive()) {
        popupDialog.getActive().tabSwitchInProgress = false;
        popupDialog.getActive().dialogShowInProgress = false;
    }
}

//inscribes dialog content into hidden div and returns width for it (max of suggested and actual) and height (min of suggested and actual)
function inscribeDialogContentWidth(contentElem, suggWidth, suggHeight, inscribeClass) {
    var inscribeDiv = dojo.byId("dialogContentInscribeDiv");
    if (!inscribeDiv) {
        inscribeDiv = document.createElement("div");
        document.body.appendChild(inscribeDiv);
        inscribeDiv.id = "dialogContentInscribeDiv";
        inscribeDiv.style.left = "0";
        inscribeDiv.style.top = "0";
        inscribeDiv.style.position = "absolute";
        inscribeDiv.style.overflow = "auto";
    }
    inscribeDiv.className = inscribeClass;
    inscribeDiv.style.width = suggWidth + 'px';
    inscribeDiv.innerHTML = contentElem.innerHTML;
    var height = suggHeight ? Math.min(suggHeight, inscribeDiv.scrollHeight) : inscribeDiv.scrollHeight;
    var obj = {width: Math.max(suggWidth, inscribeDiv.scrollWidth),
        height: height};
    inscribeDiv.innerHTML = "";
    return obj;
}

/*block clicking ouside dialog while ajax request is in progress*/
function dialogRefreshContent(active) {
    var dialog = active.dialog;
    if (dojo.html.hasClass(dialog, 'Dialog')) {
        if (dialog.getAttribute("isLightWeight")=="true")
            return false;
        dojo.byId(dialog.id + 'content').style.display = 'none';
        dojo.byId(dialog.id + 'contentSubstDiv').style.display = 'block';
        var modalSubstLayer = dojo.byId("modalSubstLayer");
        if (modalSubstLayer)
            dojo.event.disconnect(modalSubstLayer, "onmousedown", popupDialog, "hide");
        popupDialog.getActive().allowHidingDialog = false;
        return true
    }
}

document.submitDialog = function(buttonId, dialogId, formName) {
    var frm = find_control(formName);
    var nvs = new Array();
    add_all_form_hiddens(frm, nvs);

    var namesArray = collect_all_form_visible_field_names(formName);
    var names = namesArray.split(',');
    try {
        var controls = find_controls(names, formName);
        for (var i = 0; i < controls.length; i++) {
            var com = controls[i];
            var tagName = com.tagName.toLowerCase();
            if (tagName == 'input' || tagName == 'select' || tagName == 'textarea') {
                addFormComponents(nvs, com);
            } else {
                addFormComponentsFromNode(nvs, com);
            }
        }
    } catch (e) {

    }
    nvs.push('submit_button_id');
    nvs.push(buttonId);
    nvs.push('display_dialog_id');
    nvs.push(dialogId);
    nvs.push('show_dialog');
    nvs.push('true');
    displayRequestLayer(true);
    window.clearTimeout(document.removeLayerTimeout);
    document.removeLayerTimeout = setTimeout("ajaxResponseNotReceived()", NO_RESPONSE_TIMEOUT);
    setDialogHeight(dojo.byId(dialogId), "auto");
    send_ajax_request(dialogId, nvs, frm.action, false);
}

function removeLayerResponse() {
    window.clearTimeout(document.removeLayerTimeout);
    document.removeLayerTimeout = setTimeout("ajaxResponseHasErrors()", RESPONSE_JS_ERRORS_TIMEOUT);
}

function ajaxResponseNotReceived() {
    displayRequestLayer(false);
    popupDialog.getActive().allowHidingDialog = true;
    alert('No response from server has been received!');
}

function ajaxResponseHasErrors() {
    displayRequestLayer(false);
    popupDialog.getActive().allowHidingDialog = true;
    alert('Received response has errors!');
}

function displayRequestLayer(display) {
    dojo.byId('ajaxRequestLayer').style.display= display ? 'block' : 'none';
}

function initDialogDragging(dialogId) {
    if (isUndefined(window.initDialogDragElement)) return;
    var curElement=dojo.byId(dialogId);
    for (var k=0; k<curElement.childNodes.length; k++) {
        if (curElement.childNodes[k].nodeName.toLowerCase()=="table") {
            curElement = curElement.childNodes[k];
        }
    }
    for (var k=0; k<curElement.childNodes.length; k++) {
        if (curElement.childNodes[k].nodeName.toLowerCase()=="tbody") {
            curElement = curElement.childNodes[k];
        }
    }
    var trs=curElement.childNodes;
    for (var i = 0; i < trs.length; i++) {
        for (var j = 0; j < trs[i].childNodes.length; j++) {
            if (trs[i].childNodes[j].nodeName.toLowerCase()=="td" &&
                !(trs[i].childNodes[j].id == "innerTd" || trs[i].childNodes[j].id.indexOf("contentPane") > -1) ){
                initDialogDragElement(trs[i].childNodes[j]);
            }
        }
    }
}

/*inserts simple text into bubble and adjusts its width and height*/
function fillBubbleWithText (dialog, text, minWidth, padding, leftAlign) {
    if (!minWidth) minWidth=400;
    dialog = dojo.byId(dialog);
    dialog.style.left="-5000px";
    dialog.style.display="block";
    dialog.style.width = "auto";
    var content = dojo.byId(dialog.id + 'Content');
    content.style.padding = padding ? padding : "3px 4px";
    if (!leftAlign)
        content.style.textAlign = "center";
    content.innerHTML=text;
    dialog.style.width = inscribeDialogContentWidth(content, minWidth, null, "font-10").width + 38 + 'px';
    dialog.setAttribute('dialogWidth', dojo.style.getMarginBoxWidth(dialog));
    dialog.setAttribute('dialogHeight', dojo.style.getMarginBoxHeight(dialog));
}

function showHintBubble (dialog, markerSpan, xPos) {
    dialog = dojo.byId(dialog);
    markerSpan = dojo.byId(markerSpan);
    var spanLeft = dojo.style.getAbsoluteX(markerSpan, true);
    var dialogLeft = xPos ? xPos :
            spanLeft - parseInt(dialog.getAttribute("dialogWidth")) + 30;
    var dialogTop = dojo.style.getAbsoluteY(markerSpan, true) + dojo.byId("dialogBorderBotGreyTail").height - parseInt(dialog.getAttribute("dialogHeight")) - 3;
    popupDialog.show(dialog, {posX: dialogLeft, posY: dialogTop, reflectionVert: popupDialog.reflectionType.TOP, noFade: true, noLayer: true});
    var tail = popupDialog.getActive().tail;
    tail.style.left = (spanLeft + dojo.style.getMarginBoxWidth(markerSpan)/2 - tail.width/2) + 'px';
}

function hideDialog() {
    popupDialog.hide();
}

/*onclick listener for object which a bubble should appear at*/
function showTooltipOnClick(object, dialog, reflection) {
    dialog = dojo.byId(dialog);
    var objWidth = dojo.style.getMarginBoxWidth(object);
    var dialogLeft = dojo.style.getAbsoluteX(object, true) + objWidth/2 - parseInt(dialog.getAttribute("dialogWidth"))/2;
    dialogLeft = dialogLeft > 0 ? dialogLeft : 0;
    var dialogTop = dojo.style.getAbsoluteY(object, true) + dojo.byId("dialogBorderBotGreyTail").height - parseInt(dialog.getAttribute("dialogHeight")) - 8;
    var reflectionVert = popupDialog.reflectionType.TOP;
    if (dialogTop < document.body.scrollTop + 10 || reflection == popupDialog.reflectionType.BOTTOM) {
        reflectionVert = popupDialog.reflectionType.BOTTOM;
        dialogTop = dojo.style.getAbsoluteY(object, true) + dojo.style.getMarginBoxHeight(object);
    }
    popupDialog.show(dialog, {posX: dialogLeft, posY: dialogTop, reflectionVert: reflectionVert, noFade: true});
    var tail = popupDialog.getActive().tail;
    tail.style.left = (dojo.style.getAbsoluteX(object, true) + objWidth/2 - tail.width/2) + 'px';
}

/*displays DialogBorder *dialog* at the top of *object* at horizontal middle.*/
function showDialogAtTopCenter(object, dialog, offsetY, params) {
    dialog = dojo.byId(dialog);
    popupDialog.fireEvent('prepareForShow', dialog);
    if (!params) params = {};
    dialog.style.left = "-5000px";
    dialog.style.display = "block";
    object = dojo.byId(object);
    var objectLeft = dojo.style.getAbsoluteX(object, true);
    var objectWidth = dojo.html.getMarginBoxWidth(object);
    params.posX = params.posX ? params.posX : objectLeft - dialog.getAttribute('dialogWidth')/2 + objectWidth/2;
    params.posX = Math.max(params.posX, 10);
    params.posX = Math.min(params.posX, dojo.html.getViewportWidth() + getScrollLeft() - 10 - dojo.style.getMarginBoxWidth(dialog));
    params.reflectionVert = params.reflectionVert ? params.reflectionVert : popupDialog.reflectionType.TOP;
    if (!params.posY) {
        if (params.reflectionVert == popupDialog.reflectionType.TOP) {
            params.posY = dojo.style.getAbsoluteY(object, true) - dialog.offsetHeight +
                        (dojo.html.hasClass(dialog, "tailedDialog") ? dojo.byId('dialogBorderBotWhiteTail').height : 0) + (offsetY ? offsetY : 0);
        } else {
            params.posY = dojo.style.getAbsoluteY(object, true) -
                        (dojo.html.hasClass(dialog, "tailedDialog") ? dojo.byId('dialogBorderBotWhiteTail').height : 0) + (offsetY ? offsetY : 0);
        }
    }
    popupDialog.show(dialog, params);
    var tail = popupDialog.getActiveTail();
    if (tail) {
        tail.style.left = objectLeft + objectWidth/2 - tail.width/2 + 'px';
    }
}

function removeHoverOnDialogClose(button, dialogId, imageName) {
    if (popupDialog.getActive() != null && popupDialog.getActive().dialog.id == dialogId) {
        return;
    }
    button.src = imageName;
}

function dialogOnResize() {
    if (!popupDialog.getActive())
        return;
    var dialog = popupDialog.getActive().dialog;
    if (popupDialog.getActive().dialogPositionGetter) {
        popupDialog.recalculatePosition();
        return;
    }
    var windowWidth = dojo.html.getViewportWidth();
    var windowHeight = dojo.html.getViewportHeight();
    var dialogRight = parseInt(dialog.style.left) + dojo.style.getMarginBoxWidth(dialog);
    var dialogBottom = parseInt(dialog.style.top) + dojo.style.getMarginBoxHeight(dialog);
    if (dialogRight > windowWidth - 10) {
        var dialogLeft = parseInt(dialog.style.left) - (dialogRight - windowWidth + 10);
        dialog.style.left = (dialogLeft > 0 ? dialogLeft : 0) + 'px';
    }
    if (dialogBottom > windowHeight - 10) {
        var dialogTop = parseInt(dialog.style.top) - (dialogBottom - windowHeight + 10);
        dialog.style.top = (dialogTop > 0 ? dialogTop : 0) + 'px';
    }
}

function setDialogHeight(dialog, height) {
    if (!dojo.html.hasClass(dialog, "Dialog")) return false;
    dojo.byId(dialog.id + '_contentPane').style.height =
        (height == "auto" ? "auto" : (height - dialogHeightOffset) + "px");
    dialog.setAttribute("dialogHeight", height);
    return true;
}

function setDialogWidth(dialog, width) {
    dialog = dojo.byId(dialog);
    dialog.style.width = width+"px";
    dialog.setAttribute("dialogWidth", width);
}

function showInfoTooltip(link, text, width) {
    width = width ? width : 320;
    var dialog = dojo.byId('HintPopup');
    fillBubbleWithText(dialog, text, width);
    dojo.byId('HintPopupContent').style.textAlign="left";
    showDialogAtTopCenter(link, dialog, 3, {noFade: true, isSecondLevel: true});
}