var edisk;
var Q = jQuery.noConflict();
Q(document).ready(function () {load();});

function load() {

    lang = {
        intl: new i18n(i18nDict),
        transl: function (str) {
            return this.intl.transl(str);
        }
    }

    edisk = {
        root_url: ed_basename,
        dialog: false,
        messageShow: false,
        
        reloadPage: function () {
            window.location.reload();
            window.location.href = window.location.href;
        },

        showMessage: function(msg) {
            document.getElementById('loadingDiv').style.visibility = 'visible';
            document.getElementById('loadingDiv').innerHTML = msg;
            edisk.messageShow = true;
            tipTimeout = setTimeout('edisk.hideMessage()', 8000);
        },

        hideMessage: function(){
            document.getElementById('loadingDiv').style.visibility = 'hidden';
            document.getElementById('loadingDiv').innerHTML = lang.transl("LOADINGDIV");
            edisk.messageShow = false;
            clearTimeout(tipTimeout);
        },

        checkResponse: function (msg) {
            if (msg == 'false') {
                alert(lang.transl("AUTH_ERROR"));
                window.location.href = '/';
                return false;
            }
            if (msg == '') return false;
            return true;
        },

        loadAjax: function(url, params, successFunction) {
            Q('#loadingDiv').show();
            Q('#loadingDiv').css('visibility', 'visible');
            //alert(url);
            url = ed_basename + '/' + url;
            
            Q.ajax({
                type: "POST",
                url: url,
                data: params,
                success: function(msg) {
                    if (msg == 'x-prihlaseni-user') {window.location.href = ed_basename; return false;}
                    if (!edisk.checkResponse(msg)) {
                        Q('#loadingDiv').css('visibility', 'hidden');
                        Q('#loadingDiv').hide();
                        return false;
                    }
                    successFunction(msg);
                    if (!edisk.messageShow) {
                        Q('#loadingDiv').css('visibility', 'hidden');
                        Q('#loadingDiv').hide();
                    }
                    return true;
                }
            });
            return false;
        },

        initDialog: function() {
            this.dialog = Q("#dialog_obal");
            this.dialog.dialog({
                open: function() {},
                beforeclose: function() {
                },
                close: function() {},
                    bgiframe: true,
                    modal: false,
                    width: 700,
                    height: 300,
                    dialogClass: 'x',
                    resizable: false,
                    buttons: {}
            });
            this.dialog.dialog('close');
            window.scrollTo(0, 0);
        },

        showDialog: function(msg, buttons) {
            this.dialog.dialog('destroy');
            Q('#dialog_obal').html(msg);
            var width = 700;
            var height = 300;

            if (Q('#dialog').hasClass('lightbox-podminky')) {width = 710;height = 300;}
            if (Q('#dialog').hasClass('lightbox-login')) {width = 320;height = 235;}
            if (Q('#dialog').hasClass('lightbox-middle')) {width = 520;height = 250;}
            if (Q('#dialog').hasClass('lightbox-middlehigh')) {width = 520;height = 380;}
            if (Q('#dialog').hasClass('lightbox-links')) {width = 490;height = 405;}
            if (Q('#dialog').hasClass('lightbox-preview')) {width = 490;height = 405;}
            Q('#dialog').attr('class', '');

            if (buttons)
                this.dialog.dialog({
                    open: function() {},
                    beforeclose: function() {},
                    close: function() {},
                        bgiframe: true,
                        modal: false,
                        width: width,
                        height: height,
                        resizable: false,
                        buttons: {'Ok': function() {}}
                });
            else
                this.dialog.dialog({
                    open: function() {},
                    beforeclose: function() {},
                    close: function() {},
                        bgiframe: true,
                        modal: false,
                        width: width,
                        height: height,
                        resizable: false,
                        buttons: false
                });
            Q('.enterpressed').keypress(function(event) {if (event.keyCode==13) {document.forms.loginForm.submit();}});
            this.dialog.dialog('moveToTop');
            this.dialog.dialog( "option", "position", ['center', 'center']);
            this.dialog.dialog('open');
            Q('#ui-dialog-title-dialog_obal').html(Q('#dialog').attr('title'));
            Q("#dialog").attr('scrollTop', 0);
            Q("#dialog input:text:visible:first").focus();
        },

        hideDialog: function() {
            this.dialog.dialog('close');
        },

        initLightbox: function(anchors) {
            Q(anchors).click(function() {
                var anchor = Q(this);
                var url = Q(this).attr('href');
                var params = '';
                edisk.loadAjax(url, params, function(msg) {
                    if (anchor.hasClass('showButtonsDialog')) 
                        edisk.showDialog(msg, true);
                    else
                        edisk.showDialog(msg, false);
                });
                return false;
            });
            
        },

        wait: function() {
            if (countdown > 0) {
                Q('#countdownspan').html('<strong>' + countdown + '</strong>');
                countdown -= 1;
                setTimeout('edisk.wait()', 1000);
            }
            else {
                Q('#countdownspan').html('<strong>' + countdown + '</strong>');
                setTimeout('edisk.setHomeLocation()', 0);
            }
        },

        setHomeLocation: function() {window.location = ed_basename;}
    }

    edisk.initDialog();
    edisk.initLightbox(".thickbox, .thickbox3, .lightbox, .thickboxmultiupload");
    Q('#folderOptions a, #options a').click(function() {return false;})
    Q('.enterpressed').keypress(function(event) {if (event.keyCode==13) {document.forms.loginForm.submit();}});
    
    Q(".mootoolsTips").tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " :: ",
        extraClass: "pretty",
        fixPNG: true,
        opacity: 0.95,
        left: -120
    });

    Q("a.bg-button").mouseover(function(){
        this.style.color = 'black';
    }).mouseout(function(){
        this.style.color = '#fff';
    });

    Q("a").filter("#toggleTodoList").click(function() {
        if (Q("div").filter("#todoWrapper").is(":visible"))
          Q("#todoWrapper").hide("slow");
        else
          Q("#todoWrapper").show("slow");
        collapseTodoList();
    });

    Q("a").filter("#toggleContactList").click(function() {
        if (Q("div").filter("#groupWrapper").is(":visible"))
          Q("#groupWrapper").hide("slow");
        else
          Q("#groupWrapper").show("slow");
        collapseContacts();
    });

    Q("#draggable .fNameCell .item, #todoWrapper .todoItem").draggable({
	containment: 'document',
	opacity: 0.6,
	revert: 'invalid',
	helper: 'clone',
	zIndex: 100
    });
    
    loadDrop();
    if (document.getElementById('settings-vypis')) loadSettingsDrag();
}

