$(function() {
    maminka.init();
});

var maminka = {

    init: function() {
        // add require mark to form
        maminka.requiredMark();

        // righBoxy
        this.hoverRightBox();

        // hover FB button
        this.becomeFans();

        // hover all buttons
        this.buttonHover();

        // hover main menu
        this.mainMenuHover();

        // login box butttons hover
        this.loginButtonHover();

        // service box controller
        this.serviceBoxControler();
        
        // datePicker
        this.datePicker();

        // printing list
        this.printList();

        // show horoscope detail
        this.horoscope_detail();
        
        // advisory hidding form
        this.advisoryFakeForm();

        // baby name hover efects for IE 6
        this.babyNameHove();

        // IFRAME FIX
        this.iframeFix();
    },

    datePicker: function() {

        $(".datepicker").datepicker({
            showOn: 'button',
            buttonImage: '/img/skins/default/ico/small_cal.png',
            buttonImageOnly: true,
            changeMonth: true,
            changeYear: true,
            firstDay: 1,
            minDate: '-90y',
            maxDate: '+0d',
            yearRange: '-90:+90'
        });
    },

    requiredMark: function() {
        $("label.required").prepend("<span>*&nbsp;</span>");
    },
    
    hoverRightBox: function() {
        $(".right_box h3 img").each(function() {

            var img_src = $(this).attr("src").split('.');
            jQuery("<img>").attr("src", img_src[0] + "_on." + img_src[1]);

            $(this).mouseover(function() {
                var img_src = $(this).attr("src").split('.');
                $(this).attr("src", img_src[0] + "_on." + img_src[1]);
            });

            $(this).mouseout(function() {
                var img_src = $(this).attr("src").split('_on.');
                $(this).attr("src",img_src[0] + "." + img_src[1]);
            });
        });
    },
    
    becomeFans: function() {
        $("#become_fans img").each(function() {
            $(this).mouseover(function() {
                var img_src = $(this).attr("src").split('.');
                $(this).attr("src", img_src[0] + "_on." + img_src[1]);
            });
            $(this).mouseout(function() {
                var img_src = $(this).attr("src").split('_on.');
                $(this).attr("src",img_src[0] + "." + img_src[1]);
            });
        });
    },
    
    buttonHover: function() {
        $("div.button_case").each(function() {
            $(this).mouseover(function() {
                $(this).addClass("hover");
            });
            $(this).mouseout(function() {
                $(this).removeClass("hover");
            });
        });
    },
    
    mainMenuHover: function() {
        $("ul#main_menu li.main_menu").each(function() {
            var active = false;
            $(this).mouseover(function() {
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");
                    active = true;
                }
                $(this).addClass("hover");
                $("li#"+$(this).attr("id")+" ul.sub_menu").css("display","block");
            });
            $(this).mouseout(function() {
                if(active == true) {
                    $(this).addClass("active");
                    active = false;
                }
                $(this).removeClass("hover");
                $("li#"+$(this).attr("id")+" ul.sub_menu").css("display","none");
            });
        });
    },
    loginButtonHover: function() {
        $("#short_buttons img").each(function() {
            $(this).mouseover(function() {
                var img_src = $(this).attr("src").split('.');
                $(this).attr("src",img_src[0] + "_on." + img_src[1]);
            });
            $(this).mouseout(function() {
                var img_src = $(this).attr("src").split('_on.');
                $(this).attr("src",img_src[0] + "." + img_src[1]);
            });
        });
    },
    serviceBoxControler: function() {
        $("#box_social_left ul li").css("display","none");
        $("#box_social_left ul li:first").css("display","block");
        $("#box_social_right ul li").css("display","none");
        $("#box_social_right ul li:first").css("display","block");

        $("#box_social_left ul").mouseover(function() {
            $("#box_social_left ul li").css("display","block");
        });
        $("#box_social_left ul").mouseout(function() {
            $("#box_social_left ul li").css("display","none");
            $("#box_social_left ul li:first").css("display","block");
        });
        $("#box_social_right ul").mouseover(function() {
            $("#box_social_right ul li").css("display","block");
        });
        $("#box_social_right ul").mouseout(function() {
            $("#box_social_right ul li").css("display","none");
            $("#box_social_right ul li:first").css("display","block");
        });
    },
    printList: function() {

        $("ul#print_sel li").css("display","none");
        $("ul#print_sel li:first").css("display","list-item");

        $("ul#print_sel li").mouseover(function() {
            $("ul#print_sel li").css("display","list-item");
        });
        $("ul#print_sel").mouseout(function() {
            $("ul#print_sel li").css("display","none");
            $("ul#print_sel li:first").css("display","list-item");
        });
    },
    horoscope_detail: function() {
        $("#show_horo").click( function (){
            $("#horoscope_text").animate( {height:"20em"}, 1500 );
            $("#show_horo").css("display","none");
        });
    },
    advisoryFakeForm: function() {
        //$("#list-comment-fulltext-add").hide();
        $("div#fake_form").html("<table><tr><td class=\"td_left\"> Dotaz </td><td><textarea rows=\"1\" cols=\"99\">Vložte dotaz</textarea></td></tr></table>");
        $("div#fake_form table tr td textarea").click( function (){
            $("div#fake_form").css("display","none");
            listCommentControl.fulltextSearch();
            $("textarea#frmaddForm-content").focus();
            $("textarea#frmaddForm-content").setCursorPosition(1);

        });
    },
    babyNameHove: function() {
        $("table.babyname-alphabet-filter td").each(function() {
            $(this).mouseover(function() {
                $(this).addClass('hover');
            });
            $(this).mouseout(function() {
                $(this).removeClass('hover');
            });
        });
    },
    iframeFix: function() {
        $("iframe").each( function() {
            $("iframe body").attr("style","background:red");
        });
    }
}


/* -------------------------------------------------------------------------- */
/* -------------------------- lightBox -------------------------------------- */
/* -------------------------------------------------------------------------- */

