var edisk;
var Q = jQuery.noConflict();
Q(document).ready(function () {load();});
var tipTimeout = 0;
var profi = false;
var admin = false;

function load() {
    
    lang = {
        intl: new i18n(i18nDict),
        transl: function (str) {
            return this.intl.transl(str);
        }
    }

    edisk = {
        root_url: ed_basename,
        dialog: false,
        messageShow: false,

        getBasename: function () {
            var url = edisk.root_url;
            if (locale) url += '/' + locale;
            return url;
        },

        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');
            
            url = url.replace(ed_basename + '/', "");
            if (admin)
                url = ed_basename + '/aadmin.php?action=' + url;
            else if (profi)
                url = ed_basename + '/' + url;
            else
                url = ed_basename + '/' + locale + '/' + url;
            //alert(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('.flash').hide();
            Q('#dialog_obal').html(msg);
            var width = 700;
            var height = 300;

            if (Q('#dialog').hasClass('lightbox-profi-podminky')) {width = 710;height = 300;}
            if (Q('#dialog').hasClass('lightbox-profi-login')) {width = 320;height = 235;}
            if (Q('#dialog').hasClass('lightbox-profi-middle')) {width = 520;height = 250;}
            if (Q('#dialog').hasClass('lightbox-profi-middlehigh')) {width = 520;height = 380;}
            if (Q('#dialog').hasClass('lightbox-profi-links')) {width = 490;height = 405;}
            if (Q('#dialog').hasClass('lightbox-profi-preview')) {width = 490;height = 405;}
            // nahraj classes
            if (Q('#dialog').hasClass('lightbox-add-folder')) {width = 280;height = 150;}
            if (Q('#dialog').hasClass('lightbox-podminky')) {width = 710;height = 340;}
            if (Q('#dialog').hasClass('lightbox-podminky-long')) {width = 710;height = 355;}
            if (Q('#dialog').hasClass('lightbox-login')) {width = 320;height = 265;}
            if (Q('#dialog').hasClass('lightbox-send')) {width = 310;height = 170;}
            if (Q('#dialog').hasClass('lightbox-sms-quick')) {width = 420;height = 470;}
            if (Q('#dialog').hasClass('lightbox-sms')) {width = 420;height = 380;}
            if (Q('#dialog').hasClass('lightbox-bank')) {width = 420;height = 430;}
            if (Q('#dialog').hasClass('lightbox-banksk')) {width = 420;height = 470;}
            if (Q('#dialog').hasClass('lightbox-bankpl')) {width = 420;height = 450;}
            if (Q('#dialog').hasClass('lightbox-links')) {width = 505;height = 370;}
            if (Q('#dialog').hasClass('lightbox-move')) {width = 555;height = 370;}
            if (Q('#dialog').hasClass('lightbox-rename')) {width = 375;height = 370;}
            if (Q('#dialog').hasClass('lightbox-links-folder')) {width = 505;height = 480;}
            if (Q('#dialog').hasClass('lightbox-bonus')) {width = 450;height = 430;}
            if (Q('#dialog').hasClass('lightbox-premium')) {width = 685;height = 225;}
            if (Q('#dialog').hasClass('lightbox-premium-no-conn')) {width = 685;height = 310;}
            if (Q('#dialog').hasClass('lightbox-premium-login')) {width = 685;height = 185;}
            if (Q('#dialog').hasClass('lightbox-premium-login-no-conn')) {width = 685;height = 270;}
            if (Q('#dialog').hasClass('lightbox-premium-twocolumn')) {width = 685;height = 200;}
            if (Q('#dialog').hasClass('lightbox-premium-twocolumn-noconn')) {width = 685;height = 285;}

            if (Q('#dialog').hasClass('lightbox-credit-options')) {width = 735;height = 265;}
            if (Q('#dialog').hasClass('lightbox-credit-options-sms')) {width = 735;height = 265;}
            if (Q('#dialog').hasClass('lightbox-credit-options-paypal')) {width = 735;height = 265;}
            if (Q('#dialog').hasClass('lightbox-bank-doklad')) {width = 790;height = 430;}
            if (Q('#dialog').hasClass('lightbox-bank-dokladsk')) {width = 790;height = 470;}
            if (Q('#dialog').hasClass('lightbox-bank-dokladpl')) {width = 790;height = 450;}
            if (Q('#dialog').hasClass('lightbox-admin-user')) {width = 490;height = 370;}

            Q('#dialog').attr('class', '');

            if (buttons)
                this.dialog.dialog({
                    open: function() {},
                    beforeclose: function() {Q('.flash').show();},
                    close: function() {},
                        bgiframe: true,
                        modal: false,
                        width: width,
                        height: height,
                        resizable: false,
                        buttons: {'Ok': function() {}}
                });
            else
                this.dialog.dialog({
                    open: function() {},
                    beforeclose: function() {Q('.flash').show();},
                    close: function() {},
                        bgiframe: true,
                        modal: false,
                        width: width,
                        height: height,
                        resizable: false,
                        buttons: false
                });
            
            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();
            edisk.preparePage();
            
            loadToolTip('#dialog');
            reload();
            edisk.hideMessage();
        },

        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;},

        preparePage: function() {
            Q('.enterpressed').keypress(function(event) {if (event.keyCode==13) {document.forms.loginForm.submit();}});
            Q('.new_window').click(function() {return !new_window(this.href);});
            Q('.searchField').click(function() {if (this.value == lang.transl("SEARCH_FIELD")) this.value = '';});
            Q('.searchField').blur(function() {if (this.value == '') this.value = lang.transl("SEARCH_FIELD");});
        }
    }

    edisk.initDialog();
    edisk.initLightbox(".thickbox, .thickbox3, .lightbox, .thickboxmultiupload");
    edisk.preparePage();
    loadSubSpecifics();
}

