var core;
var Q = jQuery.noConflict();
Q(document).ready(function () {load();});
var tipTimeout = 0;
var uploadingFile = false;
var uploadingNoticed = false;

function load() {

    lang = {
        intl: new i18n(i18nDict),
        transl: function (str) {
            return this.intl.transl(str);
        }
    }

    core = {
        root_url: cms_basename,
        dialog: false,
        messageShow: false,
        lightboxClasses: ".lightbox, .fancybox",
        dontInterrupt: ".dontInterrupt",

        preventUploadInterrupt: function () {
            Q("a").not(core.lightboxClasses).not(core.dontInterrupt).click(function(e) {
                if (uploadingFile) {
                    uploadingNoticed = true;
                    if (!confirm(lang.transl("WINDOW_CLOSING_UPLOAD"))) {
                        e.preventDefault();
                        return false;
                    }
                }
                return true;
            });

            Q(window).bind("beforeunload", function() {
                if (uploadingFile && !uploadingNoticed) {
                    alert(lang.transl("WINDOW_CLOSING"));
                }
                return true;
            });
        },

        getBasename: function () {
            var url = core.root_url;
            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;
            core.messageShow = true;
            tipTimeout = setTimeout('core.hideMessage()', 8000);
        },

        hideMessage: function(){
            if (document.getElementById('loadingDiv')) {
                document.getElementById('loadingDiv').style.visibility = 'hidden';
                document.getElementById('loadingDiv').innerHTML = lang.transl("LOADINGDIV");
            }
            core.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) {
            if (!url) return false;
            Q('#loadingDiv').show();
            Q('#loadingDiv').css('visibility', 'visible');
            
            url = url.replace(cms_basename + '/', "");
            url = cms_basename + url;
            
            Q.ajax({
                type: "POST",
                url: url,
                data: params,
                success: function(msg) {
                    if (msg == 'x-prihlaseni-user') {window.location.href = cms_basename;return false;}
                    if (!core.checkResponse(msg)) {
                        Q('#loadingDiv').css('visibility', 'hidden');
                        Q('#loadingDiv').hide();
                        return false;
                    }
                    
                    successFunction(msg);

                    if (!core.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-detail')) {width = 530;height = 600;}
            if (Q('#dialog').hasClass('lightbox-narrow-detail')) {width = 530; height = 300;}
            
            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();
            core.preparePage();
            
            loadToolTip('#dialog');
            reload();
            core.hideMessage();
        },

        hideDialog: function() {
            this.dialog.dialog('close');
        },
        
        showSiteMsg: function(message, type) {
            Q('#sitemsgplace').html('<div id="siteMsg"><p><span class="title">'+message+'</span><span class="message"></span></p></div>');
            Q('#sitemsgplace').removeClass('x');
            Q("#siteMsg").effect("pulsate", {times:1}, 2500);
            if (type == 'error') Q("#siteMsg").css('background', '#D02820');
            else Q("#siteMsg").css('background', '#0ebceb');
        },
        
        initLightbox: function(anchors) {
            Q(anchors).click(function(e) {
                
                e.preventDefault();
                alert('dd');return;
                var anchor = Q(this);
                var url = Q(this).attr('href');
                var params = '';
                core.loadAjax(url, params, function(msg) {
                    if (anchor.hasClass('showButtonsDialog'))
                        core.showDialog(msg, true);
                    else
                        core.showDialog(msg, false);
                });
                
                core.hideMessage();
                return false;
            });
        },

        wait: function() {
            if (countdown > 0) {
                Q('#countdownspan').html('<strong>' + countdown + '</strong>');
                countdown -= 1;
                setTimeout('core.wait()', 1000);
            }
            else {
                Q('#countdownspan').html('<strong>' + countdown + '</strong>');
                setTimeout('core.setHomeLocation()', 0);
            }
        },

        setHomeLocation: function() {window.location = cms_basename;},

        preparePage: function() {
            Q('.enterpressed').keypress(function(event) {if (event.keyCode==13) {Q(this).parents('form').submit();}});
            Q('.newWindow').click(function() {return !new_window(this.href);});
            Q('.external').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");});
            
        },

        scrollBit: function() {
            window.scrollBy(0,5);
        },
        scrollBitBack: function() {
            window.scrollBy(0,-5);
        },
        redirect: function(href) {
            window.location.href = href;
        }
    }

    core.initDialog();
    core.initLightbox(core.lightboxClasses);
    core.preparePage();
    loadCoreFunctions();
    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;
    }
}
 
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;
    core.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');
}

function confirmDel(href, confirm_text, submit_text, cancel_text) {
    Q('#thickBox .in').html(confirm_text);
    Q('#thickBox .cancel').val(cancel_text);
    Q('#thickBox .submit').val(submit_text);
    Q("#thickBox").show();

    Q("#thickBox .cancel").click(function () {Q("#thickBox").css('display', 'none');core.scrollBit();core.scrollBitBack();return false;});
    Q("#thickBox .submit").click(function () {Q("#thickBox").css('display', 'none');core.redirect(href);return false;});
    return false;
}

function showDialog(msg, buttons) {
    core.showDialog(msg, buttons);
    reload();
}

function reload() {
    Q('.reload_lightbox').click(function(ev) {
        ev.preventDefault();
        var url = Q(this).attr('href');

        core.dialog.dialog("close");
        core.loadAjax(url, '', function(req) {
            showDialog(req);
            return true;
        });
    });
}

