;(function ($, undefined) {

    $(document).ready(function () {

        /* Side */
        var lastScrollPos = 0;

        $(window).on('scroll.sleep', function (e) {
            if ($(this).scrollTop() < lastScrollPos || $(this).scrollTop() < 60) {
                $('#side').removeClass('asleep');
            } else {
                $('#side').addClass('asleep');
            }
            lastScrollPos = $(this).scrollTop();
        });

        /* Menu */
		$('#menu li').has('ul').find('> a').on('click', function (e) {
            $(this).parent().toggleClass('open');
            e.preventDefault();
        });

        $('#menu').on('click', function (e) {
	        if ($(e.target).closest('.menu-container').length === 0) {
	        	$('body').removeClass('menu-open');
	        }
        });

        $('.menu-toggler').on('click', function (e) {
            $('body').toggleClass('menu-open');
            e.preventDefault();
        });

        /* Search */
        $('#search > button').on('click.search', function (e) {
            if (!$(this).parent().hasClass('open')) {
                $(this).parent().find('input').focus();
                e.preventDefault();
            }
            $(this).parent().toggleClass('open');
        });

        $(document).on('click.search', function (e) {
            var el = $('#search');
            if (!$(e.target).closest($('button', el)).length && e.target != $('input[name="search"]', el)[0]) {
                el.removeClass('open');
            }
        });

        /* Selectall */
        $('input[type="checkbox"].selectall').selectall({
            select: function (items) {
                $('.actions .actions-options').trigger('toggle', [items]);
            }
        });

        /* Actions */
        $('.actions .actions-options').on('toggle', function (e, items) {
            var selected = items.filter(function () {
                return $(this).is(':checked');
            });
            if (selected.length) {
                $(this).removeClass('hidden');
            } else {
                $(this).addClass('hidden');
            }
        });

        /* Thumbs */
        $('.thumb').on('click', function (e) {
            var thumbs = $(this).parent().find('.thumb'),
                checkbox = $(':checkbox', this);

            $(this).toggleClass('selected');
            checkbox.prop('checked', !checkbox.is(':checked'));

            $('.actions .actions-options').trigger('toggle', [$(':checkbox', thumbs)]);

            if (/iPad|iPhone|iPod/.test(navigator.platform)) {
                this.reverse();
            } else {
                TweenLite.to($(this), 0.2, {z: -30, ease: Power2.easeInOut, onComplete: function () {
                    this.reverse();
                }});
            }

            e.stopImmediatePropagation();
        });

        $('.thumb').on('contextmenu', function (e) {
            if (e.which === 3) {
                $('a[data-toggle="dropdown"]', this).dropdown('toggle');
                e.preventDefault();
            }
        });

        $('.thumb').hammer().bind('press', function (e) {
            $('a[data-toggle="dropdown"]', this).dropdown('toggle');
        });

        $('.thumb a[data-toggle="dropdown"]').on('click', function (e) {
            $(this).dropdown('toggle');
            e.stopImmediatePropagation();
        });

        $(document).on('click.thumb', function (e) {
            var that = this,
                thumbs = $('.thumb');

            $.each(thumbs, function () {
                if (!e.target || (e.target !== that && !$(e.target).closest($(this)).length)) {
                    var checkbox = $(':checkbox', this);

                    $(this).removeClass('selected');
                    checkbox.prop('checked', false);

                    $('.actions .actions-options').trigger('toggle', [$(':checkbox', thumbs)]);
                }
            });
        });

        $('form .form-actions').each(function () {
            var org_actions = $(this),
                new_actions = $(org_actions.html()),
                target = $('header .form-actions-container');

            new_actions.find('button[id][type="submit"]').each(function () {
                var new_btn = $(this),
                    org_btn = org_actions.find('#' + new_btn.attr('id'));

                    new_btn
                        .attr('data-id', new_btn.attr('id'))
                        .removeAttr('id')
                        .attr('type', 'button')
                        .on('click', function () {
                            org_btn.trigger('click');
                        });
            });

            target.append(new_actions);
        });

        /**
         * CollectionType functionality
         */
        function addNewToCollectionType(element) {
            var data_target = $(element).data('target');
            var collectionHolder = $('#' + data_target);

            var data_copy_column = $(element).data('copy-column');
            if (data_copy_column != undefined) {
                var children = collectionHolder.children();
                var last_child = children[children.length - 1];
                var selected_option = $(last_child).find(data_copy_column).find('option:selected');
            }

            var prototype = collectionHolder.data('prototype');
            var new_prototype = prototype.replace(/_prototype_name_/g, 'index_' + collectionHolder.children().length);

            var element = $(new_prototype);

            element.find('textarea.autogrow').autogrow();

            if (selected_option != undefined) {
                collectionHolder.append(element);

                if (data_copy_column != undefined) {
                    var input = element.find(data_copy_column);
                    input.val(selected_option.val());

                    var event = jQuery.Event('change');
                    var targets = $(document).find('.collection-type-container ' + '#' + input.attr('id'));
                    event.target = targets[targets.length - 1];

                    $(document).trigger(event);
                }
            }
            else {
                collectionHolder.append(element);
            }
        }

        $(document).on('click', '.collection-type-container .btn-add', function(e) {
            var data_cascade = $(this).data('cascade');

            if (data_cascade != undefined) {
                $('#' + data_cascade + ' .collection-type-container .btn-add').each(function() {
                    addNewToCollectionType(this);
                });
            }
            else {
                addNewToCollectionType(this);
            }

            e.preventDefault();
        });

        $(document).on('click.delete', '.collection-type-container .btn-remove', function(e) {
            var target = $(this).data('target');
    		var related = $(this).data('related');
    		$('#' + target).find('*[data-content="' + related + '"]').remove();

            e.preventDefault();
        });

        /**
    	 * Auto grow textarea
    	 */
    	$('textarea.autogrow').autogrow();
    });
})(jQuery);