function lateLoad() {
    edisk.initLightbox("#vypis-souboru .thickbox, .thickboxmultiupload, #footer .thickbox");
    Q('#folderOptions a, #options a').click(function() {return false;})

    Q("#vypis-souboru .mootoolsTips").tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " :: ",
        extraClass: "pretty",
        fixPNG: true,
        opacity: 0.95,
        left: -120
    });

    Q("#draggable .fNameCell .item").draggable({
	containment: 'document',
	opacity: 0.6,
	revert: 'invalid',
	helper: 'clone',
	zIndex: 100
    });
    loadDrop();
}

function loadDrop() {
    
    Q("#recyclediv").droppable({
        drop:
            function(e, ui)
            {
                var id = Q(ui.draggable).children(["a:first"]).attr('id');
                
                var subid = '';
                if (id.substr(0, 8) == 'itemhref') {
                    subid = id.substr(9);
                    deleteFile(subid);
                }
                if (id.substr(0, 11) == 'todoContent') {
                    subid = id.substr(11);
                    deleteTodoitem(subid);
                }

            }
    });

    Q("#foldersBody tr").droppable({
        drop:
            function(e, ui)
            {
                var folderid = Q(this).attr('id');
                folderid = folderid.substr(6);

                var id = Q(ui.draggable).children(["a:first"]).attr('id');
                if (id.substr(0, 8) == 'itemhref') {
                    subid = id.substr(9);
                    moveFileToFolder(subid, folderid);
                }
            }
    });

    Q("#groupWrapper tr").droppable({
        drop:
            function(e, ui)
            {
                var trid = Q(this).attr('id');
                trid = trid.substr(5);

                var id = Q(ui.draggable).children(["a:first"]).attr('id');
                if (id.substr(0, 8) == 'itemhref') {
                    subid = id.substr(9);
                    var parent = Q(this).parent([".kontakty-table:first"]).parent(["span:first"]).attr('id');
                    var params = '' ;
                    var url = '';
                    if (parent.substr(4) == '0') {
                        params += '&fileCheck[]=' + subid;
                        params += '&contactNotEdiskCheck[]=' + trid;
                        url = 'x-send-links-not-edisk-mail';
                        edisk.loadAjax(url, params, function(msg) {edisk.showMessage(msg);});
                    } else {
                        params += '&fileCheck[]=' + subid;
                        params += '&contactCheck[]=' + trid;
                        url = 'x-new-acl-entry/acc/'+sessId;
                        edisk.loadAjax(url, params, function(msg) {edisk.showMessage(msg);});
                    }
                        
                }
            }
    });

    
}

