// the editor text area ID
var editorTextAreaID = "";
var commentBoxContainerId = '';

// the editor toolbox button
var editorButtons = false;

// simple mode is when only a text area for the editor is generated,
// image upload and buttons are not generated if true
// might be set before moduleSettings dependency is loaded
//var editorSimpleMode = false;

// the upload frame ID
var uploadFrameIFrameID = "";

var defaultUploadFrameContent = "";

// for values see initEditor below

// tryes to insert the text, given at the current position of the cursor
// in the editor's textarea
function addTextAtCursorInEditorTextArea( text )
{
  var textarea = obtainElementById( editorTextAreaID );
  text = text;
  
  if ( textarea.caretPos )
  {
    var caretPos = textarea.caretPos;  
    caretPos.text = text;
    // to move the cursor to the position after the inserted text
    caretPos.select();
  }
  else 
  {
    if ( textarea.selectionStart && textarea.selectionEnd )
    {
      var selLength = textarea.textLength;
      var selStart = textarea.selectionStart;
      var selEnd = textarea.selectionEnd;
      if ( selEnd == 1 || selEnd == 2 )
        selEnd = selLength;

      var s1 = (textarea.value).substring( 0, selStart );
      var s2 = (textarea.value).substring( selStart, selEnd );
      var s3 = (textarea.value).substring( selEnd, selLength );
      textarea.value = s1 + "" + s2 + text + s3;

      textarea.selectionEnd = 0;
      textarea.selectionStart = selEnd + 0 + text.length;
    }
    else
      textarea.value += text;
  };

  //focusElementById( editorTextAreaID );
}
// the helper function for the previous one, which lets the selections work
// in IE:
// due to the selection is resetted when the dialogue occurs, this function
// should be called before every dialogue, which will cause the text area
// content changes to store the current cursor position in the textarea's
// custom property, named caretPos
function storeCurrentCursorPosition()
{
  var textarea = obtainElementById( editorTextAreaID );
  if ( textarea && document.selection && document.selection.createRange ) 
  {  
    //textarea.caretPos = textarea.createTextRange();
    textarea.caretPos = document.selection.createRange().duplicate();
    window.status=textarea.caretPos.text;
  };
}

