/**
 * WYSIWYG - jQuery plugin 1.0
 *
 * Copyright (c) 2007 Juan M Martinez
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
(function( $ )
{
  $.fn.document = function()
  {
    var element = this[0];
    if ( element.nodeName.toLowerCase() == 'iframe' )
      return element.contentWindow.document;
      /*
      return ( $.browser.msie )
        ? document.frames[element.id].document
        : element.contentWindow.document // contentDocument;
       */
    else
      return $(this);
  };

  $.fn.wysiwyg = function( options ) // Первое, куда мы попадаем
  {
    var options = $.extend({
      debug : false,
      html  : '<'+'?xml version="1.0" encoding="UTF-8"?'+'><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" href="' + W_CSS + 'jquery.Wysiwyg.css" type="text/css" media="screen" /></head><body>INITIAL_CONTENT</body></html>'
    }, options);

    return this.each(function()
    {
      Wysiwyg(this, options);
    });
  };

  function Wysiwyg( element, options )  // вызывается из $.fn.wysiwyg (element - исходный элемент, options - переданные опции)
  {
    /*    return this instanceof Wysiwyg
      ? this.init(element, options)
      : new Wysiwyg(element, options);
*/
		if(this instanceof Wysiwyg){    // Если это один из объектов Wysiwyg
       this.init(element, options); // то проводим инициализацию
		}
		else{                           // Если это один из объектов Wysiwyg
			new Wysiwyg(element, options);// то создаем объект Wysiwyg с соответствующими параметрами
		}
		return this;
      
  }

  $.extend(Wysiwyg.prototype,
  {
    original : null,
    options  : {},

    element  : null,
    editor   : null,

    init : function( element, options )
    {
      options['wysiwygType'] = options['wysiwygType'] || false; // запоминаем тип редактора (служит для определения комплектации)
      this.editor = element; //Запоминаем исходный элемент textarea
      this.options = options || {}; // запоминаем настройки

      var newX = element.width || element.clientWidth; //определяем ширину и высоту исходного элемента (textarea)
      var newY = element.height || element.clientHeight;

      if ( element.nodeName.toLowerCase() == 'textarea' ) // если исходный элемент именно textarea
      {
        this.original = element;  // запоминаем орининальный элемент именно как исходный textarea

        var editor = this.editor = $('<iframe></iframe>').css({
          minHeight : ( newY - 8 ).toString() + 'px',
          width   : ( newX - 8 ).toString() + 'px'
        }).attr('id', $(element).attr('id') + 'IFrame');

        if ( $.browser.msie )
        {
          this.editor
            .css('height', ( newY ).toString() + 'px');

          /**
          var editor = $('<span></span>').css({
            width   : ( newX - 8 ).toString() + 'px',
            height  : ( newY - 8 ).toString() + 'px'
          }).attr('id', $(element).attr('id') + 'IFrame');

          editor.outerHTML = this.editor.outerHTML;
           */
        }
      }
      var panel = this.panel = $('<ul></ul>').addClass('panel');
      this.appendMenu('bold', {title: 'жирный'});
      this.appendMenu('italic', {title: 'курсив'});
      this.appendMenu('strikeThrough', {title: 'зачеркнутый'});
      this.appendMenu('underline', {title: 'подчеркнутый'});

      if(options['wysiwygType'] != 'comment'){
        this.appendMenuSeparator();
        this.appendMenu('justifyLeft', {title: 'по левому краю'});
        this.appendMenu('justifyCenter', {title: 'по центру'});
        this.appendMenu('justifyRight', {title: 'по правому краю'});
        this.appendMenu('justifyFull', {title: 'по ширине'});
      
        this.appendMenu('indent', {title: 'увеличить отступ'});
        this.appendMenu('outdent', {title: 'уменьшить отступ'});
      
        this.appendMenuSeparator();
        this.appendMenu('subscript', {title: 'подстрочный'});
        this.appendMenu('superscript', {title: 'надстрочный'});
      }
      this.appendMenuSeparator();
      this.appendMenu('undo', {title: 'отменить'});
      this.appendMenu('redo', {title: 'вернуть'});

      this.appendMenuSeparator();
      this.appendMenu('insertOrderedList', {title: 'нумерованный список'});
      this.appendMenu('insertUnorderedList', {title: 'маркированный список'});
      this.appendMenu('insertHorizontalRule', {title: 'черта'});

      if ( $.browser.msie )
      {
        this.appendMenu('createLink', {title: 'гиперссылка'}, null, function( self ) { self.editorDoc.execCommand('createLink', true, null); });
        //this.appendMenu('insertImage', {title: 'вставить изображение'}, null, function( self ) { self.editorDoc.execCommand('insertImage', true, null); });
        //this.appendMenu('insertImage', {title: 'вставить изображение'});
      }
      else
      {
        this.appendMenu('createLink', {title: 'гиперссылка'}, null, function( self ) { var szURL = prompt('Ingrese una URL', 'http://'); if ( szURL && szURL.length > 0 ) self.editorDoc.execCommand('createLink', false, szURL); });
        //this.appendMenu('insertImage', {title: 'вставить изображение'}, null, function( self ) { var szURL = prompt('Ingrese una URL', 'http://'); if ( szURL && szURL.length > 0 ) self.editorDoc.execCommand('insertImage', false, szURL); });
        //this.appendMenu('insertImage', {title: 'вставить изображение'});
      }

      if(options['wysiwygType'] != 'comment'){
        if ( $.browser.mozilla )
        {
        this.appendMenuSeparator();
        var tempArr1 = new Array;var tempArr2 = new Array;var tempArr3 = new Array;
        tempArr1[0] = 'h1';tempArr1['title'] = 'заголовок первого уровня';
        this.appendMenu('heading', tempArr1, 'h1');
        tempArr2[0] = 'h2';tempArr2['title'] = 'заголовок второго уровня';
        this.appendMenu('heading', tempArr2, 'h2');
        tempArr3[0] = 'h3';tempArr3['title'] = 'заголовок третьего уровня';
        this.appendMenu('heading', tempArr3, 'h3');
        }
      }

			if ( ( $.browser.msie ) ){
	      this.appendMenuSeparator();
	      this.appendMenu('cut', {title: 'вырезать'});
	      this.appendMenu('copy', {title: 'копировать'});
	      this.appendMenu('paste', {title: 'вставить'});
    	}
      if ( ( $.browser.mozilla ) )
      {
        this.appendMenuSeparator();
        this.appendMenu('increaseFontSize', {title: 'увеличить шрифт'});
        this.appendMenu('decreaseFontSize', {title: 'уменьшить шрифт'});
      }

      this.appendMenuSeparator();
      if(options['wysiwygType'] != 'comment'){
        this.appendMenu('html', {title: 'посмотреть HTML-код'}, null, function( self )
        {
        if ( self.viewHTML )
        {
          self.setContent( $(self.original).val() );
          $(self.original).hide();
        }
        else
        {
          self.saveContent();
          $(self.original).show();
        }

        self.viewHTML = !( self.viewHTML );
        });
      }

      this.appendMenu('removeFormat', {title: 'убрать форматирование'}, null, function( self )
      {
        self.editorDoc.execCommand('removeFormat', false, []);
        self.editorDoc.execCommand('unlink', false, []);
      });
      this.element = $('<div></div>').css({
        width : ( newX ).toString() + 'px'
      }).addClass('wysiwyg')
        .append(panel)
        //.append( $('<div><!-- --></div>').css({ clear : 'both' }) )
        .append(editor);
      $(element)
      // .css('display', 'none')
      .hide()
      .before(this.element);
      this.viewHTML = false;
      this.initialHeight = newY - 8;
      this.initialContent = $(element).text();
      this.initFrame();
      if ( this.initialContent.length == 0 )
        this.setContent('<br />');
      
    },

    initFrame : function()
    {
      
      this.editorDoc = $(this.editor).document();
      this.editorDoc.open();
      this.editorDoc.write(
        this.options.html.replace(/INITIAL_CONTENT/, this.initialContent)
      );
      this.editorDoc.close();
      this.editorDoc.contentEditable = 'true';
      this.editorDoc.designMode = 'on';
      
    },

    getContent : function()
    {
      return $( $(this.editor).document() ).find('body').html();
    },

    setContent : function( newContent )
    {
      $( $(this.editor).document() ).find('body').html(newContent);
    },

    saveContent : function()
    {
      if ( this.original )
        $(this.original).val( this.getContent() );
    },

    appendMenu : function( cmd, args, className, fn )
    {
      
      var self = this;
      var args = args || [];

      var liEl = $('<li></li>');
	        if ($.browser.msie)
	        	liEl.append(
	          	$('<a href="/" title="' + args['title'] + '" onclick="return false;"><!-- --></a>').addClass(className || cmd)
	          	);
	        else
	        liEl.append(
	        	$('<a title="' + args['title'] + '" ><!-- --></a>').addClass(className || cmd)
	        );
      
      if ($.browser.msie){
	      liEl.mousedown(function() {
	        if ( fn ){
	        	 fn(self);
	        }
	        else{
	        	 if(cmd == 'insertImage'){
             theImage = 'http://www.kouzma.ru/images/photo.gif"  alt="bubub" align="left" border="0" hspace="12" vspace="11"';
	        	   self.editorDoc.execCommand("InsertImage",false,theImage);
	        	   
	        	   /*var HTMLText = '<div id="wysiwygImage">1234567890</div>';
	        	   var IFrameText = '<frame><form action="/" method="POST" enctype="multipart/form-data">123<input type="file" /><input type="submit" value="Загрузить" /></form></frame>';
	        	   $("body").append(IFrameText);
	        	   $("body").append(HTMLText);*/
	        	 }
	        	 else{
	        	   self.editorDoc.execCommand(cmd, false, args);
	        	   //$("#wysiwyg").get(0).focus();
	        	   $(self.original).get(0).focus();
	        	 }
	        	 
	        	 
	        	 /*Для IE 
	        	 $("#wysiwyg").get(0).focus();
	        	 */ 
	        	 /*Для Mozilla
	        	  var fr = $("#wysiwygIFrame").get(0);
	        	   fr.contentWindow.focus();
	        	  */
	        	   /*Для Opera
	        	   var fr = $("#wysiwygIFrame").get(0);
	        	   fr.focus();
	        	  */
	        }
	      });
	      
      }
      else{
	      liEl.click(function() {
	        if ( fn ){
	        	 fn(self);
	        }
	        else{
	        	 self.editorDoc.execCommand(cmd, false, args);
						if ($.browser.opera)
							$("#" + $(self.original).attr('id') + "IFrame").get(0).focus();
						else{
							$("#" + $(self.original).attr('id') + "IFrame").get(0).contentWindow.focus();
						}
	        }
	      });      	
      }
      liEl.appendTo( this.panel );
    },

    appendMenuSeparator : function()
    {
      $('<li class="separator"></li>').appendTo( this.panel );
    }
  });
})(jQuery);