var lightBox = {
    active: false,
    dialogObj: false,
    handleScroll: true,

    show: function (dialogObj, handleScroll) {
        if (this.active == true) {
            return false;
        }

        // hide select inputs in IE6
        if ($.browser.msie && $.browser.version == '6.0') {
            $("select[name!='id_type']").each(function() {
                if ($(this).is(':visible')) {
                    $(this).data('dialog_hide', true);
                    $(this).hide();
                }
            });
            $("#dialog select").each(function() {
                $(this).show();
            });
        }

        this.active = true;

        if (typeof(dialogObj) == 'object') {
            this.dialogObj = dialogObj;
        } else {
            this.dialogObj = false;
        }

        if (typeof(handleScroll) == "boolean") {
            this.handleScroll = handleScroll;
        } else {
            this.handleScroll = true;
        }

        this.resize();
        $("#overlay").show();

        $(window).resize( function() {
            lightBox.resize();
        });

        if (this.handleScroll) {
            $(document).bind("scroll", function() {
                lightBox.move();
            });
        }

        $(document).keydown( function(objEvent) {
            lightBox.keyDown(objEvent);
        });

        return false;
    },

    keyDown: function(objEvent) {
        // FIXME - test IE !!!
        if (objEvent.keyCode == 27) {
            lightBox.close();
        }
        if (objEvent.keyCode == 37 && typeof(lightBox.dialogObj.navigateLeft) == 'function') {
            lightBox.dialogObj.navigateLeft();
        }
        if (objEvent.keyCode == 39 && typeof(lightBox.dialogObj.navigateRight) == 'function') {
            lightBox.dialogObj.navigateRight();
        }
    },

    resize: function() {
        $("#overlay").width( $(document).width() );
        $("#overlay").height( $(document).height() );

        this.move();
    },

    move: function () {
        if (typeof(this.dialogObj) != 'object') {
            return;
        }

        var dialogLeft = Math.round($(window).width() / 2) - ($(this.dialogObj.lightBoxIdObj).width() / 2);
        var dialogTop = Math.round($(window).height() / 2) - ($(this.dialogObj.lightBoxIdObj).height() / 2);

        if (dialogLeft < 0 ) {
            dialogLeft = 5;
        }
        if (dialogTop < 0) {
            dialogTop = 5;
        }

        dialogTop += $(document).scrollTop();

        $(this.dialogObj.lightBoxIdObj).css({
            left: dialogLeft + "px",
            top:  dialogTop + "px"
        });
    },

    close: function () {
        if (this.active) {
            this.active = false;

            // show hiden select inputs in IE6
            if ($.browser.msie && $.browser.version == '6.0') {
                $('select').each(function() {
                    if ($(this).data('dialog_hide') == true) {
                        $(this).data('dialog_hide', false);
                        $(this).show();
                    }
                });
            }

            if (typeof(this.dialogObj.close) == 'function') {
                this.dialogObj.close();
            }

            $("#overlay").hide();

            $(window).unbind("resize");
            $(document).unbind("keydown");
            $(document).unbind("scroll");
        }
        this.dialogObj = false;

        return false;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------- dialog ---------------------------------------- */
/* -------------------------------------------------------------------------- */

var dialog = {
    width: 400,
    height: 250,
    active: false,
    lightBoxIdObj: '#dialog',

    show: function(width, height) {
        if (typeof(width) != 'undefined') {
            this.width = width;
        }
        if (typeof(height) != 'undefined') {
            this.height = height;
        }

        this.active = true;

        $(this.lightBoxIdObj).width(this.width);
        $(this.lightBoxIdObj).height(this.height);

        $(this.lightBoxIdObj).show();

        var objHelp = $(".dialog_content_help", this.lightBoxIdObj);
        if (objHelp.length > 0) {
            $("#dialog_help_ico").show();
        } else {
            $("#dialog_help_ico").hide();
        }

        lightBox.show(this);
    },

    showHelp: function() {
        $("#dialog_help").html( $("#dialog .dialog_content_help").html() );
        $("#dialog_content").hide();
        $("#dialog_help").show();
    },

    hideHelp: function() {
        $("#dialog_help").hide();
        $("#dialog_content").show();
    },

    close: function() {
        if (this.active) {
            this.active = false;

            $(this.lightBoxIdObj).hide();
            lightBox.close();
        }

        return false;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------- imagePreview ---------------------------------- */
/* -------------------------------------------------------------------------- */

var imagePreview = {
    width: 835,
    height: 660,
    active: false,
    lightBoxIdObj: '#dialog_image',
    lightBoxIdContent: '#dialog_image_content',
    lightBoxIdTitle: '#dialog_image_title',

    showImage: function(filename) {

        this.active = true;

        $(this.lightBoxIdObj).width(this.width);
        $(this.lightBoxIdObj).height(this.height);

        $(this.lightBoxIdContent).html('');
        $(this.lightBoxIdContent).append(
            '<div class="img">' +
                '<img src="' + filename + '" onclick="return lightBox.close()">' +
            '</div>');

        $(this.lightBoxIdObj).show();

        return lightBox.show(this, false);
    },

    makeTitle: function(title, authorTitle, sourceTitle, carouselTitle) {
        var buf = '';
        if (typeof(title) != 'undefined') {
            buf = '<span class="image_tile">' + title + '</span>';
            if (typeof(carouselTitle) != 'undefined') {
                buf += ' [' + carouselTitle + ']';
            }
        }
        if (typeof(authorTitle) != 'undefined' || typeof(sourceTitle) != 'undefined') {
            buf += '<br />';
        }
        if (typeof(authorTitle) != 'undefined') {
            buf += '<i>autor:</i> ' + authorTitle;
        }
        if (typeof(sourceTitle) != 'undefined') {
            if (typeof(authorTitle) != 'undefined') {
                buf += ', ';
            }
            buf += '<i>zdroj:</i> ' + sourceTitle;
        }
        return buf;
    },

    show: function(filename, title, authorTitle, sourceTitle) {
        this.showNavigate(false, false);
        $(this.lightBoxIdTitle).html(this.makeTitle(title, authorTitle, sourceTitle));

        return this.showImage(config.storagePublicUrl + filename);
    },

    showPrivate: function(filename, title, authorTitle, sourceTitle) {
        this.showNavigate(false, false);
        $(this.lightBoxIdTitle).html(this.makeTitle(title, authorTitle, sourceTitle));

        return this.showImage(filename);
    },

    showNavigate: function(left, right) {
        if (left == true) {
            $("#dialog_image_nav_left").show();
        } else {
            $("#dialog_image_nav_left").hide();
        }
        if (right == true) {
            $("#dialog_image_nav_right").show();
        } else {
            $("#dialog_image_nav_right").hide();
        }
    },

    close: function() {
        if (this.active) {
            this.active = false;

            $(this.lightBoxIdTitle).html('');
            $(this.lightBoxIdObj).hide();
            lightBox.close();
        }

        return false;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------- galleryPreview -------------------------------- */
/* -------------------------------------------------------------------------- */

var galleryPreview = {
    width: 835,
    height: 660,
    active: false,

    lightBoxIdObj: '#dialog_image',
    lightBoxIdContent: '#dialog_image_content',
    lightBoxIdTitle: '#dialog_image_title',

    carouselList: null,
    carouselIndex: null,

    show: function(carouselList, carouselIndex) {
        this.carouselList = carouselList;
        this.carouselIndex = carouselIndex;

        this.active = true;

        $(this.lightBoxIdObj).width(this.width);
        $(this.lightBoxIdObj).height(this.height);

        this.showCarouselItem();
        $(this.lightBoxIdObj).show();

        return lightBox.show(this, false);
    },

    showCarouselItem: function() {
        $(this.lightBoxIdContent).html('');

        var __navigateLeft = true;
        var __navigateRight = true;

        if (this.carouselIndex == 0) {
            __navigateLeft = false;
        }
        if ((parseInt(this.carouselIndex) + 1) == this.carouselList.length) {
            __navigateRight = false;
        }

        imagePreview.showNavigate(__navigateLeft, __navigateRight);

        $(this.lightBoxIdTitle).html(imagePreview.makeTitle(
            this.carouselList[this.carouselIndex].title,
            this.carouselList[this.carouselIndex].author,
            this.carouselList[this.carouselIndex].source,
            (parseInt(this.carouselIndex) + 1) + '/' + this.carouselList.length
            )
        );

        $(this.lightBoxIdContent).append(
            '<div class="img">' +
                '<img src="' + this.carouselList[this.carouselIndex].orig + '" onclick="return lightBox.close()">' +
            '</div>'
        );
    },

    navigateLeft: function(obj) {
        if (this.carouselIndex) {
            this.carouselIndex--;
        }
        if (typeof(obj) == 'object') {
            obj.blur();
        }
        this.showCarouselItem();
    },

    navigateRight: function(obj) {
        if (this.carouselIndex<this.carouselList.length-1) {
            this.carouselIndex++;
        }
        if (typeof(obj) == 'object') {
            obj.blur();
        }
        this.showCarouselItem();
    },

    navigateOver: function(obj) {
        $(obj).removeClass('dialog_image_nav');
    },

    navigateOut: function(obj) {
        $(obj).addClass('dialog_image_nav');
    },

    close: function() {
        if (this.active) {
            this.active = false;

            $(this.lightBoxIdObj).hide();
            lightBox.close();
        }

        return false;
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------- rightControl ---------------------------------- */
/* -------------------------------------------------------------------------- */

var rightControl = {
    id: false,
    obj: false,
    name: false,
    type: false,

    show: function (obj, id, name, type) {
        this.id = id;
        this.obj = obj;
        this.name = name;
        this.type = type;

        var value = $("#" + id).val();

        return mfAjax.action( {
            'obj': obj,
            'url': link.rightControl,
            'data': {
                'id': id,
                'name': name,
                'value': value,
                'type': type
            }
        } );
    },

    showDialog: function() {
        this.idRightChange();
        dialog.show();
    },

    idRightChange: function() {
        var value = $("#frmrightForm-id_right").val();
        if (value == 'friend') {
            $("#rightControl-rel").show();
        } else {
            $("#rightControl-rel").hide();
        }
    },

    save: function () {
        var relRightData = $("input[name*='rel_right']:checked").serializeArray();
        var relRight = new Array();
        var idRight = $("#frmrightForm-id_right").val();

        for (var i in relRightData) {
            relRight.push(relRightData[i]['name']);
        }

        return mfAjax.action( {
            'obj': this.obj,
            'url': link.rightControlSave,
            'data': {
                'id': this.id,
                'id_right': idRight,
                'rel_right': relRight.join(',')
            }
        } );
    },

    handleSave: function(value, text) {
        $("#" + this.id + '-title').html(text);
        $("#" + this.id).val(value);

        this.close();
    },

    close: function () {
        this.id = false;
        this.obj = false;
        this.name = false;
        this.type = false;

        return dialog.close();
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------- Diary  ---------------------------------------- */
/* -------------------------------------------------------------------------- */

var diary = {
    elId: '#frmdiaryForm-content',
    wiki: {'b': '**',
           'i': '//',
           'u': '__'},

    addSmiley: function(obj) {
        return textAreaControl.addSmiley(this.elId, obj);
    },

    addFormat: function(tag) {
        return textAreaControl.formatSelected(this.elId, this.wiki[tag], this.wiki[tag]);
    },

    deleteDiary: function() {
        return true;
    }
}

var textAreaControl = {
    scrollTop: false,
    selection: null,

    addSmiley: function(elId, obj) {
        var tag = $(obj).find("img").attr('title');

        this.saveScroll(elId);
        this.saveSelection(elId);

        $(elId).replaceSelection(' ' + tag + ' ');

        this.restoreScroll(elId);
        this.selection.start += 2 + tag.length;
        this.selection.end +=  2 + tag.length;
        this.setSelection(elId);

        return false;
    },

    saveScroll: function(elId) {
        this.scrollTop = $(elId).scrollTop();
    },

    restoreScroll: function(elId) {
        if (this.scrollTop) {
            $(elId).scrollTop(this.scrollTop);
        }
    },

    saveSelection: function(elId) {
        this.selection = $(elId).getSelection();
    },

    setSelection: function(elId) {
        if (this.selection.start) {
            $(elId).setSelection(this.selection.start, this.selection.end);
        }
    },

    formatSelected: function(elId, tagPre, tagPost) {
        this.saveScroll(elId);

        var text = $(elId).getSelection().text;
        if (text == '') {
            text = ' ';
        }

        var textWiki = tagPre + text;
        if (typeof(tagPost) != 'undefined') {
            textWiki += tagPost;
        }

        $(elId).replaceSelection(textWiki);

        this.restoreScroll(elId);
        return false;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------- Friend ---------------------------------------- */
/* -------------------------------------------------------------------------- */

var friend = {

    editGroup: function(id_friend) {
        return mfAjax.action( {
            'obj': null,
            'url': link.friendEditGroup,
            'data': {
                'id_friend': id_friend
            }
        } );
    },

    showEditGroup: function() {
        dialog.show();
    },

    saveGroup: function() {
        var friendGroup = $("input[name*='group[']:checked").serializeArray();
        var friendData = new Array();
        var idFriend = $("input[name='id_friend']").val();

        for (var i in friendGroup) {
            friendData.push(friendGroup[i]['name']);
        }

        return mfAjax.action( {
            'obj': null,
            'url': link.friendSaveGroup,
            'data': {
                'id_friend': idFriend,
                'group': friendData.join(',')
            }
        } );
    },

    deleteGroup: function(obj, text) {
        var val = $("#frmgroupFilterForm-id_group").val();
        if (!val) {
            return false;
        } else {
            return dialogConfirm.form(obj, text);
        }
    },

    close: function() {
        return dialog.close();
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------- searchControl --------------------------------- */
/* -------------------------------------------------------------------------- */

var searchControl = {
    select: function(obj, what) {
        return mfAjax.action( {
            'obj': this.obj,
            'url': link.showSiteSearch,
            'data': {
                'search': what,
                'query': $('#frmsearchControlForm_header-query').val()
            }
        } );
    },

    onFocus: function() {
        $('#frmsearchControlForm_header-query').addClass('active');
        return false;
    },

    onBlur: function() {
        var objInput = $('#frmsearchControlForm_header-query');
        if (objInput.val() == '') {
            objInput.removeClass('active');
        }
        return false;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------- Profile Presenter ----------------------------- */
/* -------------------------------------------------------------------------- */
var profile = {
    babyObj: false,

    init: function() {
        $(document).ready(function () {
            $("#frmEditForm-id_group").bind('change',profile.changeBabyBirthday);
            profile.changeBabyBirthday();

            $('input.datepicker').datepicker(
                {
                    duration: 'full',
                    changeMonth: true,
                    changeYear: true,
                    firstDay: 1,
                    minDate: '-40y',
                    maxDate: '+0d',
                    yearRange: '-40:+40'
                }
            );
        });
    },

    changeBabyBirthday: function() {
        var idGroup = $("#frmEditForm-id_group").val();

        if (idGroup == 'pregnant') {
            $("#baby_birthday").show();
        } else {
            $("#baby_birthday").hide();
        }
    },

    removeBaby: function(obj) {
        this.babyObj = obj;
        return dialogConfirm.clb('profile.handleRemoveBaby()', dictionary.profileRemoveBaby);
    },

    handleRemoveBaby: function() {
        var obj = profile.babyObj;
        profile.babyObj = false;

        if (obj) {
            return formTableRemoveElement(obj,
                'form_table',
                form_elements,
                form_namePrefix,
                form_idPrefix,
                form_ignoreRow,
                form_labels
            );
        }
        return false;
    },

    addChild: function() {
        formTableCreateElement('form_table', form_elements, form_namePrefix, form_idPrefix, 0, form_labels);
        
        maminka.datePicker();

        return false;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------- hospitalPresenter ----------------------------- */
/* -------------------------------------------------------------------------- */

var hospital = {
    init: function() {
        $(document).ready( function () {
            hospitalMap.initialize();
        });
    },

    toggleAdvencedBasic: function() {
        $('#searchAdvanced').toggle('fast', function() {
            if ($(this).is(":visible")) {
                $('#linkAdv').text(dictionary.simpleSearch);
                $('#firstSubmit').hide();
            } else {
                $('#linkAdv').text(dictionary.advancedSearch);
                $('#firstSubmit').show();
            }
        });
    }
};

var hospitalMap = {
    initialize: function () {
        if (GBrowserIsCompatible()) {
            this.map = new GMap2(document.getElementById("map_canvas"));
            this.map.setCenter(new GLatLng(hospitalParam.latitude, hospitalParam.longitude), hospitalParam.zoom);
            this.map.addControl(new GSmallMapControl());
            this.map.addControl(new GMapTypeControl());

            for (var i in hospitalData) {
                this.createHospital(hospitalData[i])
            }
        }
    },

    createHospital: function (data) {
        var point = new GLatLng(data.latitude, data.longitude);
        var hospital = new GMarker(point);
        hospitalMap.map.addOverlay(hospital);

        GEvent.addListener(hospital, "click", function() {
            hospitalMap.map.openInfoWindowHtml(point, data.titleHtml);
        });
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------- babyName -------------------------------------- */
/* -------------------------------------------------------------------------- */

var babyName = {
    hideName: function(nameId) {
        $('#name_' + nameId).hide();

        return true;
    },

    removeFromPoll: function(nameId) {
        mfAjax.action( {
            'obj': this,
            'url': link.removeFromPoll,
            'data': {
                'nameId': nameId
            }
        } );

        babyName.hideName(nameId);

        return false;
    },

    toggleAdvencedBasic: function() {
        $('#searchAdvanced').toggle('fast', function() {
            if ($(this).is(":visible")) {
                $('#linkAdv').text(dictionary.simpleSearch);
                $('#firstSubmit').hide();
            } else {
                $('#linkAdv').text(dictionary.advancedSearch);
                $('#firstSubmit').show();
            }
        });
    }
};

/* -------------------------------------------------------------------------- */
/* ------------------------------ base -------------------------------------- */
/* -------------------------------------------------------------------------- */

var flashMessage = {
    active: false,
    lightBoxIdObj: '#dialog_flash',
    lightBoxIdContent: '#dialog_flash_content',

    show: function(message, type) {
        if (lightBox.active) {
            alert(message);
            return false;
        }
        if (this.active) {
            return false;
        }

        this.active = true;

        // TODO - type
        $(this.lightBoxIdContent).html(message);

        $(this.lightBoxIdObj).show();
        return lightBox.show(this);
    },

    close: function() {
        if (this.active) {
            this.active = false;

            $(this.lightBoxIdObj).hide();
            lightBox.close();
        }

        return false;
    }
};

var dialogConfirm = {
    active: false,
    lightBoxIdObj: '#dialog_confirm',
    lightBoxIdContent: '#dialog_confirm_content',
    formObj: false,
    linkObj: false,
    clbObj: false,

    form: function(formObj, message) {
        if (this.active) {
            return true;
        }

        this.active = true;
        this.formObj = formObj;

        $(this.lightBoxIdContent).html(message);

        $(this.lightBoxIdObj).show();
        return lightBox.show(this);
    },

    clb: function(clb, message) {
        if (this.active) {
            return true;
        }

        this.active = true;
        this.clbObj = clb;

        $(this.lightBoxIdContent).html(message);

        $(this.lightBoxIdObj).show();
        return lightBox.show(this);
    },

    yes: function() {
        if (this.formObj) {
             if ($(this.formObj).attr('tagName') == 'FORM') {
                return $(this.formObj).submit();
             } else {
                return this.formObj.click();
             }
        } else if (this.clbObj) {
            eval(this.clbObj);
            this.close();
        } else if (this.linkObj) {
            window.location = this.linkObj.href;
        }
        return false;
    },

    close: function() {
        if (this.active) {
            this.active = false;

            $(this.lightBoxIdObj).hide();
            lightBox.close();
        }

        this.formObj = false;
        this.linkObj = false;
        this.clbObj = false;

        return false;
    },

    link: function(linkObj, message) {
        if (this.active) {
            return true;
        }

        if ($.browser.msie) {
            return confirm(message);
        }

        this.active = true;
        this.linkObj = linkObj;

        $(this.lightBoxIdContent).html(message);

        $(this.lightBoxIdObj).show();
        return lightBox.show(this);
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------– top article Control --------------------------- */
/* -------------------------------------------------------------------------- */

var articleControl = {

    init: function()
    {
        $(document).ready(function () {
            articleControl.start();
        });
    },


    start: function() {

        var animationSpeed = 3000; // speed of animation
        var count = $(".hp_left_box .hp_in_box").size() * 1;
        /* check if the number of elemens is not 1 */
        if (count > 1){

            $(".hp_left_box #box_1").addClass("active");


            $("div.hp_in_box").mouseover(function() {
                if ($(this).hasClass("active") != true) {
                    if ($(this).hasClass("commercial") == true) {
                        $(this).addClass("commercial_hover");
                    }
                    $(this).addClass("hover");
                }
                number = $(this).attr("id").substr(4,5);
                $(".hp_right_box img").css("opacity","0");
                $(".hp_left_box .hp_in_box").removeClass("active");
                $(this).addClass("active");
                $("#hp_img_"+number).css("opacity","1");
                clearInterval(MyInterval);
            });
            $("div.hp_in_box").mouseout(function() {
                if ($(this).hasClass("hover") == true) {
                    if ($(this).hasClass("commercial_hover") == true) {
                        $(this).removeClass("commercial_hover");
                    }
                    $(this).removeClass("hover");
                }
                $(".hp_right_box img").css("opacity","0");
                number = $(this).attr("id").substr(4,5);
                $("#hp_img_"+number).css("opacity","1");
                number = 0;
                MyInterval = window.setInterval(hp_box, 3000);
            });

            function hp_box() {
                var number = $(".hp_left_box .active").attr("id").substr(4,5);
                number = (number * 1 )+ 1;
                var prev = number - 1;
                count = $(".hp_left_box .hp_in_box").size() * 1;
                if (number == count + 1) {
                    number = 1;
                    prev = count;
                }
                $("#hp_img_"+prev).css("z-index","0");
                $("#hp_img_"+number).css("z-index","1");
                $("#hp_img_"+prev).animate({opacity : 0}, 900);
                $("#hp_img_"+number).animate({opacity : 1}, 900);
                $(".hp_left_box #box_"+number).addClass("active");
                $(".hp_left_box #box_"+prev).removeClass("active");
            }

            MyInterval = window.setInterval(hp_box, 3000);

        } else { // if here is only one element
            $(".hp_left_box #box_1").addClass("active");
        };
    }
};


/* -------------------------------------------------------------------------- */
/* ----------------------------Comment Reply Control------------------------- */
/* -------------------------------------------------------------------------- */

var CommentReplyControl = {
    elId: '#frmreplyComment-text',

    init: function()
    {
        $(document).ready(function ()
        {
        	CommentReplyControl.start();
        });
    },

    start: function()
    {
        multi = $("#frmreplyComment-replyCommentStats").val();
        $("#frmreplyComment-replyCommentCode").val(parseInt(multi.substring(0,1)) * parseInt(multi.substring(1,2)));
    	
    	$("#replyCommentForm").hide();
        slidedUp = 0;

        NumberOfElements = $(".discusion_list_all .main_box_in > div.discusion_list").size(); // read the number of all comments
        for(var i = 0; i < NumberOfElements; i++){

            $(".discusion_list_all .main_box_in  > div.discusion_list:eq("+ i +")").attr('id', "box" + i);

            $(".discusion_list_all .main_box_in  #box" + i +" .get-reaction").attr('id', i); // get IDs to comments and link
        };

        $(".discusion_list_all .main_box_in  .get-reaction").click(function(){

            selected = $(this).attr('id'); // read the  IDs of clicked link

            title = ("Re: " + $("#box" + selected + " h3").text());

            $("#frmreplyComment-title").val(title); // set the "reply" title

            $(".discusion_list_all .main_box_in  div.discusion_list").removeClass("selected");
            $(".discusion_list_all .main_box_in  #box" + selected).addClass("selected");

            if($(this).hasClass("selected")){

                $("#replyCommentForm").slideUp();
                $(".get-reaction").removeClass("selected");
                $(".discusion_list_all .main_box_in  div.discusion_list").removeClass("selected");

            } else {

                $(".get-reaction").removeClass("selected");

                $("#replyCommentForm").hide();
                $("#replyCommentForm").appendTo("#box" + selected);
                $("#replyCommentForm").slideDown();

                $("#box" + selected + " .get-reaction").addClass("selected");

            };

            return false;
        });

        $("#frmreplyComment-cancel").click(function(){
            $("#replyCommentForm").slideUp();
            $(".get-reaction").removeClass("selected");
            $(".discusion_list_all .main_box_in  div.discusion_list").removeClass("selected");

            return false;
        });

    },

    addSmiley: function(obj) {
        return textAreaControl.addSmiley(this.elId, obj);
    }
};

/* -------------------------------------------------------------------------- */
/* ------------------------------ Watch Discussion -------------------------- */
/* -------------------------------------------------------------------------- */

var watchDiscussion = {

    setWatch: function(modeId, type) {
        mfAjax.action( {
            'obj': this,
            'url': link.setWatchDiscussion,
            'data': {
                'id': modeId,
                'type': type
            }
        } );

        return false;
    },

    showDialog: function() {
        dialog.show();
        return false;
    },

    save: function() {
           mfAjax.action( {
            'obj': null,
            'url': link.addWatchDiscussion,
            'data': {
                'id': $("#frmsetWatchForm-modeId").val(),
                'type': $("#frmsetWatchForm-type").val(),
                'notifyType': $("#frmsetWatchForm-notifyType").val()
            }
        } );
        this.close();
        return false;
    },

    close: function() {
        dialog.close();
        return false;
    }
}

/* -------------------------------------------------------------------------- */
/* ------------------------------ Comment Controls -------------------------- */
/* -------------------------------------------------------------------------- */

var addCommentControl = {
    elId: '#frmaddComment-text',
    
    setParentToComment: function(parentId) {
        $("#frmreplyComment-parent_id").val(parentId);
        $('#replyCommentForm').show();
        return false;
    },

    hideReplyForm: function() {
        $('#replyCommentForm').hide();

        return false;
    },

    offendingNotify: function() {
        alert('TODO');
        lightBox.show(this);
        $("#offendingNotify").show();

        return false;
    },

    addSmiley: function(obj) {
        return textAreaControl.addSmiley(this.elId, obj);
    }
};

var listCommentControl = {

    init: function()
    {
        $(document).ready(function () {
            if (!$("#frmSearchForm-text").val()) {
                listCommentControl.hideFulltextSearch();
            }
            multi = $("#frmaddComment-addCommentStats").val();
            $("#frmaddComment-addCommentCode").val(parseInt(multi.substring(0,1)) * parseInt(multi.substring(1,2)));
        });
    },

    checkComment: function(discussionId, id) {
        var isChecked = '';

        if ($("#checkCommentId_" + id).is(":checked")) {
            isChecked = "on";
        }

        mfAjax.action( {
            'obj': this,
            'url': link.checkComment,
            'data': {
                'discussionId': discussionId,
                'commentId': id,
                'isChecked': isChecked
            }
        } );
    },

    offendingConfirm: function(idComment) {
        return dialogConfirm.clb('listCommentControl.offendingSend(' + idComment + ')', dictionary.offendingConfirm);
    },

    offendingSend: function(idComment) {
        mfAjax.action( {
            'obj': this,
            'url': link.commentOffendingNotify,
            'data': {
                'id': idComment
            }
        } );
    },

    fulltextSearch: function() {
    	if ($("#list-comment-fulltext-add").is(':visible')) {
            $("#list-comment-fulltext-add").slideUp();
        } else {
            $("#list-comment-fulltext-add").slideDown();
            $("#list-comment-fulltext-add table textarea:first").focus();
        }

        return false;
    },

    hideFulltextSearch: function() {
        //$("#list-comment-fulltext-add").hide();
    }
};


/* -------------------------------------------------------------------------- */
/* ------------------------------ Rating Control ---------------------------- */
/* -------------------------------------------------------------------------- */

var ratingControl= {
    controls: {},
    controlsRating: {},
    controlsTimeOut: null,
    controlsTimeOutId: null,

    init: function(id, rating)
    {
        this.controls[id] = false;
        this.controlsRating[id] = rating;

        $(document).ready(function () {
            ratingControl.start();
        });
    },

    start: function()
    {
        for (var i in this.controls) {
            if (this.controls[i] != true) {
                this.controls[i] = true;

                $("#" + i + " a").mouseover(ratingControl.slide);
                $("#" + i).mouseout(ratingControl.slideOffTimeOut);
            }
        }
    },

    slide: function()
    {
        if (ratingControl.controlsTimeOut) {
            window.clearTimeout(ratingControl.controlsTimeOut);
            ratingControl.controlsTimeOut = null;
        }

        var sta = 0;
        var end = $(this).text();
        var li = $(this).parent().parent().find("li");

        li.removeClass("selected");
        li.slice(sta, end).addClass("selected");
    },

    slideOffTimeOut: function()
    {
        if (ratingControl.controlsTimeOut) {
            window.clearTimeout(ratingControl.controlsTimeOut);
            ratingControl.controlsTimeOut = null;
        }
        ratingControl.controlsTimeOutId = $(this).attr('id');
        ratingControl.controlsTimeOut = window.setTimeout(ratingControl.slideOff, 200);
    },

    slideOff: function()
    {
        if (ratingControl.controlsTimeOutId) {
            $("#" + ratingControl.controlsTimeOutId + " li").removeClass("selected");
            var restoreRating = ratingControl.controlsRating[ratingControl.controlsTimeOutId];
            if (restoreRating > 0) {
                $("#" + ratingControl.controlsTimeOutId + " li").slice(0, restoreRating).addClass("selected");
            }
        }
        ratingControl.controlsTimeOutId = null;
    }
}

/* -------------------------------------------------------------------------- */
/* --------------------------- message -------------------------------------- */
/* -------------------------------------------------------------------------- */

var message = {
    userIconActive: false,
    elId: '#frmmessageForm-text',

    init: function() {
        $(function() {
            $(".friend-list-level2").bind('mouseover', function(e) {
                message.showUserIcon($(this));
            });
            $(".friend-list-level1,.friend-list-level2").bind('mouseout', message.hideUserIcon);
        });
    },

    deleteMessage: function(messageId) {
        mfAjax.action( {
            'obj': this,
            'url': link.messageDelete,
            'data': {
                'messageId': messageId
            }
        } );

        $('#message_' + messageId).remove();

        return false;
    },

    deleteMessages: function() {
        $("input[id^='message_del_']:checked").each(function() {
            message.deleteMessage($(this).val());
        });

        return false;
    },

    selectGroup: function(groupId) {
        var value = $("input[name='recipients[" + groupId + "]']").is(':checked');
        $("input[name^='recipients_" + groupId + "']").attr('checked', value);
    },

    toggleGroup: function(groupId) {
        $("input[name='recipients[" + groupId + "]']").attr('checked', false);
    },

    checkRecipients: function() {
        if ($("input[name^='recipients_']:checkbox:checked").length == 0) {
            flashMessage.show('Musíte vybrat alespoň jednoho příjemce vzkazu', 'error');
            return false;
        }

        return true;
    },

    showUserIcon: function(obj) {
        $("#message-choose-group .choose-group-over").removeClass('choose-group-over');
        $(obj).addClass('choose-group-over');

        var imgFilename = $(obj).find("input:checkbox").attr('mfImage');

        if (imgFilename) {
            userIconUrl = config.storagePublicUrl + imgFilename;
        } else {
            userIconUrl = config.baseUri + 'img/default-user.png';
        }

        if (!message.userIconActive) {
            message.userIconActive = true;
            $("#userIcon").show();
        }
        $('#userIcon').attr('src', userIconUrl);
    },

    hideUserIcon: function() {
        if (message.userIconActive) {
            $("#message-choose-group .choose-group-over").removeClass('choose-group-over');
            message.userIconActive = false;
            $("#userIcon").hide();
        }
    },

    addSmiley: function(obj) {
        return textAreaControl.addSmiley(this.elId, obj);
    }
}

/* -------------------------------------------------------------------------- */
/* ------------------------------ poll -------------------------------------- */
/* -------------------------------------------------------------------------- */

var poll = {
    vote: function(pollElId, pollId) {
        var selectedOptions = new Array;
        var regExp = new RegExp('^options\\[(\\d+)\\]$');

        $('#' + pollElId + ' :checkbox:checked').each(function() {
            var optionId = $(this).attr('name').match(regExp);
            selectedOptions.push(optionId[1]);
        });

        if (selectedOptions.length == 0) {
            alert('Nevybrala jste žádnou odpověď!');
        } else {
            mfAjax.action( {
                'obj': this,
                'url': link.pollVote,
                'data': {
                    'poll_id': pollId,
                    'options': selectedOptions.toString()
                }
            } );
        }

        return false;
    },

    voteOne: function(pollId, optionId) {
        mfAjax.action( {
            'obj': this,
            'url': link.pollVote,
            'data': {
                'poll_id': pollId,
                'option': optionId
            }
        } );

        return false;
    }
};


/* -------------------------------------------------------------------------- */
/* ------------------------------ calendar ---------------------------------- */
/* -------------------------------------------------------------------------- */

var calendar = {
   
    calendarData: null,
    calendarDataByDate: null,

    calendarForm: null,

    exclusiveFieldSets: {
        birthday: ['name','birth_date'],
        menstruation: ['cycle','last_menstruation_date']
    },

    commonFieldSets: {
        dateFields: ['date_from','date_to'],
        timeFields: ['time_from','time_to'],
        contentFields: ['subject','content']
    },

    init: function(calendarData, calendarDataByDate) {
        this.calendarData = calendarData;
        this.calendarDataByDate = calendarDataByDate;
       
        $(function(){

            calendar.calendarForm = $('#calendar-form');

            $("#calendar-view .day-cell").dblclick(function () {
                 calendar.showDay(this);
                 return false;
            });
            $("#calendar-view .show-day").click(function () {
                 calendar.showDay(this);
                 return false;
            });
            // We need live, because elements of this type are created using DOM
            $("#calendar .show-event").live('click', function () {
                 calendar.showEvent(this);
                 return false;
            });
            $("#calendar .delete-event").live('click', function () {
                 return confirm(dictionary.deleteEventConfirm);
            });
            $("#calendar-form select[name=id_type]").change(function () {
                calendar.enableFields($(this).val());
                 return false;
            });
            $("#calendar-detail .add-event").click(function () {
                 calendar.showEvent(null);
                 return false;
            });
            $("#calendar-detail .close-detail").click(function () {
                 lightBox.close();
                 return false;
            });

            $("#calendar-detail table td.data")
                .mouseover(function(){
                    $(this).addClass('active')
                })
                .mouseout(function(){
                    $(this).removeClass('active')
                });

            $("#calendar-form .for-clone").parents('tr').hide();

            $("#calendar-form input[name=cancel]").click(function(){
                lightBox.close();
                return false;
            });
        });
    },

    getHour: function(time) {
        var parts = time.split(':');
        // parseInt removes leading zero
        return parseInt(parts[0],10);
    },

    getMin: function(time) {
        var parts = time.split(':');
        // parseInt removes leading zero
        return parseInt(parts[1],10);
    },

    showDay: function(parent) {
        var date = $(".full-date", parent).text();

        var calendarDetail = $('#calendar-detail');
        var calendarTable = $('table',calendarDetail);

        $('.cur-date',calendarDetail).text(date);
        $('tr',calendarTable).removeClass('busy')
        $('td',calendarTable).text('');

        for (var eventId in this.calendarDataByDate[date]) {
            var event = this.calendarData[eventId];

            var eventInOneDay = event.date_from == event.date_to;
            var eventHasMoreDaysAndStarts = (!eventInOneDay) && event.date_from == date;
            var eventHasMoreDaysAndEnds = (!eventInOneDay) && event.date_to == date;
            var intraDay = event.time && (eventInOneDay || eventHasMoreDaysAndStarts || eventHasMoreDaysAndEnds);

            var hourRow = $('#all-day', calendarTable);
            var timeHtml = '';

            if (intraDay) {

                var startHour = eventHasMoreDaysAndEnds ? 0 : this.getHour(event.time_from);
                var endHour = eventHasMoreDaysAndStarts ? 24 : this.getHour(event.time_to);
                var endMin = this.getMin(event.time_to);

                timeHtml =
                  '<span class="time">'+
                    (eventInOneDay || eventHasMoreDaysAndStarts?event.time_from:'')+' - '+
                    (eventInOneDay || eventHasMoreDaysAndEnds?event.time_to:'')+
                  '</span>';

                hourRow = $('#hour-'+startHour, calendarTable);

                for (var hour=startHour; hour<endHour || (hour == endHour && endMin>0); hour++) {
                    $('#hour-'+hour).addClass('busy');
                }
            }

            var eventHtml =
                '<div class="event type-fg-'+event.id_type+'">'+
                  timeHtml +
                  '<span class="subject">'+event.subject+'</span>'+
                  '<span class="content">'+event.content+'</span>'+
                '</div>';
            $('.data', hourRow).append($(eventHtml));

            $('.type', hourRow)
                .append($('<div class="type-bg-'+event.id_type+'">&nbsp;</div>'));

            var actionNode = $('#calendar-actions div').get(0).cloneNode(true);
            $('span.event-id',actionNode).text(eventId);
            var deleteLink = $('a.delete-event',actionNode);
            if (event.id_type != 'birthday_baby') {
                deleteLink.attr('href', deleteLink.attr('href') + '?eventId=' + eventId);
            } else {
                deleteLink.remove();
            }


            $('.action', hourRow).append($(actionNode));
        }

        this.displayDetail();
        return false;
    },

    displayDetail: function() {
        var calendarDetail = $('#calendar-detail');
        calendarDetail.addClass('opened').show();
        lightBox.show({
            active: true,
            lightBoxIdObj: '#'+calendarDetail.attr('id'),
            close: function(){
                this.active = false;
                calendarDetail.removeClass('opened').hide();
                lightBox.close();
            }
        });
    },

    changeFieldsVisibility: function(fieldArray, show)  {
        for (var field in fieldArray) {
            var row = $('tr:has(:input[name='+fieldArray[field]+'])',this.calendarForm);
            if (show) {
                row.show();
            } else {
                row.hide();
            }
        }
    },

    enableFields: function(eventType) {

        for (var fs in calendar.commonFieldSets) {
            this.changeFieldsVisibility(this.commonFieldSets[fs], false);
        }

        for (var fs in calendar.exclusiveFieldSets) {
            this.changeFieldsVisibility(this.exclusiveFieldSets[fs], false);
        }

        switch (eventType) {
            case 'birthday':
                this.changeFieldsVisibility(this.exclusiveFieldSets.birthday, true);
                break;

            case 'menstruation':
                this.changeFieldsVisibility(this.exclusiveFieldSets.menstruation, true);
                break;

            default:
                for (var fs in this.commonFieldSets) {
                    this.changeFieldsVisibility(this.commonFieldSets[fs], true);
                }
         }

         var curDate = $('#calendar-detail .cur-date').text();
         $('input[name=date_from][value=]', this.calendarForm).val( curDate );
         $('input[name=date_to][value=]', this.calendarForm).val( curDate );
         $('input[name=birth_date][value=]', this.calendarForm).val( curDate );
    },

    populateSelect: function(selectId) {
        var typeSelect = $('select[name=id_type]', this.calendarForm);

        $('option',typeSelect).remove();

        $('select[name='+selectId+'] option',this.calendarForm).each(function(){
            $(this.cloneNode(true)).appendTo(typeSelect);
        });

        typeSelect.show();
    },

    showEvent: function(actionLink) {
        var typeSelect = $('select[name=id_type]', this.calendarForm);

        $('span.event-title',this.calendarForm).remove();

        for (var fs in this.exclusiveFieldSets) {
            this.changeFieldsVisibility(this.exclusiveFieldSets[fs], false);
        }

        for (var fs in this.commonFieldSets) {
            this.changeFieldsVisibility(this.commonFieldSets[fs], false);
        }

        $('input[type=text], input[name=id], textarea', this.calendarForm).val('');
        $('input[type=text], textarea', this.calendarForm).removeAttr('disabled');
        $('input[name=save]', this.calendarForm).show();

        $('h3', this.calendarForm).hide();

        if (actionLink) {
            $('h3.event-detail', this.calendarForm).show();

            var eventId = $(".event-id", actionLink).text();
            var event = this.calendarData[eventId];

            // If we cannot change the type
            if ($('select[name=change_id_type] option[value='+event.id_type+']').length==0) {

                typeSelect.hide();

                if (event.id_type == 'delivery' || event.id_type == 'delivery_temporary') {

                    var fullDate = $(actionLink).parent().find(".full-date").text();
                    var deliveryWeek = this.calendarDataByDate[fullDate][event.id]['subject_add'];

                    typeSelect.parent('td').append(
                        $('<span class="event-title">' +
                           deliveryWeek +
                          '. ' +
                          event.id_type_title +
                          '<br /><br />' +
                          '<a href="' + link.articleAge.replace('mdz-age-mdz', (100 + parseInt(deliveryWeek))) + '" title="">' +
                          dictionary.calendarDelivaryLink +
                          '</a>' +
                          '</span>'
                        )
                    );
                } else {
                    typeSelect.parent('td').append(
                        $('<span class="event-title">' + event.id_type_title + '</span>')
                    );
                }
            }

            // If we cannot add such type - we cannot modify either
            if ($('select[name=add_id_type] option[value='+event.id_type+']').length==0) {
                $('input[type=text], textarea', this.calendarForm).attr('disabled','disabled');
                $('input[name=save]', this.calendarForm).hide();
            }

            // Populate data in the form
            for (var i in this.calendarData[eventId]) {
                $(':input[name='+i+']', this.calendarForm).val(event[i]);
            }

            switch (event.id_type) {
                case 'birthday':
                case 'birthday_baby':
                    this.changeFieldsVisibility(this.exclusiveFieldSets.birthday, true);
                    $('input[name=name]', this.calendarForm).val( event.subject);
                    $('input[name=birth_date]', this.calendarForm).val( event.date_from);
                    break;

                case 'menstruation':
                    this.changeFieldsVisibility(this.exclusiveFieldSets.menstruation, true);
                    break;

                case 'ovulation':
                    break;

                case 'delivery':
                    break;

                case 'delivery_temporary':
                    break;

                default:
                    for (var fs in this.commonFieldSets) {
                        this.changeFieldsVisibility(this.commonFieldSets[fs], true);
                    }
                    this.populateSelect('change_id_type');
            }

            typeSelect.val(event.id_type);

        } else {
            $('h3.new-event', this.calendarForm).show();
            this.populateSelect('add_id_type');
            this.enableFields(typeSelect.val());
        }

        var calendarDetail = $('#calendar-detail');
        if (calendarDetail.hasClass('opened')) {
            this.calendarForm.addClass('reopen');
            lightBox.close();
        }
        this.calendarForm.show();
        lightBox.show({
            active: true,
            lightBoxIdObj: '#'+calendar.calendarForm.attr('id'),
            close: function(){
                this.active = false;
                calendar.calendarForm.hide();
                lightBox.close();
                if (calendar.calendarForm.hasClass('reopen')) {
                    calendar.calendarForm.removeClass('reopen');
                    setTimeout(function(){calendar.displayDetail()},10);
                }
            }
        });
    }
};

/* -------------------------------------------------------------------------- */
/* ------------------------------ advisory ---------------------------------- */
/* -------------------------------------------------------------------------- */

var advisory = {
    elId: '#frmaddForm-content',

    checkQA: function(advisoryId, id) {
        var isChecked = '';

        if ($("#checkQAId_" + id).is(":checked")) {
            isChecked = "on";
        }

        mfAjax.action( {
            'obj': this,
            'url': link.checkAdvisoryQA,
            'data': {
                'advisoryId': advisoryId,
                'QAId': id,
                'isChecked': isChecked
            }
        } );
    },

    addSmiley: function(obj) {
        return textAreaControl.addSmiley(this.elId, obj);
    }
};


/* -------------------------------------------------------------------------- */
/* ------------------------------ show-war-box------------------------------- */
/* -------------------------------------------------------------------------- */

var showWarBox = {

    init: function()
    {
        $(document).ready(function () {
            showWarBox.start();
        });
    },


    start: function() {

        $(".war .hide").hide();

        $(".war .header").append(" <a href='' id='showWarCLick'>Zobraz více</a>");


        $("#showWarCLick").toggle(
            function () {
                $(".war .hide").slideDown();
                $(".war .header a").text("Schovej více");
            },
            function () {
                $(".war .hide").slideUp();
                $(".war .header a").text("Zobraz více");
            }
        );


    }
};

/* -------------------------------------------------------------------------- */
/* ---------------------------------- Request ------------------------------- */
/* -------------------------------------------------------------------------- */

var recommend = {
    sendMessage: function(type) {
        return mfAjax.action( {
            'obj': null,
            'url': link.recommendSendMessage,
            'data': {
                'url': link.linkThis,
                'backTo': link.linkBackTo,
                'type': type
            }
        } );
    },

    sendMail: function(type) {
        return mfAjax.action( {
            'obj': null,
            'url': link.recommendSendMail,
            'data': {
                'url': link.linkThis,
                'backTo': link.linkBackTo,
                'type': type
            }
        } );
    },

    showMessage: function() {
        dialog.show(700, 400);
    },

    showMail: function() {
        dialog.show(700, 450);
    }
}

var Facebook = {
    userMessageText: '',
    title: '',
    text: '',
    link: '',
    clickLogin: false,

    init: function(facebookApiKey, title, text, link, umt) {
    this.title = title;
    this.text = text;
    this.link = link;
    this.userMessageText = umt;

    FB.init(
            facebookApiKey,
            '/xd_receiver.htm',
            {
                "ifUserConnected": Facebook.onConnected,
                "ifUserNotConnected": Facebook.onNotConnected
            }
        );
    },

    onNotConnected: function() {
    $('#facebook-loader').hide();
    $('#facebook-notConnected').show();
        $('#facebook-connected').hide();
    },

    onConnected: function() {
    if (clickLogin) {
            Facebook.callPublish();
        } else {
            $('#facebook-notConnected').hide();
        $('#facebook-loader').hide();
        $('#facebook-connected').show();
        }
    },

    callPublish: function() {
    $('#facebook-connected').hide();
    $('#facebook-continue').hide();
    $('#facebook-loader').show();
    var title = this.title;
    var text = this.text;
    var umt = this.userMessageText;
    var link = this.link;

        FB.ensureInit(function () {
            FB.Connect.streamPublish(
            '',
                {'name': title,
                'href': link,
                'description': text,
                'media':[{
                    'type': 'image',
                    'src': 'http://www.maminka.cz/img/logos/maminka-cz.png',
                    'href': link
                }]},
                null,
                '',
                umt,
                function(post_id, exception, data) {
                    $('#facebook-loader').hide();
            $('#facebook-continue').show();
                    if (post_id) {
                        window.location = link;
                    }
                }
            );
        });
    },

    clickLogin: function() {
    clickLogin = true;
    $('#facebook-loader').show();
    $('#facebook-notConnected').hide();
    $('#facebook-continue').hide();
    }
}

/* -------------------------------------------------------------------------- */
/* ----------------------------------- Ads  --------------------------------- */
/* -------------------------------------------------------------------------- */

jQuery.fn.extend({

    showStickyLeaderboard: function(){
        var pageEnvelopeSelector = '#all-page';
        var lb = $('#adblock-leaderboard');
        var lbTop = lb.position().top;
        
        $("div#adblock-leaderboard-space").css({ 
            "display" : "block",
            "height"  : $("div#adblock-leaderboard").height()
        });

        // No way to learn this from jQuery.support
        var supportsPositionFixed = ($.browser.msie && $.browser.version < 7 ? 0:1);

        $(pageEnvelopeSelector).css('padding-top',lb.outerHeight()+'px');
        lb.css({position:(supportsPositionFixed?'fixed':'absolute'), top: lbTop+'px'});

        if (supportsPositionFixed) {
            return;
        }

        var fixPosition = function(){
            // Smooth movements
            if (!lb.hasClass('moving')) {
                lb.addClass('moving').animate(
                    {top:lbTop+$(window).scrollTop()+'px'},
                    {speed: 'fast',complete: function() {lb.removeClass('moving');fixPosition();}}
                );
            }
        };

        $(window).scroll(fixPosition);        
    },

    closeStickyLeaderboard: function(){
        var pageEnvelopeSelector = '#all-page';
        $('#adblock-leaderboard').css({'position':'static','top':0});
        $("div#adblock-leaderboard-space").hide();
        $(pageEnvelopeSelector).animate({paddingTop: '0px'},{speed: 'fast'});        
    },

    showStickySkyscraper: function() {
        var ss = $('#adblock-skyscraper');
        var originalTop = ss.position().top;
        var originalMargin = 0;
        var fixPosition = function() {
            var maxTop = $('#content').height() - ss.height() - 1;
            var marginTop = Math.min( maxTop, Math.max(originalMargin,$(window).scrollTop()-originalTop));
            if (!ss.hasClass('moving')) {
                ss.addClass('moving').animate(
                    {"marginTop": marginTop+'px'},
                    {
                        speed: 'fast',
                        complete:function(){
                            $('#adblock-skyscraper').removeClass('moving');
                            fixPosition()
                        }
                    }
                );
            }
        }
        $(window).scroll(fixPosition);
    }
});
