var Actions = Class.extend({
	init: function(target, template)
	{
		this.target = target;
		this.template = template;
		this.needSave = false;
		this.enable(true);
	},
	getTarget: function()
	{
		return this.target;
	},
	getTemplate: function()
	{
		return this.template;
	},
	enable: function(init)
	{
		this.cancel(true, init);
		this.save(
			true,
			init
		);
		this.publish(
            true,
			init
		);
		if (init) {
			jQuery(document)
				.off('keydown')
				.keydown(function(event){
					var found = false;
					if (
						(event.ctrlKey || event.metaKey) &&
						(event.which == 115 || event.which == 83)
					) {
						jQuery(
							'.'+Actions.SAVE_CLASS, $this.getTarget()
						).click();
						found = true;
					} else if (
						(event.ctrlKey || event.metaKey) && event.shiftKey &&
						(event.which == 115 || event.which == 83)
					) {
						jQuery(
							'.'+Actions.PUBLISH_CLASS, $this.getTarget()
						).click();
						found = true;
					} else if (
						(event.ctrlKey || event.metaKey) &&
						(event.which == 102 || event.which == 70)
					) {
						jQuery(
							'.csd-middle .widgets-wrapper:visible .search input'
						).focus();
						found = true;
					}
					if (found) {
						event.preventDefault();
					}

					return !found;
				});
		}

        jQuery('body').removeClass(Template.LOADING_CLASS);
	},
	disable: function()
	{
        jQuery('body').addClass(Template.LOADING_CLASS);
        this.cancel(false);
		this.save(false);
		this.publish(false);
	},
	refresh: function(needSave)
	{
		var $this = this;

		if ($this.needSave != needSave) {
			$this.needSave = needSave;
			if ($this.needSave) {
				jQuery(window).on('beforeunload', function(event){
					var text = Translator.trans('cs_admin.designer.confirm');

					if (event) {
						event.returnValue = text;
					}

					return text;
				});
				$this.save(true);
				$this.publish(true);
			} else {
				jQuery(window).off('beforeunload');
				//$this.save(false);
				//$this.publish(false);
			}
		}
	},
	cancel: function(enable, callBack)
	{
		var $this = this;
		var item = jQuery(
			'.'+Actions.CANCEL_CLASS, $this.getTarget()
		);
		if (enable) {
			item.removeClass(Actions.DISABLED_CLASS);
		} else {
			item.addClass(Actions.DISABLED_CLASS);
		}
		if (callBack) {
			item.off('click');
			item.click(function(event){
				var closeWindow;

				event.preventDefault();

				if (!jQuery(this).hasClass(Actions.DISABLED_CLASS)) {
					closeWindow = !$this.needSave;
					if (!closeWindow) {
						closeWindow = confirm(
							Translator.trans('cs_admin.designer.confirm')
						);
						if (closeWindow) {
							jQuery(window).off('beforeunload');
						}
					}

					if (closeWindow) {

						BlockContent.unBlockContent();

						if (window.opener) {
							window.close();
						} else {
							window.location.href = $this.getTarget().data('cancelUrl');
						}
					}
				}
			});
		}
	},
	save: function(enable, callBack)
	{
		var $this = this;
		var item = jQuery(
			'.'+Actions.SAVE_CLASS, $this.getTarget()
		);
		if (enable) {
			item.removeClass(Actions.DISABLED_CLASS);
            if(item.parent().is('.btn-group')) {
                item.next().removeClass(Actions.DISABLED_CLASS);
            }
		} else {
			item.addClass(Actions.DISABLED_CLASS);
            if(item.parent().is('.btn-group')) {
                item.next().addClass(Actions.DISABLED_CLASS);
            }
		}
		if (callBack) {
			if(item.parent().is('.btn-group')) {
				item = jQuery(item.add(item.siblings('ul').children()));
			}

			item.off('click').click(function(event, publish, locale){
				event.preventDefault();
				if (!jQuery(this).hasClass(Actions.DISABLED_CLASS)) {

					var action = $(event.target).data("action"),
						modal = new Modal();

					/*locale = typeof locale !== 'undefined' ? locale : $this.getTemplate().getDefaultLocale(true);*/
					locale = (locale === null || typeof locale === 'undefined') ? null : locale;

					$this.disable();

					jQuery.ajax({
						'type': 'post',
						'url': $this.getTarget().data('saveUrl'),
						'data': {
							'structure': $this.getTemplate().json(),
							'content': $this.getTemplate().getContentManager().json(),
							'publish': (publish ? 1 : 0),
							'locale': locale
						},
						beforeSend: function() {
							if (action === "save-preview-dates") {

								modal.render();
								modal.render(Widget.MODAL_SMALL_SPECIFIC_CLASS);
								modal.addContent('<div class="csmodal-title">Selecciona una data</div>' +
									'<div class="form-group"><div class="col-md-12">'+
									'<div class="input-group input-large date-picker">'+
									'<input type="text" class="form-control" name="from" id="preview-date" readonly="readonly" placeholder="dd/mm/aaaa hh:mm"><span class="input-group-addon remove-date"></span>'+
									'</div>'+
									'</div>');

								modal.addOption(Modal.ACCEPT_OPTION, null, null, 'btn mainBtn btn-save disabled', function () {
									var url = $(event.target).data("url");
									var date = jQuery('#preview-date', modal.getTarget()).val();
									url = ComitiumUtils.addURLParameter(url, "previewDate", date);
									goToPreview(url);
									modal.remove();
									window.location.reload();
								});

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

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

								jQuery('#preview-date', modal.getTarget()).datetimepicker({
									autoclose: true,
									language: CSTemplate.defaultLocale.locale
								});
							}
						},
						'complete': function(response){
							$this.enable(response.status == 200);
							if (response.status == 200) {
								$this.getTemplate()
									.resetUpdate();

								if (action === "save-preview") {
									goToPreview($(event.target).data("url"));
									window.location.reload();
								} else if (action === "save-preview-dates") {
									jQuery(modal.getTarget()).find('.btn-save').removeClass("disabled");
								}
								else if (action === "save-reload"){
									window.location.reload();
								} else {
									jQuery(
											'.'+Actions.CANCEL_CLASS, $this.getTarget()
									).click();
								}

								BlockContent.unBlockContent();
							}
						}
					});
				}
			});

			var goToPreview = function(url){
				window.open(url, "_blank");
			};
		}
	},
	publish: function(enable, callBack)
	{
		var $this = this;
		var item = jQuery(
			'.'+Actions.PUBLISH_CLASS, $this.getTarget()
		);
		if (enable) {
			item.removeClass(Actions.DISABLED_CLASS);
            if(item.parent().is('.btn-group')) {
                item.next().removeClass(Actions.DISABLED_CLASS);
            }
		} else {
			item.addClass(Actions.DISABLED_CLASS);
            if(item.parent().is('.btn-group')) {
                item.next().addClass(Actions.DISABLED_CLASS);
            }
		}
		if (callBack) {
            if(item.parent().is('.btn-group')) {
                item = jQuery(item.add(item.siblings('ul').children()));
            }

			item.off('click').click(function(event){
				event.preventDefault();
                var locale = $(event.target).data('locale');
                /*if(locale === null || typeof locale === 'undefined') {
                    var template = $this.getTemplate();
                    var locales = template.locales.concat([template.defaultLocale]);
                    locale = '';
                    for(var i = 0; i < locales.length; i++) {
                        locale += locales[i].locale;
                        if(i !== locales.length-1){
                            locale+=',';
                        }
                    }
                }*/
				jQuery(
					'.'+Actions.SAVE_CLASS, $this.getTarget()
				).trigger(event, [true, locale]);
			});
		}
	}
});
Actions.DISABLED_CLASS = 'disabled';
Actions.CANCEL_CLASS = 'btn-cancel';
Actions.SAVE_CLASS = 'btn-save';
Actions.PUBLISH_CLASS = 'btn-publish';
