var djConfig = {
    //  isDebug:true,
    parseOnLoad: true
};

function sourceNodeCreator(panelItem) {

    var panel = document.createElement("div");
    dojo.addClass(panel, "panel");
    dojo.attr(panel, {
        id: "dojoUnique" + panelItem.tfid,
        paneltype: panelItem.type,
        tfid: panelItem.tfid
    });

    panel.style.left = panelItem.left + "px";
    panel.style.top = panelItem.top + "px";

    var contentId = panelItem.contentId;
    var cname = "";
    if (panelItem.type % 2 == 1) {
        cname = "narrowPanel";
    }
    else {
        cname = "widePanel";
    }

    var panelContentHeight = CH - 47;
    if (panelItem.type > 2) {
        panelContentHeight += Math.floor((parseInt(panelItem.type) - 1) / 2) * CH;
    }

    var panelBoxHeight = Math.floor((parseInt(panelItem.type) + 1) / 2) * CH - 13;

    var innerhtml = new String();
    innerhtml += '	<div class="panelBox ' + cname + '" id="panelBox' + panelItem.tfid + '" style:"height:' + panelBoxHeight + 'px;">';
    innerhtml += '    	<div class="panelHeaderBox">';
    innerhtml += '			<div class="panelHeader clearfix">';
    innerhtml += '				<div class="titleBox" id="panelHandler' + panelItem.tfid + '">';
    innerhtml += panelItem.title;
    innerhtml += '				</div>';
    innerhtml += '				<div class="buttonsBox clearfix">';
    innerhtml += '					<div class="edit" onclick="editDialog(' + panelItem.tfid + ');"></div>';
    innerhtml += '					<div class="close" onClick="deletePanel(' + panelItem.tfid + ');"></div>';
    innerhtml += '				</div>';
    innerhtml += '			</div>';
    innerhtml += '		</div>';
    innerhtml += '		<div class="panelContentBox">';
    innerhtml += '			<div class="panelContent" id="panelContent' + panelItem.tfid + '" style="height:' + panelContentHeight + 'px;">';
    innerhtml += '				<iframe id="panelIframe' + panelItem.tfid + '" frameborder="0" scrolling="no"></iframe>';
    if (isLogin() || _later) {
        if (isPaid() || _later)
            innerhtml += '				<div id="moveMouseHolder' + panelItem.tfid + '" class="mouseHolder" style="display: none;"></div>';
        else
            innerhtml += '				<div id="moveMouseHolder' + panelItem.tfid + '" class="mouseHolder mousePointer" onclick="showUpgradeDialog({always: true})"></div>';
    } else
        innerhtml += '				<div id="moveMouseHolder' + panelItem.tfid + '" class="mouseHolder mousePointer" onclick="showAllowActionDialog({always: true})"></div>';

    innerhtml += '			</div>';
    innerhtml += '		</div>';
    innerhtml += '  </div>';

    dojo.attr(panel, "innerHTML", innerhtml);
    getContent(contentId, panelItem.tfid);

    var area = dojo.byId('contentarea');
    area.appendChild(panel);

    var movable = new dojo.dnd.Moveable(panel, { handle: "panelHandler" + panelItem.tfid });
    current_tfid = panelItem.tfid;
}

function sourceNodePlaceHolder(panel) {

    var panelItem = getPanel(dojo.attr(panel, "tfid"));

    if (!panelItem) {
        alert("sourceNodePlaceHolder: No object to copy");
        return false;
    }

    var contentId = panelItem.contentId;
    var cname = "";
    if (panelItem.type % 2 == 1) {
        cname = "narrowPanel";
    }
    else {
        cname = "widePanel";
    }

    var panelContentHeight = CH - 47;
    if (panelItem.type > 2) {
        panelContentHeight += Math.floor((parseInt(panelItem.type) - 1) / 2) * CH;
    }

    var panelBoxHeight = Math.floor((parseInt(panelItem.type) + 1) / 2) * CH - 13;


    var innerHTML = new String();

    innerHTML += '<div class="placeHolderBox ' + cname + '">';
    innerHTML += '<div class="shadowTop">';
    innerHTML += '<div class="shadowBottom">';
    innerHTML += '<div class="placeHolderContent" style="height:' + panelBoxHeight + 'px;">';
    innerHTML += '</div>';
    innerHTML += '</div>';
    innerHTML += '</div>';
    innerHTML += '</div>';

    var copyPanel = document.createElement("div");
    copyPanel.id = "dojoCopy";
    copyPanel.className = "placeHolder";
    copyPanel.innerHTML = innerHTML;
    copyPanel.style.left = panelItem.left + "px";
    copyPanel.style.top = panelItem.top + "px";

    /*var copyPanel = panel.cloneNode(true);
    copyPanel.id = "dojoCopy" + panelItem.tfid;

	var panelContent = getChildByClassName(copyPanel, "panelContent");
    panelContent.innerHTML = "";
    */
    var area = dojo.byId('contentarea');
    area.appendChild(copyPanel);

    return copyPanel;
}