function initEditor()
{
  editorTextAreaID = "textfield";
  commentBoxContainerId = 'commentbox';

  editorButtons = new Array();

  uploadFrameIFrameID = "uploadFrame";

  defaultUploadFrameContent = "<style>html,body{border:none;background:transparent;margin:0px;padding:0px;overflow:hidden;}</style><form style='margin:0px; padding:0px' id='fileform' method='POST' enctype='multipart/form-data' action='http://"+SERVER_NAME+"/'><input type='hidden' name='"+PARAM_DOCUMENT_PATH_STRING+"' value='"+DOCUMENT_PATH_STRING+"'><input type='hidden' name='MAX_FILE_SIZE' value='1000000'><input type='hidden' name='"+PARAM_FUNCTION+"' value='"+PARAM_FUNCTION_INSET_FILE_ADD+"'><input style='margin:0px; padding=0px' width='150' height='25' name='"+PARAM_ADD_INSET_FILE_DATA+"' type='file' value=''><input style='margin:0px; padding=0px' width='70' height='20' type='submit' value='Вставить'></form>";


  // italic text
  var i = 0;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить курсивный текст.";
  editorButtons[i]['caption'] = "<em>К</em>";
  editorButtons[i]['command'] = "var text = prompt( 'Введите курсивный текст:', '' ); if ( text ) addTextAtCursorInEditorTextArea('&lt;em&gt;'+text+'&lt;/em&gt;');";

  // strong text
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить полужирный текст.";
  editorButtons[i]['caption'] = "<strong>Ж</strong>";
  editorButtons[i]['command'] = "var text = prompt( 'Введите полужирный текст:', '' ); if ( text ) addTextAtCursorInEditorTextArea('&lt;strong&gt;'+text+'&lt;/strong&gt;');";

  // big text
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить большой текст. Преимущественно для иероглифов.";
  editorButtons[i]['caption'] = "<big>б</big>";
  editorButtons[i]['command'] = "var text = prompt( 'Введите большой текст:', '' ); if ( text ) addTextAtCursorInEditorTextArea('&lt;big&gt;'+text+'&lt;/big&gt;');";

  // small text
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить маленький текст.";
  editorButtons[i]['caption'] = "<small>М</small>";
  editorButtons[i]['command'] = "var text = prompt( 'Введите маленький текст:', '' ); if ( text ) addTextAtCursorInEditorTextArea('&lt;small&gt;'+text+'&lt;/small&gt;');";

  // strike text
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить зачёркнутый текст.";
  editorButtons[i]['caption'] = "<strike>зач</strike>";
  editorButtons[i]['command'] = "var text = prompt( 'Введите зачёркнутый текст:', '' ); if ( text ) addTextAtCursorInEditorTextArea('&lt;strike&gt;'+text+'&lt;/strike&gt;');"; 

  // anchor
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить ссылку.";
  editorButtons[i]['caption'] = "<a>URL</a>";
  editorButtons[i]['command'] = "var url = prompt( 'Введите URL ссылки:', 'http://', '' ); var text = prompt( 'Введите текст ссылки:' ); if ( text && url ) addTextAtCursorInEditorTextArea('&lt;a href=\\\''+url+'\\\'&gt;'+text+'&lt;/a&gt;');";

  // image
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить изображение.";
  editorButtons[i]['caption'] = "<div width='30' height='20' style='background-image:url(\""+MODULE_PATH+"image.gif\");'>&nbsp;</div>";
  editorButtons[i]['command'] = "var url = prompt( 'Введите URL изображения:', 'http://' ); if ( url ) addTextAtCursorInEditorTextArea('&lt;img&gt;'+url+'&lt;/img&gt;');";

  // smileys
  i++;
  editorButtons[i] = new Array();
  // smileys list
  var smileys = new Array(
    " :-) ",
    " ;-) ",
    " :-( ",
    " :-P ",
    " B-) ",
    " >:-< ",
    " :-\\ ",
    " =-O ",
    " :-> ",
    " :-D ",
    " (*_*) ",
    " <3 ",
    " (9_9) ",
    " :,-( ",
    " O:-) ",
    " O_o "
  );
  editorButtons[i]['hint'] = "Нажмите на смайлик, чтобы вставить его.<br />";
  for ( var smileyI = 0; smileyI < smileys.length; smileyI++ )
    editorButtons[i]['hint'] += "<span onclick=\\'javascript: addTextAtCursorInEditorTextArea(smileys["+smileyI+"])\\'>"+replaceSymsWithSmileys( smileys[smileyI].replace(/</g,"&lt;").replace(/>/g,"&gt;"), SMILEYS_PATH ).replace(/'/g,"\\'") + "</span> ";
  editorButtons[i]['caption'] = "<div width='30' height='20' style='background-image:url(\""+replaceSymsWithSmileys( smileys[0], SMILEYS_PATH ).replace(/<img class='smiley' src='/,"").replace(/' \/>/,"")+"\"); background-repeat: no-repeat; background-position: center;'>&nbsp;</div>";
  editorButtons[i]['command'] = "";

  // h1
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить заголовок.";
  editorButtons[i]['caption'] = "h1";
  editorButtons[i]['command'] = "var text = prompt( 'Введите текст заголовка:', '' ); if ( text ) addTextAtCursorInEditorTextArea('\\n&lt;h1&gt;'+text+'&lt;/h1&gt;\\n');";

  // h2
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить подзаголовок.";
  editorButtons[i]['caption'] = "h2";
  editorButtons[i]['command'] = "var text = prompt( 'Введите текст подзаголовка:', '' ); if ( text ) addTextAtCursorInEditorTextArea('\\n&lt;h2&gt;'+text+'&lt;/h2&gt;\\n');";

  // h3
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить название параграфа.";
  editorButtons[i]['caption'] = "h3";
  editorButtons[i]['command'] = "var text = prompt( 'Введите текст подзаголовка:', '' ); if ( text ) addTextAtCursorInEditorTextArea('\\n&lt;h3&gt;'+text+'&lt;/h3&gt;\\n');";

  // pre
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить неформатированный текст.";
  editorButtons[i]['caption'] = "pre";
  editorButtons[i]['command'] = "var text = prompt( 'Введите текст, который нужно вывести без форматирования:', '' ); if ( text ) addTextAtCursorInEditorTextArea('\\n&lt;pre&gt;'+text+'&lt;/pre&gt;\\n');";

  // ul
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить маркированный список. Вводится только первая строка, дальше необходимо внутри тега &amp;lt;ul&amp;gt; повторять только тег &amp;lt;li&amp;gt;.";
  editorButtons[i]['caption'] = "&bull;&nbsp;ul";
  editorButtons[i]['command'] = "var text = prompt( 'Введите первую строку списка:', '' ); if ( text ) addTextAtCursorInEditorTextArea('\\n&lt;ul&gt;\\n&lt;li&gt;'+text+'&lt;/li&gt;\\n&lt;/ul&gt;\\n');";

  // ol
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить нумерованный список. Вводится только первая строка, дальше необходимо внутри тега &amp;lt;ol&amp;gt; повторять только тег &amp;lt;li&amp;gt;.";
  editorButtons[i]['caption'] = "1.&nbsp;ol";
  editorButtons[i]['command'] = "var text = prompt( 'Введите первую строку списка:', '' ); if ( text ) addTextAtCursorInEditorTextArea('\\n&lt;ol&gt;\\n&lt;li&gt;'+text+'&lt;/li&gt;\\n&lt;/ol&gt;\\n');";

  // table
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить таблицу. Вводится только первая ячейка первой строки. Дальше для создания новой строки необходимо внутри тега &amp;lt;table&amp;gt; повторять тег &amp;lt;tr&amp;gt; и содержащиеся в нём теги &amp;lt;td&amp;gt;. Чтобы в той же строке создать новую ячейку необходимо внутри тега &amp;lt;tr&amp;gt; повторять тег &amp;lt;td&amp;gt;. Число ячеек во всех строках должно быть одинаковым. И вообще, если не знаете как это делать&nbsp;&mdash; лучше не делайте.";
  editorButtons[i]['caption'] = "table";
  editorButtons[i]['command'] = "var text = prompt( 'Введите текст первой ячейки:', '' ); if ( text ) addTextAtCursorInEditorTextArea('\\n&lt;table border=\\\'2\\\'&gt;\\n&lt;tr&gt;\\n&lt;td&gt;'+text+'&lt;/td&gt;\\n&lt;/tr&gt;\\n&lt;/table&gt;\\n');";

  // web upload
  i++;
  editorButtons[i] = new Array();
  editorButtons[i]['hint'] = "Вставить объект стороннего сервиса. Нужно вставить ссылку на страницу Youtube, Loadup, содержащую видео, аудио или что там за сервис они предоставляют";
  editorButtons[i]['caption'] = "video";
  editorButtons[i]['command'] = "var url = prompt( 'Введите URL видео или чего там:', 'http://' ); if ( url ) addTextAtCursorInEditorTextArea('&lt;webupload&gt;'+url+'&lt;/webupload&gt;');";

  // the document content editor
  var commentBoxContent = "";
  //commentBoxContent += "<div id='"+commentBoxContainerId+"' style='display:none'>";
  commentBoxContent += "<h1><span id='commentboxheader'>Вам слово</span></h1>\n";
  
  if ( !editorSimpleMode )
  {
    commentBoxContent += "<table>\n<tr>\n";

    // drawing the first half of editorButtons
    for ( var i = 0; i < Math.round( editorButtons.length / 2 ); i++ )
    {
      commentBoxContent += "<td style='width:45px; height:25px; padding:3px; overflow: hidden;'>\n";
      commentBoxContent += "  <div class='buttoninput' style='overflow:hidden' ";
      commentBoxContent += "  onmouseover=\"javascript: placeElementWithContentOnTopFromMe( this, 'hintconstrain', 'hintcontent', '"+editorButtons[i]['hint']+"', 0, 0, hintHidingDelay );\"";
      commentBoxContent += "  onmouseout=\"javascript: startHidingLastElement('hintconstrain');\"";
      commentBoxContent += "  onclick=\"javascript: "+editorButtons[i]['command']+"; obtainElementById( '"+editorTextAreaID+"' ).focus(); \"";
      commentBoxContent += ">"+editorButtons[i]['caption']+"</div>\n";
      commentBoxContent += "</td>\n";
    };
    commentBoxContent += "</tr>\n<tr>\n";
    // drawing the second part of editorButtons
    for ( var i = Math.round( editorButtons.length / 2 ); i < editorButtons.length; i++ )
    {
      commentBoxContent += "<td style='width:45px; height:25px; padding:3px; overflow: hidden;'>\n";
      commentBoxContent += "  <div class='buttoninput' style='overflow:hidden' ";
      commentBoxContent += "  onmouseover=\"javascript: placeElementWithContentOnBottomFromMe( this, 'hintconstrain', 'hintcontent', '"+editorButtons[i]['hint']+"', 0, 0, hintHidingDelay );\"";
      commentBoxContent += "  onmouseout=\"javascript: startHidingLastElement('hintconstrain');\"";
      commentBoxContent += "  onclick=\"javascript: "+editorButtons[i]['command']+"; obtainElementById( editorTextAreaID ).focus(); \"";
      commentBoxContent += ">"+editorButtons[i]['caption']+"</div>\n";
      commentBoxContent += "</td>\n";
    };

    commentBoxContent += "</tr>\n</table>\n";
  };

  commentBoxContent += "<table width='100%'>\n";
  commentBoxContent += "  <tr>\n";
  commentBoxContent += "    <td style='padding-left:30px; padding-right:30px'>\n";
  commentBoxContent += "      <div class='multilinetextinput'><textarea onclick='javascript: if ( this.value == defaultTextFieldValue ) this.value=\"\"' onfocus='javascript: if ( this.value == defaultTextFieldValue ) this.value=\"\"' disable_onmouseover='javascript: if ( !this.disabled ) this.blur(); this.focus();' onkeyup='javascript: storeCurrentCursorPosition(); ' onmouseup='javascript: storeCurrentCursorPosition(); ' style='height:500px; width:100%' id='"+editorTextAreaID+"'></textarea></div>\n";
  commentBoxContent += "    </td>\n";
  commentBoxContent += "  </tr>\n";
  commentBoxContent += "  <tr>\n";
  commentBoxContent += "    <td>\n";
  if ( !editorSimpleMode )
  {
    commentBoxContent += "      <table style='margin:0px; padding:0px;'>\n";
    commentBoxContent += "        <tr>\n";
    commentBoxContent += "          <td>Вставить файл:</td>\n";
    commentBoxContent += "          <td><div id='uploadFrameDiv'><iframe frameborder=\'0\' allowtransparency=\'true\' id='"+uploadFrameIFrameID+"' class='uploadframe' src='about:blank' onload='javascript: uploadFrameCallback(this);'></iframe></div></td>\n";
    commentBoxContent += "        </tr>\n";
    commentBoxContent += "      </table>\n";
  };
  commentBoxContent += "      <table align='right' style='margin-left:auto; margin-right:0px;'>\n";
  commentBoxContent += "        <tr>\n";
  commentBoxContent += "          <td id='cancelbuttoncontainer' style='display:none'>\n";
  commentBoxContent += "            <div class='buttoninput' style='width:200px;'><input tabindex='3' type='button' id='cancelbutton' onclick='javascript: prepareCommentBoxForDefaultFunctionality();' value='Отмена' /></div>\n";
  commentBoxContent += "          </td>\n";
  commentBoxContent += "          <td>\n";
  commentBoxContent += "            <div class='buttoninput' style='width:200px'><input tabindex='3' type='button' id='submitbutton' value='' /></div>\n";
  commentBoxContent += "          </td>\n";
  commentBoxContent += "        </tr>\n";
  commentBoxContent += "      </table>\n";
  commentBoxContent += "    </td>\n";
  commentBoxContent += "  </tr>\n";
  commentBoxContent += "</table>\n";
  //commentBoxContent += "</div>\n";

  var commentBoxContainer = obtainElementById(commentBoxContainerId);
  if ( commentBoxContainer )
  {
    commentBoxContainer.innerHTML = commentBoxContent;
    // dependency is loaded
    dependencyLoaded('editor');
  }

}




// ------------------------------------------------------------------
// functions to manage the files upload
// ------------------------------------------------------------------
// adds the URL of the file, uploaded from the temp frame into
// the text field and restores the frame's content with controls
// to upload the next file
function uploadFrameCallback( uploadFrame, outputTextFieldId )
{ 
  var uploadFrameDocument = getFrameDocument( uploadFrame );
  if ( !(uploadFrameDocument.body.form) )
  {
    // due to the Opera fills with two new line symbols an empty document,
    // this replace is required
    var response = uploadFrameDocument.body.innerHTML.replace(/\s/g,"").replace(/<[^>]*>/g,"");
    if ( response != "" )
    {
      if ( response != RESPONSE_IGNORED_EMPTY && response != RESPONSE_FORBIDDEN )
      {
        obtainElementById( editorTextAreaID ).value += "<img>" + INSET_FILE_URL_BASE + response + "</img>";
      }
      else
      { 
        alert(response);
      };
      obtainElementById( "uploadFrameDiv" ).innerHTML = '<iframe id="'+uploadFrameIFrameID+'" class="uploadframe" src="about:blank" onload="javascript: uploadFrameCallback(this);"></iframe>';
    }
    else
    {
      uploadFrameDocument.body.innerHTML = defaultUploadFrameContent;    
      uploadFrameDocument.body.style.margin = "0px";
      uploadFrameDocument.body.style.padding = "0px";
      uploadFrameDocument.body.style.background = "transparent";
    };
  };
}

// INIT
addDependentCallback(function(){
  initEditor();
},'constants, settings, textModifiers, helperFunctions, moduleSettings', false);

