/**
 * tinymce a51editor_plugin
 */
(function() {
	tinymce.create('tinymce.plugins.a51editor_image', {
		init : function(ed, url) {
			var plugin = this;
			this.editor = ed;

			// Register commands
			ed.addCommand('a51editor_image', function() {
			  var dialog = null;
			  
			  dialog = ed.theme.showTabbedDialog({
          'title'       : App.lang('Image Dialog'),
			    'tabs'        : {
            'upload_image'          : { 'title' : App.lang('Upload Image'), 'action' : plugin.actionUploadImage },
			      'insert_by_url'         : { 'title' : App.lang('External Image'), 'action' : plugin.actionInsertByUrl }
            // 'choose_existing_image' : { 'title' : App.lang('Choose Existing'), 'action' : plugin.actionChooseExistingImage }
			    },
			    'selected' : 'upload_image',
			    'wide'        : false
			  });
      });
			
			// toggle state of link button
      ed.onNodeChange.add(function(editor, control_manager, current_node, selection_is_collapsed, object) {
  			var control;
        var $current_node = $(current_node);
        var is_img = $current_node.is('img');
  			if (control = control_manager.get('a51editor_image')) {
  			  control.setActive(is_img);
  			} // if
      });

			// Register buttons
			ed.addButton('a51editor_image', {
				title : App.lang('Insert Image'),
				cmd : 'a51editor_image'
			});
		},
		
    /**
     * Insert by url
     *
     * @param Object editor
     */
    actionInsertByUrl : function (editor) {
      var form = editor.theme.renderDialogForm(App.lang('Insert'));
      var fields_wrapper = form.find('div.fields_wrapper');
      var image_url = $('<input type="text" class="input_text" name="href" id="editor_image_url" value="" />').appendTo($('<div class="control_holder"><label class="main_label" for="editor_image_url">' + App.lang('Image URL') + '<em>*</em></label></div>').appendTo(fields_wrapper));
      var dialog = $(this).parents('.flyout_dialog:first');
      
      // initial value
      var node = $(editor.selection.getStart());
      if (node.is('img')) {
        image_url.val(node.attr('src'));
      } // if
      
		  setTimeout(function () {
		    image_url.focus().selectRange(image_url.val().length);
		  }, 100);
      
      // on form submit
      form.submit(function () {
        var image_url_value = $.trim(image_url.val());
        
        // check if url is valid
        if (!App.isValidUrl(image_url_value)) {
          App.Wireframe.Flash.error('Image URL is not in valid format');
          return false;
        } // if
                 
        editor.execCommand('mceInsertContent', false, '<img src="' + image_url_value + '" image-type="external" alt="" />');
        App.widgets.FlyoutDialog.close(dialog);
        return false;
      });
      
      return form;
    },
    
    /**
     * Upload Image action
     *
     * @param Object editor
     */
    actionUploadImage : function (editor) {
      var form = editor.theme.renderDialogForm(App.lang('Upload')).attr('enctype', 'multipart/form-data');
      var fields_wrapper = form.find('div.fields_wrapper');
      var image_file = $('<input type="file" class="input_file" name="attachment" id="editor_image" value="" />').appendTo($('<div class="control_holder"><label class="main_label" for="editor_image">' + App.lang('Choose File') + '<em>*</em></label></div>').appendTo(fields_wrapper));
      var dialog = $(this).parents('.flyout_dialog:first');
      
      form.submit(function () {
        var filename = image_file.val();
        if (!filename) {
          App.Wireframe.Flash.error('File is not selected.');
        } // if
        
        var extension = filename.split('.').pop().toLowerCase();
        // extension = extension ? extension.toLowerCase() : null;
        var allowed_extensions = ['png', 'jpg', 'jpeg', 'gif', 'bmp'];
        if ($.inArray(extension, allowed_extensions) == -1) {
          App.Wireframe.Flash.error('Image is not supported (supported types are :supported_types)', { 'supported_types' : allowed_extensions.join(', ') });
          return false;
        } // if

        App.widgets.FlyoutDialog.startProcessing(dialog);
        form.ajaxSubmit({
          'url' : App.extendUrl(editor.settings.a51theme.attachments_upload_url, { 'async' : 1 }),
          'type' : 'post',
          'dataType' : 'json',
          'success' : function (response) {
            editor.execCommand('mceInsertContent', false, '<img src="' + response.urls.view + '" image-type="attachment" object-id="' + response.id + '" alt="" />');
            App.widgets.FlyoutDialog.stopProcessing(dialog);
            App.widgets.FlyoutDialog.close(dialog);
          },
          'error' : function (response) {
            App.widgets.FlyoutDialog.stopProcessing(dialog);
            if (typeof(response) == 'object' && response) {
              if(response['ajax_message']) {
                var response_message = response.ajax_message;
              } else {
                var response_message = App.Wireframe.Utils.responseToErrorMessage(response);
              } // if
            } else {
              var response_message = App.lang('Unknown error occurred. Please try again later');
            } // if
            App.Wireframe.Events.trigger('async_operation_error', [ response_message, response ]);
          }
        });
        return false;
      });
      
      return form;
    },
    
    /**
     * Choose Existing Image action
     *
     * @param Object editor
     */
    actionChooseExistingImage : function (editor) {
      return 'choose existing';      
    },
    
  	/**
  	 * Function that lists all embeded objects in editor and return it's ID's
  	 * This function is used when data loads into editor and saves from it to determine
  	 * whether some objects are added or removed from editor
  	 *
  	 * @return Object
  	 */
  	getEmbededObjects : function () {
  	  var return_value = {
  	    'type' : 'attachments',
  	    'objects' : []
  	  }; // return
  	  
      $(this.editor.contentDocument).contents().find('img[image-type="attachment"]').each(function () {
        return_value.objects.push(this.getAttribute('object-id'));
      });
      
      return return_value
  	},

		getInfo : function() {
			return {
				longname : 'Insert Image',
				author : 'A51 D.O.O.',
				authorurl : 'http://www.a51dev.com/',
				infourl : 'http://www.a51dev.com/',
				version : tinymce.majorVersion + "." + tinymce.minorVersion
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('a51editor_image', tinymce.plugins.a51editor_image);
})();