function onMouseOut(e) {

    if (!e) var e = window.event;
    var relTarg = e.relatedTarget || e.toElement;

    if (relTarg != null && relTarg.nodeName == "HTML" && lastMover != null) {
        dndStop();
    }
}

function dndStop() {
    //alert("GOT");
    var tmpMover = lastMover;

    dojo.publish("/dnd/move/stop", [tmpMover]);
    dojo.removeClass(dojo.body(), "dojoMove");
    dojo.removeClass(tmpMover.node, "dojoMoveItem");

    tmpMover.destroy();
    tmpMover = null;
    lastMover = null;
    if (dojo.isIE) {
        document.selection.clear();
    }
    else {
        window.getSelection().removeAllRanges();
    }
}

var lastMover = null;
function onDndStart(mover) {
    var panel = mover.node, tfid;
    if (!(tfid = dojo.attr(panel, "tfid"))) return;

    if (lastMover) {

        dndStop();
        return;
    }

    lastMover = mover;

    if (dojo.isIE) {
        if (window.event.button != 1) {
            dndStop();
            return;
        }
    } else if (mover.mouseButton != 0) {
        dndStop();
        return;
    }

    var feedbackDialogBox = dojo.byId("feedbackDialogBox");

    if (feedbackDialogBox) {
        feedbackDialogBox.style.display = "none";
    }

    showMouseHolder();

    var panelCopy = sourceNodePlaceHolder(mover.node);
    dojo.style(panel, "zIndex", 100);
    dojo.style(panelCopy, "zIndex", 1);

    dojo.style(panel, "opacity", 0.85);
}

function onDndDrop(mover) {
    var panel = mover.node;

    var type = dojo.attr(panel, "paneltype");
    var tfid = dojo.attr(panel, "tfid");

    if (!tfid) return;

    lastMover = null;

    var area = dojo.byId("contentarea");
    if (document.getElementById("dojoCopy"))
        area.removeChild(document.getElementById("dojoCopy")); // DO NOT USE DOJO instead getElementById!!! Cause of error if right mouse button menu appear

    if ((isLogin() && isPaid()) || _later) showMouseHolder(false);

    dojo.style(panel, "zIndex", 1);
    dojo.style(panel, "opacity", 1);

    var inner_x = MOUSE.x - getX(area);
    var inner_y = MOUSE.y - getY(area);

    var panelItem = getPanel(tfid);

    var u, v, u0, v0;
    u = Math.floor(inner_x / CW);
    v = Math.floor(inner_y / CH);
    u0 = Math.floor(panelItem.left / CW);
    v0 = Math.floor(panelItem.top / CW);

    if (type % 2 == 0) u = 0; // always drop wide panel on left side
    if (u < 0) u = 0; // left border
    if (u > 1) u = 1; // right border
    if (v < 0) v = 0; // top border
    if (v > 0 && _map[u][v] == _map[u][v - 1]) v--;
    while (v > 0 && _map[u][v] == _map[u][v - 1]) {
        --v; // always drop on top of panel
    }

    if (v > MAXVERT) v = MAXVERT; // bottom border

    if (u == u0 && v == v0) { // nothing was changed
        panel.style.left = panelItem.left + "px";
        panel.style.top = panelItem.top + "px";
        return;
    }

    //    printMap("before tfid delete\n");

    deleteFromMap(tfid);

    //    printMap("after tfid delete");

    if (!allowSimpleDrop(type, u, v)) {
        moveDown(type, u, v);
    }

    setMap(u, v, panelItem.type, tfid);

    gravitation();

    updatePanels();

    adjustContentArea();

    savePanelsState();

    if (!(isLogin() || _later)) {
        //panel.style.left = panelItem.left + "px";
        //panel.style.top = panelItem.top + "px";
        showAllowActionDialog();
    }
}


function allowSimpleDrop(type, u, v) {
    // return 0 - allow Drop; 1 - need to move down

    var t = type;
    while (t > 0) {
        if (_map[u][Math.floor(v + (t - 1) / 2)] != 0) return 0;
        t -= 2;
    }
    t = type;
    if (t % 2 == 0) {
        while (t > 0) {
            if (_map[u + 1][Math.floor(v + (t - 1) / 2)] != 0) return 0;
            t -= 2;
        }
    }
    return 1;
}

