/**
 * jQuery.a51editor
 * - custom made wysiwyg editor
 *
 * Copyright (c) 2009 Goran Radulovic - goran.radulovic@gmail.com | http://www.goranradulovic.com
 * closed source, do not redistribute
 *
 * Useful resources
 * @link http://www.quirksmode.org/dom/execCommand.html - quirksmode article about contenteditable/designmode commands and crosbrowser compatibilities
 * @link https://developer.mozilla.org/En/Rich-Text_Editing_in_Mozilla - article about contenteditable/designmode commands in mozilla firefox
 * @link http://accessgarage.wordpress.com/2009/05/08/how-to-hack-your-app-to-make-contenteditable-work/ - fixes for common problems with contenteditable
 * @link http://blog.cms-schulze.de/2009/07/09/work-around-gecko-contenteditable-bug-436703/ workaround for copy paste bug
 *
 * @author Goran Radulovic <goran.radulovic@gmail.com>
 */
(function($) {
  
  /**
   * Public methods
   * 
   * @var Object
   */
  var public_methods = {
      
    /**
     * Initialise editor
     * 
     * @param Object options
     *      object
     *      interface
     * @returns jQuery
     */
    init : function(options) {
      return this.each(function () {
        var wrapper = $(this);
        var wrapper_dom = this;
        var settings = jQuery.extend({}, defaults, options);
                
        var textarea_id = wrapper.attr('id') + '_textarea';
        var textarea = $('<textarea id="' + textarea_id + '" name="' + settings.name + '" class="visual_editor_textarea">' + (settings.value ? settings.value : '') + '</textarea>').appendTo(wrapper);
        
        if (options.required) {
          textarea.attr('required', 'required');
        } // if

        tinymce.baseURL = get_proxy_url('');
        
        var main_menu_buttons = settings.buttons ? settings.buttons : [
          'bold',
          'italic',
          'underline',
          'strikethrough',
          'separator',
          'a51editor_alignment_left',
          'a51editor_alignment_center',
          'a51editor_alignment_right',
          'separator',
          'blockquote',
          'a51editor_mark_note',
          'a51editor_mark_updated',
          'a51editor_mark_important',
          'separator',
          'insertunorderedlist',
          'insertorderedlist',
          'separator',
          'a51editor_link',
          'a51editor_image',
          'a51editor_code',
          'a51editor_table'
        ];
        
        var additional_buttons = settings.additional_buttons ? settings.additional_buttons : [];        
        var all_buttons = main_menu_buttons.concat(additional_buttons);
        
        var plugins = settings.plugins ? settings.plugins : [
          'a51editor_headings',
          'a51editor_mark',
          'a51editor_link',
          'a51editor_lists',
          'a51editor_image',
          'a51editor_code',
          'a51editor_alignment',
          'table',
          'a51editor_table',
          'a51editor_macros',          
          'tabfocus',
          'lists',
          'paste'
        ];

        var init_options = {
          mode                      : 'exact',
          elements                  : textarea_id,
          theme                     : 'a51editor',
          editor_css                : settings.editor_css,
          plugins                   : plugins.join(','),
          buttons                   : all_buttons,
          main_menu_buttons         : main_menu_buttons,
          extended_valid_elements   : settings.whitelisted_tags,
          inline_styles             : false,
          force_p_newlines          : true,
          gecko_spellcheck          : true,
          browsers                  : "msie,gecko,opera,safari",
          remove_linebreaks         : true,
          apply_source_formatting   : false,
          relative_urls             : false,
          absolute_urls             : true,
          convert_urls              : false,
          convert_newlines_to_brs   : false,
          object_resizing           : false,
          fix_list_elements         : true,
          width                     : 'auto',
          height                    : 'auto',
          language_load             : false,
          tab_focus                 : ':prev,:next',
          visual                    : false,
          entity_encoding           : 'raw',
          paste_block_drop          : true,
          a51theme                  : {
            main_script_url             : App.Config.get('homepage_url'),
            embeded_name                : settings.embeded_name ? settings.embeded_name : 'embeded_objects',
            attachments_upload_url      : settings.attachments_upload_url,
            vertical_resize             : settings.vertical_resize ? settings.vertical_resize : false,
            add_script_url              : settings.add_script_url,
            edit_script_url             : settings.edit_script_url,
            view_script_url             : settings.view_script_url,
            quick_search_url            : settings.quick_search_url,
            min_height                  : 150,
            max_height                  : 500
          }
        };

        // forbid pasting images from clipboard in safari
        init_options['paste_preprocess'] = function(pl, o) {
          if ($.browser.safari) {
            if (o.content && o.content.indexOf('webkit-fake-url') != -1) {
              o.content = '';
            } // if
          } // if

          if ($.browser.mozilla) {
            o.content = o.content.replace(/<img([^>]*)\ssrc=(['"])data\:image(?:[^\2\/]*\/)*([^\2]+)\2>/gi, '');
          } // if
        }; // paste_preprocess
        
        tinyMCE.init(init_options);
        
        // we need to show textarea, but make it invisible so html validation could pass
        textarea.show().css({
          'position'    : 'absolute',
          'height'      : '1px',
          'overflow'    : 'hidden',
          'width'       : '20px',
          'top'         : '10px',
          'left'        : '20px',
          'border'      : '0px',
          'background'  : 'transparent',
          'box-shadow'  : 'none'
        }).focus(function () {
          // when field is focused, focus the editor
          tinymce.get(textarea_id).focus();
          if (!textarea.val()) {
            textarea.addClass('validation_error');
          } // if
        });
      });
    }
  };
  
  var get_proxy_url = function (path) {
    return App.Config.get('homepage_url')  + '/proxy.php?proxy=visual_editor_resources&module=visual_editor&path=' + path;
  }; // get_proxy_url
  
  ////////////////////////////////////////////////////////// PLUGIN INITIAL DATA ///////////////////////////////////////////////////////////  
  
  /**
   * Plugin name
   * 
   * @var String
   */
  var plugin_name = 'visualEditor';
  
  /**
   * Default options
   *
   * @var Object
   */
  var defaults = {
    auto_save : true
  };
        
  ///////////////////////////////////////////////////////// PLUGIN FRAMEWORK STUFF /////////////////////////////////////////////////////////
  /**
   * Register jQuery plugin and handle public methods
   * 
   * @param mixed method
   * @return null
   */
  $.fn[plugin_name] = function(method) { 
    if (public_methods[method]) {
      return public_methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return public_methods.init.apply(this, arguments);
    } else {
      $.error('Method ' +  method + ' does not exist in jQuery.' + plugin_name);
    } // if
  };

})(jQuery);