function new_window(url) {
    wasOpen  = false;
    win = window.open(url);
    return (typeof(win)=='object')?true:false;
}

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';
            }
        }
    }
}

jQuery.fn.outerHTML = function() {
    return Q('<div>').append( this.eq(0).clone() ).html();
};

function loadToolTip(anchor) {

   Q(anchor + ' .tooltip').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " :: ",
        extraClass: "pretty",
        fixPNG: true,
        opacity: '0.95',
        left: -90
    });
    
    if (anchor == '#dialog') {
        Q('#dialog').removeAttr('title');
    }
    
}

function loadMoreFiles(type, start, get_files, per_row) {
    var url = 'x-load-files';
    if (start < 0) start = 0;
    var params = 'type='+type+'&start='+start+'&get_files='+get_files+'&per_row='+per_row;
    edisk.loadAjax(url, params, function(msg) {
        Q("#tab-"+type+"-div").html(msg);
        loadSlideshow("#tab-"+type+"-div");
        return true;
    });
    return false;
}

function loadSlideshow(div) {
    Q(div+' .slideshow').each(function() {
        Q(this).children("img:first").fadeIn(2000, function() {

        });
        Q(this).cycle({
            fx:      'fade',
            speed:   1500,
            timeout: 2000
        });
    });

    Q(div+' .slideshow').hover(
            function() {
                var item = Q(this).children('img:first');
                if (item.hasClass('noicon')) return;
                var src = item.attr('src');
                src = src.substr(0, src.length - 5);
                var fileid = item.attr('id');
                fileid = fileid.substr(0, fileid.length - 2);
                var imageCount = Q('#image_count_'+fileid).val();
                Q(this).cycle('destroy');
                for (var i = 5; i <= imageCount; i++)
                {
                    Q(this).append('<img src="'+src+i+'.jpg" id="'+fileid+'_'+i+'" alt="preview" class="x"/>')
                }

                Q(this).cycle({
                    fx:     'fade',
                    speed:   200,
                    timeout: 300,
                    pause:   0
                });
            },
            function(){
                Q(this).cycle({
                    fx:      'fade',
                    speed:   1500,
                    timeout: 500,
                    pause:   0
                });
            }
    ).trigger('hover');
}