function gravitation() {
    var tfid, panel, i;

    //    printMap("before gravitation");

    for (var j = 1; j < MAXVERT; ++j) {

        if (_map[0][j] == 0 && _map[1][j] == 0) continue;

        if (_map[0][j] == _map[1][j] && _map[0][j - 1] == 0 && _map[1][j - 1] == 0) { //can fall up

            tfid = _map[0][j];
            panel = getPanel(tfid);

            if (panel.type % 2 == 0) {
                var t = panel.type, t2 = Math.floor(t / 2);
                while (j > 0 && _map[0][j] != 0 && _map[1][j] != 0 &&
                    _map[0][j - 1] == 0 && _map[1][j - 1] == 0) {

                    for (i = 0; i <= t2; ++i) {
                        _map[0][j - 1 + i] = tfid;
                        _map[1][j - 1 + i] = tfid;
                    }
                    _map[0][j - 2 + i] = 0;
                    _map[1][j - 2 + i] = 0;

                    --j;
                }
            }

        } else if (_map[0][j] != 0 && _map[0][j - 1] == 0) { // can fall up

            tfid = _map[0][j];
            panel = getPanel(tfid);
            if (panel.type % 2 == 1) {
                var t = panel.type, t2 = Math.floor(t / 2);
                while (j > 0 && _map[0][j] != 0 && _map[0][j - 1] == 0) {
                    for (i = 0; i <= t2; ++i) {
                        _map[0][j - 1 + i] = tfid;
                    }
                    _map[0][j - 1 + i] = 0;

                    --j;
                }
            }
        } else if (_map[1][j] != 0 && _map[1][j - 1] == 0) { // can fall up

            tfid = _map[1][j];
            panel = getPanel(tfid);

            if (panel.type % 2 == 1) {
                var t = panel.type, t2 = Math.floor(t / 2);
                while (j > 0 && _map[1][j] != 0 && _map[1][j - 1] == 0) {
                    for (i = 0; i <= t2; ++i) {
                        _map[1][j - 1 + i] = tfid;
                    }
                    _map[1][j - 1 + i] = 0;

                    --j;
                }
            }
        }
    }

    //    printMap("after gravitation\n");
}

/*
function printMap(s) {

console.log(s);
for (var i = 0; i <= 10; ++i) {
console.log(_map[0][i] + " " + _map[1][i] + "\n");
}

console.log("\n");
}
*/

function moveDown(type, u, v) {
    var i, vjump = 100;

    //    printMap("begin moveDown\n");

    //    if (type % 2 == 1) { //carefully! narrow panel

    for (i = _map[0].length - vjump - 1; i > v; --i) {
        _map[0][i + vjump] = _map[0][i];
        _map[1][i + vjump] = _map[1][i];
    }

    for (i = vjump; i > 0; --i) {
        _map[0][v + i] = 0;
        _map[1][v + i] = 0;
    }

    _map[u][v + vjump] = _map[u][v];
    _map[u][v] = 0;

    var t = v;
    while (t >= 0) {

        if (_map[1 - u][t] != _map[1 - u][t - 1]) {
            _map[1 - u][t + vjump] = _map[1 - u][t];
            _map[1 - u][t] = 0;
            break;
        }
        _map[1 - u][t + vjump] = _map[1 - u][t];
        _map[1 - u][t] = 0;

        --t;
    }

    //    printMap("end moveDown\n");
}

function updatePanels() {
    for (var j = 0; j < MAXVERT; ++j) {
        if (_map[0][j] != 0) {
            if (j == 0 || _map[0][j] != _map[0][j - 1]) {
                updatePanelPos(0, j);
            }
        }
        if (_map[1][j] != 0 && _map[1][j] != _map[0][j]) {
            if (j == 0 || _map[1][j] != _map[1][j - 1]) {
                updatePanelPos(1, j);
            }
        }
    }
}


function updatePanelPos(i, j) {
    var tfid, panel, div;

    tfid = _map[i][j];
    panel = getPanel(tfid);

    panel.left = i * CW;
    panel.top = j * CH;
    div = dojo.byId('dojoUnique' + tfid);
    div.style.left = panel.left + "px";
    div.style.top = panel.top + "px";
}


function adjustContentArea() {
    var area = dojo.byId("contentarea");
    area.style.height = getContentHeight() + 10 + "px"; // 40px bottom margin
}

function setMap(u, v, type, tfid) {
    var t = type;
    while (t > 0) {
        _map[u][Math.floor(v + (t - 1) / 2)] = tfid;
        t -= 2;
    }
    t = type;
    if (t % 2 == 0) {
        while (t > 0) {
            _map[u + 1][Math.floor(v + (t - 1) / 2)] = tfid;
            t -= 2;
        }
    }
}

function deleteFromMap(tfid) {
    for (var j = 0; j < MAXVERT; ++j) {
        if (_map[0][j] == tfid) {
            _map[0][j] = 0;
        }
        if (_map[1][j] == tfid) {
            _map[1][j] = 0;
        }
    }
}

