"use strict";

/*globals $, jQuery, document, Cookie, DUMAS */

(function () {

    function click(root, cookie, cookieKey) {
        return function () {
            var opening = root.hasClass('frameClosed');
            if (cookie) {
                if (opening) {
                    cookie.remove(cookieKey);
                } else {
                    cookie.set(cookieKey, '1');
                }
            }

            if (opening) {
                root.removeClass('frameClosed').addClass('frameOpen');
            } else {
                root.removeClass('frameOpen').addClass('frameClosed');
            }
        };
    }

    function handleHtml(root) {
        $('.frame:not(.done)')
            .addClass('done')
            .find('.controller').each(function () {
                var root, control, settings, cookie;
                control = $(this);
                root = control.parents('.l');

                settings = root.settings('cookieName, cookiePath, cookieKey');
                if (settings.cookieName && settings.cookiePath && settings.cookieKey) {
                    cookie = new Cookie({
                        name: settings.cookieName,
                        path: settings.cookiePath,
                        expires: 3650 //10 years
                    });

                    if (cookie.get(settings.cookieKey)) {
                        root.removeClass('frameOpen').addClass('frameClosed');
                    }
                }
                control.click(click(root, cookie, settings.cookieKey));
            });
    }

    DUMAS.registerModule({
        name: 'frame',
        handleHtml: handleHtml,
        first: true
    });

    //simple module to show things with javascript (no FOUC)
    DUMAS.registerModule({
        name: 'jsShow',
        handleHtml: function (root) {
            root
            .find('.jsFadeIn')
                .removeClass('jsFadeIn')
                .css({
                    opacity: 0,
                    visibility: 'visible'
                }).animate({
                    opacity: 1.0
                }, 'fast')
                .end()
            .find('.jsShow, .jsPopIn')
                .removeClass('jsShow')
                .removeClass('jsPopIn')
                .show();
        },
        last: true
    });
}());