function i18n(i18n_dict) {
    this.i18nd = i18n_dict;

    this.toEntity = function (str) {
            var newstr = "";
            for (var i=0;i<str.length; i++) {
                    if (str.charCodeAt(i) > 128)
                            newstr += "&#"+str.charCodeAt(i)+";";
                    else
                            newstr += str.charAt(i);
            }
            return newstr;
    }

    this.transl = function (str, params) {
            var transl = str;
            if (this.i18nd && this.i18nd[str])
                    transl = this.i18nd[str];
            return printf(transl, params);
    }

    this.translateNodes = function () {
        var nodes = document.getElementsByTagName("*");
        for (var i=0;i<nodes.length;i++)
            if (nodes[i].className.match("i18n")) {
                var orig = stripStrML(nodes[i].innerHTML);
                var transl = this.transl(orig);

                if (transl == orig) transl = this.transl(this.toEntity(orig));
                nodes[i].innerHTML = transl;
            }
    }
}

function stripStr(str) {
	return str.replace(/^\s*/, "").replace(/\s*$/, "");
}

// Multiline strip
function stripStrML(str) {
    // Split because m flag doesn't exist before JS1.5 and we need to
    // strip newlines anyway
    var parts = str.split('\n');
    for (var i=0; i<parts.length; i++)
            parts[i] = stripStr(parts[i]);

    // Don't join with empty strings, because it "concats" words
    // And strip again
    return stripStr(parts.join(" "));
}

function printf(S, L) {
    if (!L) return S;

    var nS = "";
    var tS = S.split("%s");

    for(var i=0; i<L.length; i++) {
        if (tS[i].lastIndexOf('%') == tS[i].length-1 && i != L.length-1)
            tS[i] += "s"+tS.splice(i+1,1)[0];
        nS += tS[i] + L[i];
    }
    return nS + tS[tS.length-1];
}


function onRow(row){
    row.className = 'hlRow';
}

function offRow(id, cls){
    var row = document.getElementById('row'+id);
    if ( document.getElementById('check_'+id) && document.getElementById('check_'+id).checked ){
        row.className = 'selRow';
    } else {
        row.className = cls;
    }
}

function offRowFolders(id, cls){
    var folder = document.getElementById('folder'+id);
    if ( document.getElementById('checkfolder_'+id).checked ){
        folder.className = 'selRow';
    } else {
        folder.className = cls;
    }
}

function offSearchRow(id, cls){
    row = document.getElementById('row'+id);
    row.className = cls;
}

function checkAll(){
    var check = false;
    if ( document.getElementById('fCheckCtrl').checked){
        check = true;
    } else {
        check = false;
    }
    var cbA = document.getElementsByName('fileCheck[]');
    for (var i = 0; i < cbA.length; i++){
        cbA[i].checked = check;
        if (check){
            document.getElementById('row'+cbA[i].value).className = 'selRow';
        } else {
            if ( (i % 2) == 0 ){
                document.getElementById('row'+cbA[i].value).className = 'light';
            } else {
                document.getElementById('row'+cbA[i].value).className = 'dark';
            }
        }
    }
}

function checkAllMail(){
    if ( document.getElementById('fCheckCtrl').checked ){
        check = true;
    } else {
        check = false;
    }
    var cbA = document.getElementsByName('mailCheck[]');
    for (var i = 0; i < cbA.length; i++){
        cbA[i].checked = check;
        if (check){
            document.getElementById('row'+cbA[i].value).className = 'selRow';
        } else {
            if ( (i % 2) == 0 ){
                document.getElementById('row'+cbA[i].value).className = 'light';
            } else {
                document.getElementById('row'+cbA[i].value).className = 'dark';
            }
        }
    }
}