function addPanel(newpanel) {

    if (panels.count >= MAX_PANELS_CNT) return;

    sourceNodeCreator(newpanel);
    panels.add(newpanel);

    var u, v;
    v = Math.floor(newpanel.top / CH);
    u = Math.floor(newpanel.left / CW);

    setMap(u, v, newpanel.type, newpanel.tfid);
}

function getPanel(tfid) {
    if (panels) {
        var i, panel;
        for (i = 0; i < panels.count; ++i) {
            panel = panels.item(i);
            if (panel.tfid == tfid) return panel;
        }
    }

    return null;
}

function deletePanel(tfid) {

    if (showAllowActionDialog({ action: "deletePanel", arg: tfid })) return;

    if (!confirm("Are you sure you want to delete this panel?")) return;

    var i, elem, t, src_left, src_top;

    var panel = getPanel(tfid);
    if (panel) {

        deleteFromMap(tfid);

        for (i = 0; i < panels.count; ++i) {
            if (panels.item(i).tfid == tfid) {
                panels.removeAt(i);
                break;
            }
        }

        elem = dojo.byId("dojoUnique" + tfid);
        dojo._destroyElement(elem);

        gravitation();

        updatePanels();

        adjustContentArea();

        savePanelsState();
    }
}

function showMouseHolder(hide) {
    if (panels) {
        var panel;

        for (var i = 0; i < panels.count; ++i) {
            panel = panels.item(i);
            if (panel.tfid) {
                var mouseHolder = dojo.byId("moveMouseHolder" + panel.tfid);
                if (mouseHolder) {
                    if (hide !== false) dojo.style(mouseHolder, "display", "block");
                    else dojo.style(mouseHolder, "display", "none");
                }
            }
        }
    }

    return null;
}

function getContentHeight() {
    var i;

    for (i = 0; i < _map[0].length; ++i) {
        if (_map[0][i] == 0 && _map[1][i] == 0) {
            break;
        }
    }

    return i * CH;
}

var init = function() {

    var area = dojo.byId('contentarea');

    if (area == null) return;

    dojo.require("dojo.dnd.move");
    dojo.require("dojox.collections.ArrayList");
    dojo.require("dojox.image.Lightbox");
    dojo.require("dojo.cookie");

    dojo.subscribe("/dnd/move/start", onDndStart);
    dojo.subscribe("/dnd/move/stop", onDndDrop);

    panels = new dojox.collections.ArrayList();

    _map = new Array();
    _map[0] = new Array();
    _map[1] = new Array();

    for (var j = 0; j < MAXVERT; ++j) {
        _map[0][j] = 0;
        _map[1][j] = 0;
    }

    loadPanelsState();

    document.body.onmouseout = onMouseOut;
    window.onunload = hideLeaveDialog;
    window.onbeforeunload = showLeaveDialog;
};

function isLogin() {
    if (typeof _userLogin == "boolean") return _userLogin;
    return false;
}

function isPaid() {
    if (typeof _userPaid == "boolean") return _userPaid;
    return false;
}

function PanelT(tfid, type, title, contentId, left, top) {
    this.tfid = tfid;
    this.type = type;
    this.title = title;
    this.left = left;
    this.top = top;
    this.contentId = contentId;
}

var panels, source, _allowActionDialog = null, _upgradeDialog = null, _later = false;
var next_tfid = 1, current_tfid = -1;
var VS = 10, // Vertical space between panels
    CW = 278, // CELL WIDTH
    CH = 50 + VS;  // CELL HEIGHT
var cList = null;
var _map;
var MAX_PANELS_CNT = 20;
var MAXVERT = 500;
var factor = 50; // px

dojo.addOnLoad(init);

function showHistory(filename,folder) {
    var contentarea = dojo.byId('textContentBox');
    var historyarea = dojo.byId('historyarea');
    var historyIframe = dojo.byId('historyIframe');
    var rightIframe = dojo.byId('rightColumn');

    contentarea.style.display = 'none';
    rightIframe.style.display = 'none';
    historyarea.style.display = 'block';

    var newUrl;

    if(folder) {
	newUrl = folder + "/" + filename;
    } else {
	
	if(!isPaid())
	{
		newUrl =  _syndicatedFolder + '/' + filename;
	} else
	{
		newUrl =  _syndicatedFolder + '/' + filename;
	}
    }
    if (newUrl != historyIframe.src) {
        historyIframe.src = newUrl;
    }
}

function showPanels() {
    var contentarea = dojo.byId('textContentBox');
    var historyarea = dojo.byId('historyarea');
    var historyIframe = dojo.byId('historyIframe');
    var rightIframe = dojo.byId('rightColumn');

    historyarea.style.display = 'none';
    contentarea.style.display = 'block';
    rightIframe.style.display = 'block';
}

