var ContentManager = Class.extend({
    init : function(iframeNode){
        this.iframeNode = iframeNode;
    },
    enable: function()
    {
    	this.enableDraggableToolBar();
        this.enableDroppableElements();
        this.enableWidgets();
        this.enableOptions();
        this.appendCSS();
    },
    disable: function()
    {
        this.disableDroppableElements();
        this.disableDraggableToolBar();
        this.disableWidgets();
        this.disableOptions();
        this.removeCSS();
    },
    enableContentMode: function() {
        CSTemplate.disable();
        jQuery('body', jQuery(this.iframeNode).contents())
            .removeClass(ContentManager.STRUCTURE_MODE_CLASS)
            .addClass(ContentManager.CONTENT_MODE_CLASS);
        this.enable();
    },
    disableContentMode: function() {
        CSTemplate.enable();
        jQuery('body', jQuery(this.iframeNode).contents())
            .removeClass(ContentManager.CONTENT_MODE_CLASS)
            .addClass(ContentManager.STRUCTURE_MODE_CLASS);
        this.disable();
    },
    enableDraggableToolBar: function() {
        var _self = this;
        jQuery('.'+ContentManager.TOOLBAR_DRAGGABLE_WIDGETS).CSDraggable({
            render: function() {
                var selector = 'cswidget-'+jQuery(this).data('widget-id');
                jQuery.CSDragAndDropStore.setData(ContentManager.STORE_KEY_SELECTOR, '#'+selector);
                jQuery.CSDragAndDropStore.setData(ContentManager.STORE_KEY_ID, jQuery(this).data('widget-id'));
                return '<div id="'+selector+'" class="cswidget-loading" ></div>';
            },
            dragstart: function() {
                jQuery('body', _self.iframeNode.contents()).addClass(ContentManager.BODY_SHOW_HOT_ZONES_CLASS);
            },
            dragend: function() {
                jQuery('body', _self.iframeNode.contents()).removeClass(ContentManager.BODY_SHOW_HOT_ZONES_CLASS);
            }
        });
    },
    disableDraggableToolBar: function() {
        jQuery('.'+ContentManager.TOOLBAR_DRAGGABLE_WIDGETS).CSDraggable('destroy');
    },
    enableDroppableElements: function() {
        jQuery(this.iframeNode).contents().find(Layout.TAG).each(function(){
            var element = jQuery(this),
                layout = element.data('object');

            layout.enableContentMode();

            if(layout.locked) {
                element.addClass(ContentManager.LAYOUT_LOCKED_CLASS);
            }

            if(element.find(Layout.TAG).length === 0) {
                layout
                    .getEditableZone()
                    .CSDroppable({drop: ContentManager.prototype.dropCallback})
                    .addClass(ContentManager.LAYOUT_HOT_ZONE_CLASS);
            }
        });
    },
    disableDroppableElements: function() {
        jQuery(Layout.TAG ,jQuery(this.iframeNode).contents())
            .CSDroppable('destroy')
            .removeClass(ContentManager.LAYOUT_LOCKED_CLASS)
            .removeClass(ContentManager.LAYOUT_HOT_ZONE_CLASS)
            .removeClass(ContentManager.PAST_ELEMENT_CLASS)
            .removeClass(ContentManager.FUTURE_ELEMENT_CLASS);
    },
    dropCallback: function(event, item) {
        var widget = jQuery(item).data('object');
        var layout = jQuery(this).closest(Layout.TAG).data('object');
        var selector = jQuery.CSDragAndDropStore.getData(ContentManager.STORE_KEY_SELECTOR);
        var widgetId = jQuery.CSDragAndDropStore.getData(ContentManager.STORE_KEY_ID);

        jQuery.CSDragAndDropStore.removeData(ContentManager.STORE_KEY_SELECTOR);
        jQuery.CSDragAndDropStore.removeData(ContentManager.STORE_KEY_ID);

        if(!widget) {
            widget = new Widget(widgetId, layout);
            widget.getHtml(selector);
        } else {
            widget.setLayout(layout);
        }

        layout.update(true);
    },
    disableWidgets: function() {
        jQuery(Widget.TAG , jQuery(this.iframeNode).contents()).each(function() {
            var widget = jQuery(this).data('object');
            widget.disable();
        });
    },
    enableWidgets: function() {
        jQuery(Widget.TAG , jQuery(this.iframeNode).contents()).each(function() {
            var widget = jQuery(this).data('object');
            if(typeof widget !== 'undefined') {
                widget.enable();
            }
        });
    },
    export: function() {

        var item = {};

        CSTemplate.disable();
        this.disable();

        item.widgets = [];
        jQuery(Widget.TAG, this.getTarget()).each(function(){
            item.widgets.push(
                jQuery(this).data('object').export()
            );
        });

        item.layouts = CSTemplate.exportContent();

        if (CSTemplate.mode === Template.CONTENT_MODE) {
        	this.enable();
        } else {
        	CSTemplate.enable();
        }

        return item;
    },
    json: function() {
        return JSON.stringify(this.export());
    },
    getTarget: function() {
        return this.iframeNode.contents();
    },
    enableOptions: function() {
        var _self = this;
        jQuery('.'+ContentManager.SHOW_ALL_LAYOUTS_BUTTON_CLASS)
            .off('click')
            .on('click', function() {
                var body = jQuery('body', _self.iframeNode.contents());
                if(body.hasClass(ContentManager.BODY_SHOW_ALL_ZONES_CLASS)) {
                    body.removeClass(ContentManager.BODY_SHOW_ALL_ZONES_CLASS);
                    jQuery(this).removeClass('active');
                } else {
                    body.addClass(ContentManager.BODY_SHOW_ALL_ZONES_CLASS);
                    jQuery(this).addClass('active');
                    jQuery(Layout.TAG, _self.iframeNode.contents()).each(function(){
                        try {
                            jQuery(this).data('object').enableContentToolbar();
                        } catch(Exception) {
                            throw "Layout object not found.";
                        }
                    });

                    jQuery(Widget.TAG,  _self.iframeNode.contents()).trigger(Widget.LOAD_CKEDITOR_EVENT);
                }
            })
            .show();
    },
    disableOptions: function() {
        var body = jQuery('body', this.iframeNode.contents());
        body.removeClass(ContentManager.BODY_SHOW_ALL_ZONES_CLASS);
        jQuery('.'+ContentManager.SHOW_ALL_LAYOUTS_BUTTON_CLASS)
            .hide()
            .off('click')
            .removeClass('active');
    },
    editDatesCallback: function(element) {
        var _self = element;

        return function() {
            var modal = new Modal();
            modal.render(Widget.MODAL_SMALL_SPECIFIC_CLASS);

            modal.addContent('<div class="csmodal-title">'+ Translator.trans("cs_admin.designer.modal.dateSelection") +'</div>' +
            '<div class="form-group"><div class="col-md-12">'+
            '<div class="input-group input-large date-picker input-daterange">'+
            '<input type="text" class="form-control" name="from" id="'+Widget.START_DATE_ID+'" readonly="readonly" placeholder="aaaa-mm-dd hh:mm"><span class="input-group-addon remove-date"></span>'+
            '<span class="input-group-addon">'+
            Translator.trans('cs_core.label.date_range_mid')+' </span>'+
            '<input type="text" class="form-control" name="to" id="'+Widget.END_DATE_ID+'" readonly="readonly" placeholder="aaaa-mm-dd hh:mm"><span class="input-group-addon remove-date"></span>'+
            '</div>'+
            '<span class="help-block">'+
            Translator.trans("cs_admin.designer.modal.dateSelectionHelp") + '</span>' +
            '</div>'+
            '</div>');

            modal.addOption(Modal.ACCEPT_OPTION,null,null,'btn mainBtn btn-save', function() {
                var startDate = jQuery(modal.getTarget()).find('#'+Widget.START_DATE_ID).val();
                var endDate = jQuery(modal.getTarget()).find('#'+Widget.END_DATE_ID).val();

                _self.startDate = startDate;
                _self.endDate = endDate;

                var startDateObject = startDate ? jQuery(modal.getTarget()).find('#'+Widget.START_DATE_ID).data("datetimepicker").date : null;
                var endDateObject = endDate ? jQuery(modal.getTarget()).find('#'+Widget.END_DATE_ID).data("datetimepicker").date : null;

                _self.getTarget().removeClass(ContentManager.PAST_ELEMENT_CLASS+' '+ContentManager.FUTURE_ELEMENT_CLASS);

                if(startDateObject !== null && startDateObject > new Date()) {
                    _self.getTarget().addClass(ContentManager.FUTURE_ELEMENT_CLASS);
                } else if(endDateObject !== null && endDateObject < new Date()){
                    _self.getTarget().addClass(ContentManager.PAST_ELEMENT_CLASS);
                }

                if(jQuery(_self.getTarget()).is(Layout.TAG)) {
                    jQuery(_self.getTarget()).data('object').update(true);
                } else {
                    _self.getLayout().update(true);
                }

                modal.remove();
            });

            modal.addOption(Modal.CANCEL_OPTION, null, null, 'btn defaultBtn btn-cancel', function() {
                modal.remove();
            });

            jQuery(modal.getTarget()).appendTo('body').show();

            jQuery('#'+Widget.START_DATE_ID, modal.getTarget()).val(_self.startDate).datetimepicker({
                autoclose: true,
                language: CSTemplate.defaultLocale.locale
            }).on("changeDate", function (event) {
                jQuery('#'+Widget.END_DATE_ID, modal.getTarget()).data("datetimepicker").setStartDate(event.currentTarget.value);
            });

            jQuery('#'+Widget.END_DATE_ID, modal.getTarget()).val(_self.endDate).datetimepicker({
                autoclose: true,
                language: CSTemplate.defaultLocale.locale

            }).on("changeDate", function (event) {
                jQuery('#'+Widget.START_DATE_ID, modal.getTarget()).data("datetimepicker").setEndDate(event.currentTarget.value);
            });

            jQuery('.remove-date', modal.getTarget()).on('click', function() {
                jQuery(this)
                    .prev()
                    .val('')
                    .trigger('changeDate')
                    .data('datetimepicker')
                    .update();
            });
            modal.allowCancel();

        };
    },
    appendCSS: function() {
        for(var css in CSTemplate.css) {
            CSTemplate.css[css].append();
        }
    },
    removeCSS: function() {
        for(var css in CSTemplate.css) {
            CSTemplate.css[css].remove();
        }
    },
    cleanLayouts: function() {
        jQuery(Layout.TAG ,jQuery(this.iframeNode).contents())
            .removeClass(ContentManager.LAYOUT_LOCKED_CLASS)
            .removeClass(ContentManager.LAYOUT_HOT_ZONE_CLASS)
            .removeClass(ContentManager.PAST_ELEMENT_CLASS)
            .removeClass(ContentManager.FUTURE_ELEMENT_CLASS);
    },
    renderWidgets: function() {
        var widgetQueue = new WidgetQueue();
        jQuery(Widget.TAG).each(function() {
            widgetQueue.enqueue(jQuery(this));
        });
    }
});

ContentManager.TOOLBAR_DRAGGABLE_WIDGETS = 'draggable-widget';
ContentManager.STORE_KEY_ID = 'widget_drop_id';
ContentManager.STORE_KEY_SELECTOR = 'widget_drop_selector';
ContentManager.CONTENT_MODE_CLASS = 'cs-vce';
ContentManager.STRUCTURE_MODE_CLASS = 'cs-vle';
ContentManager.LAYOUT_LOCKED_CLASS = 'csl-locked';
ContentManager.LAYOUT_HOT_ZONE_CLASS = 'csl-hot';
ContentManager.BODY_SHOW_HOT_ZONES_CLASS = 'cs-vce-hot';
ContentManager.SHOW_ALL_LAYOUTS_BUTTON_CLASS = 'csd-show-all';
ContentManager.PAST_ELEMENT_CLASS = 'csd-past-element';
ContentManager.FUTURE_ELEMENT_CLASS = 'csd-future-element';
ContentManager.BODY_SHOW_ALL_ZONES_CLASS = 'cs-vce-show-all';
