/**
 * JQuery RichEdit plugin
 *
 * @author György Kövesdi <samy@rapidforum.hu>
 * @copyright SAMZlab, 2009
 * @since 2009.05.08
 *
 **/

/**
 * richEditor library
 *
 **/
var richEditor = {
  initialized:  false,
  toolbarTimer: false,
  toolbarContainer: false,
  toolbarIcons: 'images/icons/',
  currentSourceEl: false,
  commands:     {
    'bold': {
      icon: 'bold.png',
      desc: 'Vastag'
    },
    'italic': {
      icon: 'italic.png',
      desc: 'Dőlt'
    },
    'underline': {
      icon: 'underline.png',
      desc: 'Aláhúzott'
    },
    'strikethrough': {
      icon: 'strike_trough.png',
      desc: 'Áthúzott'
    },

    'archnor': {
      icon: 'insert_link.png',
      desc: 'Link beszúrása',
      fn: function(){
        $( '.archnor', richEditor.toolbarContainer ).slideDown();
      }
    },

    'insertorderedlist': {
      icon: 'numbered_list.png',
      desc: 'Számozott lista'
    },

    'insertunorderedlist': {
      icon: 'bulleted_list.png',
      desc: 'Felsorolás lista'
    },


    'outdent': {
      icon: 'decrease_indent.png',
      desc: 'Behúzás csökkentése'
    },

    'indent': {
      icon: 'increase_indent.png',
      desc: 'Behúzás növelése'
    },

    'justifyleft': {
      icon: 'align_left.png',
      desc: 'Balra igazított'
    },
    'justifyright': {
      icon: 'align_right.png',
      desc: 'Balra igazított'
    },
    'justifycenter': {
      icon: 'align_center.png',
      desc: 'Középre igazított'
    },
    'justifyfull': {
      icon: 'align_justify.png',
      desc: 'Sorkizárt'
    },

    'undo': {
      icon: 'undo.png',
      desc: 'Visszavonás',
      'class': 'rich-button-undo',
    },
    'redo': {
      icon: 'redo.png',
      desc: 'Újra'
    },
    'source': {
      icon: 'source.png',
      desc: 'Forráskód szerkesztése',
      fn:   function() {
        var _html = $('.rich-editing').html();
        richEditor.currentSourceEl = $('.rich-editing');
        $('#overlay').fadeIn();
        $('#overlay *').click( function(){ return false; } );
        $('#overlay').click( function(){ $(this).fadeOut(); });
        $('#overlay .rich-source').css({ width: $('.rich-editing').css('width'), left: $('.rich-editing')[0].getClientRects()[0].left, top: $('.rich-editing')[0].getClientRects()[0].top }).show().val( _html );
      }
    },
    'save': {
      icon: 'save.png',
      desc: 'tartalom mentése',
      fn:   function() {
        var _html = $('.rich-editing').html();
        var _name = $('.rich-editing').parents('.editable').attr('id').match( /^content-(.*)$/ )[1];
        $.post( FMB.BASE_URL + 'tartalom/mentes', { content: _html, 'page': _name }, function() {
          $( '.message', richEditor.toolbarContainer ).slideDown().html('sikeres mentés');
          setTimeout( function() {
            $( '.message', richEditor.toolbarContainer ).slideUp();
          }, 2000 );
        } );
      }
    }
  },

  initButtons: function() {
    for( var _cmd in richEditor.commands ) {
      var _options = richEditor.commands[_cmd];
      $( richEditor.toolbarContainer ).append('<img class="rich-button ' + _options['class'] + '" cmd="' + _cmd + '" src="' + richEditor.toolbarIcons + _options.icon +'" title="' + _options.desc + '"/>');
    }
    $( richEditor.toolbarContainer )
      .append('<div class="message">&nbsp;</div>')
      .append('<div class="archnor"><input type="text" value="http://"/><button class="insert">BESZÚRÁS</button><button class="cancel">MÉGSEM</button></div>');
    $( '.rich-button', richEditor.toolbarContainer ).click( function() {
      richEditor.doCmd( $(this).attr('cmd') );
      $('.rich-editing').click();
      return false;
    });
  },

  // event handlers
  onDblClick: function( e ) {
    clearTimeout( richEditor.toolbarTimer );
    if ( !$( this ).hasClass('rich-editing') ) $('.rich-editing').blur();
    $('#rich-tools').fadeIn('normal').animate({ left: this.getClientRects()[0].left, top: this.getClientRects()[0].top - 40 });
    $(this)
      .addClass('rich-editing')
      .attr('contenteditable', true ).focus();
  },

  onBlur: function( e ) {
    var _el = $(this);
    richEditor.toolbarTimer = setTimeout( function(){
      _el
      .attr('contenteditable', false )
      .removeClass('rich-editing');
      if( $('.rich-editing').length == 0 ) $('#rich-tools').fadeOut();
    }, 500 );
  },

  onMouseUp: function( e ) {
  },

  doCmd: function( cmd ) {
    if ( !richEditor.commands[ cmd ] || !richEditor.commands[ cmd ].fn ) {
      document.execCommand( cmd, false, null )
    } else {
      richEditor.commands[ cmd ].fn();
    }
  }
};

/**
 * create extensions
 **/
( function($){

  $.extend( $.fn, {

  positionedOffset: function() {
    element = this[0];
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if (element.tagName == 'BODY') break;
        var p = $(element).css('position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return {left: valueL, top: valueT};
  },

  moveToOverlay: function() {
    this.each( function() {
      var newel_, _el = $( this ), pos;
      pos = _el.positionedOffset();
      newel = _el.clone().css( {'position':'absolute', left: pos.left + 'px', top: pos.top + 'px' } ).appendTo('#overlay');
      if ( !newel[0].style.width && newel.css('display') == 'block' ) {
        newel.css({'width': '100%'});
      } else {
        console.log( newel.css('width') );
      }
    } );
  },

  /**
   * RichEdit plugin
   **/
  rich: function( options ) {
    if ( typeof options == 'function' ) {
      options = { 'complete': options };
    }
    if ( typeof options == 'undefined' ) {
      options = {};
    }
    this.addClass( 'rich-editable' );
    this
      .blur( richEditor.onBlur )
      .mouseup( richEditor.onMouseUp );

    if ( !richEditor.initialized ) {
      // init tools box
      $('body').append('<div id="rich-tools">&nbsp;</div>');
      richEditor.toolbarContainer = $('#rich-tools');
      richEditor.initButtons();
      // initialize events
      $('.rich-editable')
        .live( 'click',    richEditor.onDblClick      );
      $('#overlay textarea.rich-source').change( function() {
        richEditor.currentSourceEl.html( this.value );
      });
      //$('body').click( function(){ richEditor.toolbarTimer = setTimeout( "$('.rich-editing').blur()", 1000 ) });
      richEditor.initialized = true;
    }
    return this;
  },

  unrich: function() {
    this.removeClass( 'richEditable' );
  }

} ) } )(jQuery);
