(function ($) {
    $.widget("qusion.layout", {
        options: {
            mode: 'widget',
            prefix: 'qusion-cms-',
            widgetContent: true,
            wrapIgnore: null,
            toolbox: null,
            layout: {
                wrapper: 'wrapper',
                section: 'section',
                sectionEmpty: 'section-empty',
                sectionHover: 'section-hover',
                widget: 'widget',
                widgetReady: 'widget-ready',
                widgetHeader: 'widget-header',
                widgetContent: 'widget-content',
                bar: 'bar',
                placeholder: 'widget-placeholder',
                placeholderEmpty: 'widget-placeholder-empty'
            },
            url: {
                add: '/qusion/page/addWidget'
            },
            local: {
                edit: 'Edit',
                more: 'More',
                dropHere: 'Drop here',
                empty: 'No widgets added to this section <span>Add widgets here</span>'
            }
        },
        _create: function () {
            var self = this, options = self.options, element = this.element;

            self.toolbox = options.toolbox;
            self.pageId = $('meta[name="qusion:page"]').attr("content");

            self._wrap();
            self._activate();
            self._refresh();
        },
        _activate: function () {
            var self = this, options = self.options, element = this.element;
            // activate sorting
            $(".qusion-cms-section").sortable({
                items: ".qusion-cms-widget, .q-toolbox-item",
                connectWith: self._cssClass(options.layout.section),
                forcePlaceholderSize: true,
                forceHelperSize: false,
                helper: 'clone',
                placeholder: self._prefix(options.layout.placeholder),
                revert: 'invalid',
                tolerance: 'pointer',
                cursor: 'move',
                distance: 10,
                handle: self._cssClass(options.layout.widgetHeader),
                over: function (event, ui) {
                    ui.placeholder.parents(self._cssClass(options.layout.sectionEmpty))
                        .addClass(self._prefix(options.layout.sectionHover));
                },
                out: function (event, ui) {
                    ui.placeholder.parents(self._cssClass(options.layout.sectionEmpty))
                        .removeClass(self._prefix(options.layout.sectionHover));
                },
                start: function (event, ui) {
                    // set "DROP HERE" text
                    ui.placeholder.html(options.local.dropHere);
                },
                update: function (event, ui) {
                    //if (ui.item.is('.q-toolbox-item'))
                    //    self._createWidget(ui);
                },
                receive: function (event, ui) {
                    isReceived = true;
                    //console.log($(this).data());
                    var $target = $(this).data('ui-sortable').currentItem;
                    var $source = $(ui.sender);
                    // now you can copy data from source to target
                    $target.data('item', $source.data('item'));
                },
                stop: function (event, ui) {
                    isReceived = false;
                    if (ui.item.is('.q-toolbox-item')) {
                        self._addWidget(ui);
                    }
                    self._refresh();
                }
            }).sortable("disable");

            // activate toolbox
            self.toolbox.find('.q-toolbox-item').draggable({
                helper: "clone",
                revert: "invalid",
                revertDuration: 0,
                zIndex: 2001,
                stack: self._cssClass(options.layout.wrapper),
                iframeFix: true,
                scroll: false,
                appendTo: "body",
                connectToSortable: self._cssClass(options.layout.section),
            });

            // find and create widgets
            element.find(self._cssClass(options.layout.widget)).each(function () {
                self._wrapWidget($(this));
            });

        },
        _refresh: function () {
            var self = this, options = self.options, element = this.element;
            self._careEmptySections();
        },
        _wrap: function () {
            var self = this, options = self.options, element = this.element;
            // we are creating wrapper around page but ignoring toolbox, scripts and 
            // other elements defined by "options.wrapIgnore"
            self.wrapper = element.find(self._cssClass(options.layout.wrapper));
            if (self.wrapper.length == 0) {
                self.wrapper = $('<div />', { 'class': self._prefix(options.layout.wrapper) });
                element.children(':not(script)')
                    .not(self.wrapper)
                    .not(options.wrapIgnore)
                    .not(options.toolbox)
                    .not("script")
                    .wrapAll(self.wrapper);
            }
        },
        _wrapWidget: function (el) {
            var self = this, options = this.options;

            if (el.is(self._cssClass(options.layout.widgetReady)))
                return;

            var model = {
                title: el.data("title"),
                path: el.data("path"),
                scope: el.data("scope")
            };

            // widget content wrapper
            el.addClass(self._prefix(options.layout.widgetReady));
            el.wrapInner('<div class="' + self._prefix(options.layout.widgetContent) + ' clearfix" />');

            // widget header
            var header = $('<div />', { 'class': self._prefix(options.layout.widgetHeader) })
                .prependTo(el);

            // title
            $('<div />', { 'class': self._prefix(options.layout.widgetHeader) + '-title', text: model.title })
                .appendTo(header);

            // button more
            $('<a />')
                .append('<i class="icon-caret-down"></i>')
                .appendTo(header);

            // button edit
            $('<a />')
                .append('<i class="icon-list-ul"></i>')
                .appendTo(header);
        },
        _addWidget: function (ui) {
            var self = this, options = self.options;

            ui.item
                .removeClass('q-toolbox-item')
                .empty()
                .addClass(self._prefix(options.layout.widget));

            // generate data
            var item = ui.item.data('item');
            var data = [];
            for (var key in item) {
                data.push({ "Key": key, "Value": item[key] });
            }

            // wrap with widget elements
            //self._wrapWidget(ui.item);
            // create widget and display it
            //var content = ui.item.find(self._cssClass(options.layout.widgetContent));
            var section = ui.item.parents(self._cssClass(options.layout.section));

            $.ajax({
                type: "POST",
                url: options.url.add,
                data: JSON.stringify({
                    data: data,
                    pageId: self.pageId,
                    title: ui.item.data("title"),
                    section: section.data("section")
                }),
                //success: success,
                //dataType: 'json',
                contentType: 'application/json'
            })
                .done(function (response) {
                    ui.item.append(response);
                    self._wrapWidget(ui.item);
                })
                .fail(function () { alert("error"); });


            //$.post(options.url.add, {
            //    section: section.data("section"),
            //    data: data,
            //    title: ui.item.data("title"),
            //    id: pageId
            //}, function (data) {
            //    console.log(data);
            //});

            // create widget in persistance
            //self._trigger('widgetMove', event, ui);
            //content.load(ui.item.data("path"), function(html) {

            //});
        },
        _getSections: function () {
            var self = this, element = this.element;
            return element.find(self._cssClass(options.layout.section));
        },
        _careEmptySections: function () {
            var self = this, options = self.options, element = this.element;
            // if there are no widgets in section than mark section as empty
            element.find(self._cssClass(options.layout.section))
                .not(':has("' + self._cssClass(options.layout.widget) + '")')
                .addClass(self._prefix(options.layout.sectionEmpty));

            // if there are widgets inside section than we want to remove section empty css class
            element.find(self._cssClass(options.layout.section))
                .has(self._cssClass(options.layout.widget))
                .removeClass(self._prefix(options.layout.sectionEmpty))
                .find(self._cssClass(options.layout.placeholderEmpty)).remove();

            // every empty section has to contain empty placeholder
            element.find(self._cssClass(options.layout.sectionEmpty)).each(function () {
                $(this).empty();
                $('<div />', { html: options.local.empty })
                    .addClass(self._prefix(options.layout.placeholderEmpty))
                    .appendTo($(this));
            });

            // remove section hover class
            element.find(self._cssClass(options.layout.sectionHover))
                .removeClass(self._prefix(options.layout.sectionHover));
        },
        _cssClass: function (input) {
            return "." + this._prefix(input);
        },
        _prefix: function (input) {
            return this.options.prefix + input;
        },
    });
})(jQuery);