(function ($) {

    var curr_cont_prod = 0;
    var curr_cont_anchor;
    var cont_prod_count;
    var search_width;
    var pause_contents;

    var tinymce_settings = {
        language: "pl",
        theme: "advanced",
        indentation: '30px',
        convert_urls: false,
        relative_urls: false,
        theme_advanced_buttons1: "bold,italic,underline,separator,outdent,indent,bullist,numlist,separator,undo,redo,separator,link,unlink,separator,cleanup",
        theme_advanced_buttons2: "",
        theme_advanced_buttons3: "",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        width: "100%"
    };

    $(document).ready(function () {

        // Search menu toggle animation.

        search_width = $('.main-menu li.search a').width();

        $('.main-menu li.search').bind('mouseenter', function () {
            $(this).find('input, a')
                .addClass('hover')
                .stop('true', 'true');
            $(this).find('a')
				.animate({ width: 200 }, 200, function () {
				    $(this).siblings('input')
                        .fadeIn('fast');
				})
				.siblings('input').stop('true', 'true');
        }).bind('mouseleave focusout', function () {
            if ($(this).find('input').is(':focus')) {
                return;
            }
            $(this).find('input, a')
                .removeClass('hover')
                .stop('true', 'true');
            $(this).find('a')
				.siblings('input')
					.fadeOut('fast', function () {
					    $(this).siblings('a')
                            .animate({ width: search_width }, 200);
					});
        });

        // Content banner animation.

        $('.content-banner-menu a').mouseenter(function () {
            if ($(this).hasClass('hover') || $(this).hasClass('direct')) { return; }
            curr_cont_anchor = $(this).attr('name');
            curr_cont_prod = 0;
            $(this).closest('ul').find('a').removeClass('hover');
            $(this).addClass('hover');
            $.swapContent(0);
        });

        $('.content-banner .control-prev, .content-banner .control-next')
			.fadeTo(0, 0.3)
			.mouseover(function () { $(this).stop('true', 'true').fadeTo('fast', 1.0); })
			.mouseout(function () { $(this).stop('true', 'true').fadeTo('fast', 0.3); });

        $('.content-banner .control-prev').click(function () { $.swapContent(-1); });
        $('.content-banner .control-next').click(function () { $.swapContent(1); });
        $('.content-banner').parent('div').mouseenter(function () {
            pause_contents = true;
        }).mouseleave(function () {
            pause_contents = false;
        });

        // Courses preview container animation.

        $('#courses-menu a').mouseenter(function () {
            if ($(this).hasClass('hover')) { return; }
            pIndex = $(this).closest('ul').find('a').index($(this));
            tHeight = $('#course-preview p')
				.eq(pIndex)
				.getHeight();
            $(this).closest('ul').find('a').removeClass('hover');
            $(this).addClass('hover');
            $('#course-preview p')
				.stop('true', 'true')
				.css('display', 'none')
				.eq(pIndex)
				.parent()
					.stop('true', 'true')
					.animate({ height: tHeight }, 300)
				.end()
				.delay(300)
				.fadeIn('slow');
        });

        // Highlighting selected menu position.

        $('ul.menu a').each(function (item) {
            if (window.location == $(this).attr('href') ||
                window.location == $(this).attr('href') + "/" ||
                (window.location.pathname != null && window.location.pathname == $(this).attr('href'))) {
                $(this).addClass('hover');
            }
        });

        // Menu items toggle.

        $('ul.menu .toggle').click(function () {
            var content = $(this).siblings('ul');
            $(this).closest('ul')
                .find('li, ul')
                .stop(true, true);
            if ($(this).hasClass('hover')) {
                var tHeight = $(this).closest('li').getCondHeight(content, false);
                $(this).removeClass('hover')
                    .siblings('ul')
                    .fadeOut('slow', function () {
                        $(this).closest('li')
                            .animate({ height: tHeight }, 300)
                    });
            } else {
                var tHeight = $(this).closest('li').getCondHeight(content, true);
                $(this).addClass('hover')
                    .closest('li')
                    .animate({ height: tHeight }, 300, function () {
                        $(this).find('ul')
                            .fadeIn('slow')
                    });
            }
        });

        // Additional course info toggle.

        $('a.more-info').bind('click', function (e) {
            e.preventDefault();
            var info = $(this).closest('tr').next('.more-info').find('td');
            if (info.css('display') == 'none') {
                info.fadeIn('fast');
                $(this).addClass('hover');
            } else {
                info.fadeOut('fast');
                $(this).removeClass('hover');
            }
        });

        // Admin panel controls behaviour.

        $('table.data-grid td.controls a').click(function (e) {
            if ($(this).attr('href').indexOf('Delete') != -1) {
                var confirmation = confirm("Czy na pewno usunac wybrany element?");
                if (!confirmation) {
                    e.preventDefault();
                }
            }
        });

        // Setting TinyMCE toggle controls.

        $('table .wysiwyg').appendToggleControls();

        // Content banner animation trigger.

        $('.content-menu li').find('a:not(.direct)')
            .first()
            .trigger('mouseenter');
        pause_contents = false;

        setInterval((function () {
            if (!pause_contents) {
                $('.content-banner .control-next').trigger('click');
            }
        }), 8000);

    });

    $(window).load(function () {

        $('#courses-menu a:eq(0)').trigger('mouseenter');

    });

    $.swapContent = function (i) {
        curr_cont_prod += i;
        cont_prod_count = $('.content-banner #' + curr_cont_anchor + ' .description').length - 1;
        if (cont_prod_count < 0) { $.swapContentDisplay(); return; }
        if (curr_cont_prod < 0) {
            curr_cont_prod = cont_prod_count;
        } else if (curr_cont_prod > cont_prod_count) {
            curr_cont_prod = 0;
        }
        $.swapContentDisplay();
    }


    $.swapContentDisplay = function () {
        $('.content-banner .display').stop('true', 'true');
        $('.content-banner .display .description').remove();
        $('.content-banner .display').append($('.content-banner #' + curr_cont_anchor + ' .description:eq(' + curr_cont_prod + ')').outerHtml());
        $('.content-banner .display .description').fadeIn('slow');
        if (cont_prod_count > 0) {
            $('.control-prev, .control-next').fadeIn('slow');
        } else {
            $('.control-prev, .control-next').css('display', 'none');
        }
    }

    $.fn.getHeight = function () {
        $(this).fadeIn(0);
        elementHeight = $(this).outerHeight(true);
        $(this).fadeOut(0);
        return elementHeight;
    }

    $.fn.getCondHeight = function (objects, fadeIn) {
        var startHeight = $(this).outerHeight(false);
        var targetHeight;
        $(this).css('height', 'auto');
        if (fadeIn) {
            objects.fadeIn(0);
            targetHeight = $(this).outerHeight(false);
            objects.fadeOut(0);
        } else {
            objects.fadeOut(0);
            targetHeight = $(this).outerHeight(false);
            objects.fadeIn(0);
        }
        $(this).css('height', startHeight);
        return targetHeight;
    }

    $.fn.outerHtml = function () {
        return $(this).clone().wrap('<div></div>').parent().html();
    }

    // TinyMCE init.

    $.fn.initTinymce = function (scriptUrl, styleSheets) {
        var instanceSettings = $.extend({
            script_url: scriptUrl,
            content_css: styleSheets
        }, tinymce_settings);
        $('textarea.wysiwyg').tinymce(instanceSettings);
    }

    $.fn.appendToggleControls = function () {
        return this.each(function () {
            var editor = $(this);
            var html = $('<a class="button" href="javascript:;">HTML</a>');
            var wys = $('<a class="button hover" href="javascript:;">WYSIWYG</a>');
            $(this).closest('td')
                .prev()
                .append("<br>", wys, html)
                .find('a')
                .bind('click', function () {
                    $(this).addClass('hover')
                        .siblings('a')
                        .removeClass('hover');
                });
            wys.bind('click', function () {
                editor.tinymce().show();
            });
            html.bind('click', function () {
                editor.tinymce().hide();
            });
        });
    }

    // Images preloading.

    var img_buffer = [];

    $.bufferImages = function () {
        for (var i = 0; i < arguments.length; i++) {
            var img = document.createElement("img");
            img.src = arguments[i];
            img_buffer.push(img);
        }
    };

    $.bufferImages(
        "/../../content/images/element_dark_bg.png",
        "/../../content/images/element_darker_bg.png",
        "/../../content/images/search_ico_hover.png"
    );

})(jQuery);
