function debug(w) {
//     return;

    if (typeof console != 'undefined') {
        var date = new Date();
        var dateStr = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + '.' + date.getMilliseconds();
        console.log(dateStr + ': ' + w);
    }
}

$.fn.id = function() {
    var id = this.attr('id');
    return id ? id.substr(1) : '';
};

$.extend({ handle: function(type, selector, fn) {
    return $.fn.live.apply({ selector:selector }, [type, fn]);
}});

$.fn.extend({ highlight: function(level) {
    var el = $(this);
    while (level--) {
        el = el.parent()
    }
    return el.effect("highlight", {}, 1000)
}});


// main namespace
fb = {
    fn: {},
    _messages: [],

    init: function() {
        $.each(this._messages,function(i, msg){
//             debug(msg);
            $.jGrowl(msg, { life: 3000 });
        });
    },

    message: function(msg, options) {
        $.jGrowl(msg, $.extend({ life: 3000 }, options));
    },

    reload: function() {
        $.blockUI();
        window.location.reload();
    },

    follow: function(link) {
        fb.goto($(link).attr('href'));
        return false;
    },

    goto: function(href) {
        $.blockUI();
        window.location = href;
    },

    ajax: function(url, params, options) {
        options = $.extend({
                    'blockMsg': 'Prosím čekejte, požadavek se vyřizuje...',
                    'redirectOkUrl': null
                    }, options);

        $.blockUI({ message: options.blockMsg });

        $.post(url, params, function(data){
            if (data.result == 'ok') {
                if (options.redirectOkUrl) {
                    fb.goto(options.redirectOkUrl);
                } else {
                    fb.message(data.message);
                }
            } else {
                debug("error: " + data.error);
                fb.message(data.message ||
                    ('Při zpracování požadavku došlo k chybě (' + data.error + ')<br/><br/>' +
                     'Kontaktujte nás prosím prostřednictvím naší <a href="/kontakt">hotline</a> - postaráme se, aby chyba byla co nejdříve odstraněna.'),
                    { sticky: true }
                    );
            }
            $.unblockUI();
        }, 'json');
    }
}

fb.observers = {
    observers: [],

    register: function(subject, msg) {
        if (!this.observers[subject]) {
            this.observers[subject]= [];
        }
        if (!this.observers[subject][msg]) {
            this.observers[subject][msg]= [];
        }
    },

    subscribe: function(handler, subject, msg, args) {
        debug('fb.observers.subscribe: subject = ' + subject + ', msg = ' + msg);
        this.register(subject, msg);
        this.observers[subject][msg].push({ handler: handler, args: args });
    },

    emit: function(subject, msg, args) {
        debug('fb.observers.emit: subject = ' + subject + ', msg = ' + msg);
        $.each(this.observers[subject][msg], function(){
            var handler = this.handler;
            if (this.args) {
                $.each(this.args, function(arg) {
                    if (args[arg] == this) {
                        handler(msg, args);
                        debug('fb.observers.emit: call - matched args');
                    }
                })
            } else {
                debug('fb.observers.emit: call - no args');
                handler(msg, args);
            }
        });
    }
}

fb.search = {
    linkPointer: null,
    validator: null,

    init: function() {
        this.linkPointer = $('#search-query .pointer');
        this.moveTo($('#search-form input[name="searchType"]:checked').closest('li'));
        $('#search-form ul li a').click(this.selectLink);
        this.validator = $('#searchForm').validate({
            rules: {
                'query': {
                    required: true,
                    minlength: 3,
                    message: 'Zadejte alespoň znaky pro vyhledávání'
                }
            }
        });
/*
        $('#search-form').submit(function(){
            fb.images.container.addClass('loading');
        });
*/

    },

    selectLink: function() {
        var el = $(this).closest('li');
        fb.search.moveTo(el);
    },

    moveTo: function(el) {
        var moveTo = el.width() / 2 + el.position().left - 6.5; // pointer width / 2
        fb.search.linkPointer.animate({ marginLeft: moveTo }, 250);
    }
}

fb.topbar = {
    loaded: false,
    container: null,
    childTimer: null,
    loginValidator: null,

    init: function() {
        fb.observers.subscribe(this._updateBasket, 'basket', 'add');
        fb.observers.subscribe(this._updateBasket, 'basket', 'remove');
        fb.observers.subscribe(this._updateBasket, 'basket', 'reset');

        $('#usertools li .child').closest('li').hover(this.showChild, this.hideChild)
                                               .find(':input').focus(function(){fb.topbar.childFocus = true})
                                                              .blur(function(){fb.topbar.childFocus = false; fb.topbar.hideChild()})
        ;
        this.loginValidator = $('#loginForm').validate({
            rules: {
                'username': {
                    required: true
                },
                'password': {
                    required: true
                }
            }
        });
    },

    _updateBasket: function(msg, args) {
        debug('fb.topbar._updateBasket: msg = ' + msg);
        var cntEl = $('#basket-link span');
        var cnt = parseInt(cntEl.text());

        var htmlMsg;
        if ('add' == msg) {
            cnt++;
            htmlMsg = '<img src="http://img.fotobanka.cz/preview/small/' + args.id + '.jpg"/>' +
                      '<p>Fotografie byla přidána do košíku.</p>' +
                      '<p><a href="/basket.php">Přejít do košíku</a></p>'
                      ;
        } else if ('remove' == msg) {
            cnt--;
        } else if ('reset' == msg) {
            cnt = 0;
            htmlMsg = 'Košák byl vyprázdněn.';
        }
        cntEl.text(cnt);
        if (htmlMsg) {
            $.jGrowl(htmlMsg, { life: 3000 });
        }
    },

    showChild: function() {
        var child = $(this).find('.child');
//         child.fadeIn('fast');
        $('#usertools li .child').hide();
        child.show();
//         fb.topbar.childTimer = null;
        if (fb.topbar.childTimer) {
            clearInterval(fb.topbar.childTimer);
        }

    },

    hideChild: function() {
        debug(fb.topbar.childFocus);
        if (fb.topbar.childFocus) {
            return;
        }
        var child = $(this).find('.child');
        fb.topbar.childTimer = setTimeout(function() {
//             child.fadeOut('fast');
            child.hide();
        }, 750);
    }
}

$().ready(function () {

    $.blockUI.defaults.message = null;
    // clear out plugin default styling
    $.blockUI.defaults.overlayCSS = {};
    $.blockUI.defaults.css = {};
    // enable transparent overlay on FF/Linux
    $.blockUI.defaults.applyPlatformOpacityRules = false;

    $.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var check = false;
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
    );
    $.validator.setDefaults({
//         debug: true,
        submitHandler: function(form) {
            $.blockUI();
            form.submit();
        }
    });

    fb.init();
    fb.topbar.init();
    fb.search.init();

//     return;
    var el = $('#sidecontent');
    var container = $('#side.grid_3');
    if (el && container) {
        container.height(container.parent().height());

         debug(container.height() + ' > ' + (el.height() + 20));
        if (container.height() > (el.height() + 20)) {
            var top = container.offset().top;
            var bottom = top + container.height();
            var state = 'top';

            var fn = function() {
    //             debug('fn');
                var scrollTop = $(window).scrollTop();
                var height = el.height();
        //         debug('scroll: scrollTop = ' + scrollTop + ', wh = ' + wh + ', top = ' + top + ', bottom = ' + bottom + ', el.offset().top = ' + el.offset().top);

                if ((Math.ceil(el.offset().top) + height) > bottom) {
                    if ('bottom' != state) {
                        el.attr('style', 'position:absolute;bottom:0px');
                        state = 'bottom';
                    }
                } else if (scrollTop > top) {
                    if ('fixed' != state && (scrollTop + height) < bottom) {
                        el.attr('style', 'position:fixed;top:0');
                        state = 'fixed';
                    }
                } else {
                    if ('top' != state) {
                        el.attr('style', 'position:static');
                        state = 'top';
                    }
                }
            }

            $(window).scroll(fn)
                    .resize(fn);
        }
    }

    $('.page a').aToolTip();
//     $('div').aToolTip();

    if ($.browser.msie) {
        $('input:radio').click(function () {
            this.blur();
            this.focus();
        });
    }

    if (jQuery.isFunction($().tinymce)) {
        $('textarea.tinymce').tinymce({
            script_url : '/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
            theme : "advanced",
            plugins :
                "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,inlinepopups,insertdatetime,preview,media,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

            // Theme options
            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,

            // Office example CSS
            content_css : "/styles/editor.css",

            convert_urls : false
        });
    }

    $("a[rel]").overlay({
        mask: 'darkred',
        effect: 'apple',
        onBeforeLoad: function() {
            var wrap = this.getOverlay().find(".contentWrap");
            wrap.load(this.getTrigger().attr("href"));
        }

    });
});
