//Have the propmt box turned on by default
var promptOn = false;
var MessageBox;
var IFrameEdit=false;

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}

function getSelection (input) {
  if (!input) {
  var txt2='';
  if (document.getSelection) txt2=document.getSelection()
  else if (document.selection) txt2=document.selection.createRange().text  
  return txt2;
  }
  if (input.setSelectionRange) {
    var selectionStart = input.selectionStart;
    var selectionEnd = input.selectionEnd;
    //return selectionEnd;
    return input.value.substring(selectionStart,selectionEnd);
  }
  else if (document.selection) {
    return document.selection.createRange().text;
  }
  else 
  {
    return "";
  }
}

function replaceSelection (input, replaceString) {
  if (!input) return;
  if (input.setSelectionRange) {
    var selectionStart = input.selectionStart;
    var selectionEnd = input.selectionEnd;
    input.value = input.value.substring(0, selectionStart)
                  + replaceString
                  + input.value.substring(selectionEnd);
    if (selectionStart != selectionEnd) // has there been a selection
      setSelectionRange(input, selectionStart, selectionStart + replaceString.length);
    else // set caret
      setCaretToPos(input, selectionStart + replaceString.length);
  }
  else if (document.selection) {
  
    var range = document.selection.createRange();
    if (range.parentElement() == input) {
      var isCollapsed = range.text == '';
      range.text = replaceString;
      if (!isCollapsed)  { // there has been a selection
        //it appears range.select() should select the newly 
        //inserted text but that fails with IE
        range.moveStart('character', -replaceString.length);
        range.select();
      }
    }
  }
}

function paste(input, text, flag){ 
    if ( (document.selection || MessageBox.setSelectionRange) && flag) {
        input.focus();
        replaceSelection(input, text);
    } else { 
        input.value += text; 
    }
}

//Function to turn on or off the prompt box
function PromptMode(selectMode){
    if (selectMode.options[selectMode.selectedIndex].value == 0){promptOn = false;}
    else{promptOn = true;}
}

// Function to add the code for bold italic centre and underline, to the message
function AddMessageCode(code, promptText, InsertText) {
    if (MessageBox == null) {return;}
    if (code != "") {
	    if (promptOn == true){
		    insertCode = prompt(promptText + "\n[" + code + "]xxx[/" + code + "]", InsertText);
			    if ((insertCode != null) && (insertCode != "")){ paste(MessageBox,"[" + code + "]" + insertCode + "[/" + code + "]",true); }
	    }
	    else{paste(MessageBox,"[" + code + "]" + getSelection(MessageBox) + "[/" + code + "]",true);}
    }
    MessageBox.focus();
}

// Function to add the font colours, sizes, type to the message, to the message
function FontCode(ListBox) {
    if (MessageBox == null) {return;}
    var code = ListBox.options[ListBox.selectedIndex].value;
	    if (code != "0") {
		    if (promptOn == true){
			    insertCode = prompt(strTxtEnterTextYouWouldLikeIn + code + "\n[" + code + "]xxx[/FONT]", '');
			    if ((insertCode != null) && (insertCode != "")){ paste(MessageBox,"[" + code + "]" + insertCode + "[/FONT]",true); }
		    }
		    else{
			    paste(MessageBox,"[" + code + "]" + getSelection(MessageBox) + "[/FONT]",true);
		    }
	    }	
	    //document.getElementById(ListBox).options[0].selected = true;
	    ListBox.options[0].selected = true;
	    MessageBox.focus();
}

// Function to add the font colours to the message, to the message
function AddColourCode(ListBox) {
    if (MessageBox == null) {return;}
    var code = ListBox.options[ListBox.selectedIndex].value;
    if (code != "0") {
	    if (promptOn == true){
		    insertCode = prompt("Введите текст внутри тега " + code + "\n[" + code + "]xxx[/FONT]", '');
		    if ((insertCode != null) && (insertCode != "")){ paste(MessageBox,"[" + code + "]" + insertCode + "[/FONT]",true); }
	    }
	    else{paste(MessageBox,"[" + code + "]" + getSelection(MessageBox) + "[/FONT]",true);}
    }
    ListBox.options[0].selected = true;	
    MessageBox.focus();
}

//Function to add the code to the message for the special characters
function AddCharacter(ListBox) {	
    var chrCode = ListBox.options[ListBox.selectedIndex].value;
    if (MessageBox == null) {return;}
    if (chrCode != "0") { paste(MessageBox,chrCode,true); }
    ListBox.options[0].selected = true;	
    MessageBox.focus();
}

//Function to add the URL, indent, list, and Email code to the message
function AddCode(code) {
if (MessageBox == null) {return;}
//For the URL code
if ((code != "") && (code == "URL")) {
	insertText = prompt("Введите текст названия ссылки", "");
	if ((insertText != null) && (insertText != "") && (code == "URL")){
		insertCode = prompt("введите адрес Url для ссылки ", "http://");
		if ((insertCode != null) && (insertCode != "") && (insertCode != "http://")){ paste(MessageBox,"[" + code + "=" + insertCode + "]" + insertText + "[/" + code + "]",true); }
	}
}
//For the email code
if ((code != "") && (code == "EMAIL")) {
	insertText = prompt("введите текст для названия E-mail адреса", "");
	if ((insertText != null) && (insertText != "")){
		insertCode = prompt("Введите E-mail адрес для ссылки", "");
		if ((insertCode != null) && (insertCode != "")){ paste(MessageBox,"[" + code + "=" + insertCode + "]" + insertText + "[/" + code + "]",true); }
	}
}
//For the image code
if ((code != "") && (code == "IMG")) {	
	insertCode = prompt("Введите web адрес картинки", "http://");
	if ((insertCode != null) && (insertCode != "")){ paste(MessageBox,"[" + code + "]" + insertCode + "[/" + code + "]",true);	}			
}
//For the list code
if ((code != "") && (code == "LIST")) {
//	if (promptOn == true){
		listType = prompt("Тип списка \nВвод \'1\' для пронумерованных или оставьте пустым", "");
		while ((listType != null) && (listType != "") && (listType != "1")) {
			listType = prompt("Ошибка! Пожалуйста введите \'1\' для пронумерованных или оставьте пустым","");               
		}
		if (listType != null) {			
			var listItem = "1";
			var insertCode = "";
			while ((listItem != "") && (listItem != null)) {
				listItem = prompt("Элемент списка оставьте пустым для закрытия списка",""); 
				if (listItem != "") { insertCode += "[LI]" + listItem + "[/LI]"; }                   
			} 
			if (listType == "") {
				paste(MessageBox,"[" + code + "]" + insertCode + "[/" + code + "]",true);
			} else {
				paste(MessageBox,"[" + code + "=" + listType + "]" + insertCode + "[/" + code + "=" + listType + "]",true);
			} 
		}
//	}
//	else{
//		paste(MessageBox,"[" + code + "][LI] [/LI][LI] [/LI][LI] [/LI][/" + code + "]",true);
//	}			
}
//For the indent
if ((code != "") && (code == "INDENT")) { paste(MessageBox,"      ",true); }
MessageBox.focus();
}

function ResetForm(str){
    return confirm(str);
}

//Function to open preview post window
function OpenPreviewWindow(){
    if (MessageBox == null) {return;}
    strMessage = escape(MessageBox.value);
    document.cookie = "Message=" + strMessage
    openWin('post_preview.asp','preview','toolbar=0,location=0,status=0,menubar=0,scrollbars=1,resizable=1,width=680,height=400')
}

function AddUserName(str){
    if (MessageBox == null) {return;}
    paste(MessageBox,"[B]"+str+"[/B] ",true);
    MessageBox.focus();
}

//Function to open pop up window
function openWin(theURL,winName,features) {
    window.open(theURL,winName,features);
}

//Function to add the code to the message for the smileys
function AddSmileyIcon(iconCode) {	
   if (MessageBox == null) {return;}
   paste(MessageBox,iconCode,true);
   // MessageBox.value += "[IMG]" + iconCode + "[/IMG] ";
}

function SelectPrompt() {
w('<span class="text">Запрашивать текст:&nbsp;</span>'); 
w('<select name="selectMode" onChange=PromptMode(this)>');
w('<option value="1" selected>Да</option><option value="0">Нет</option>');
w('</select>');
}

function SelectSpecialCharacter() {
w('<select name="selectCharacter" onChange="AddCharacter(this); ">');
w('<option value="0" selected>-- Спец.символы --</option>');
w('<option value="[">[ Left Bracket</option>');
w('<option value="]">] Right Bracket</option>');
w('<option value="&nbsp;">Non breaking Space</option>');
w('<option value="#149;">#149; Bullet</option>');
w('<option value="&pound;">&pound; Pound</option>');
w('<option value="€">€ Euro</option>');
w('<option value="&yen;">&yen; Yen</option>');
w('<option value="¤">¤ General Currency</option>');
w('<option value="&times;">&times; Times</option>');
w('<option value="&divide;">&divide; Division</option>');
w('<option value="±">± Plus or Minus</option>');
w('<option value="°">° Degee Sign</option>');
w('<option value="µ">µ Micro Sign</option>');
w('<option value="&frac14;">&frac14; Quater Fraction</option>');
w('<option value="&frac12;">&frac12; Half Fraction</option>');
w('<option value="&frac34;">&frac34; Third Fraction</option>');
w('<option value="&egrave;">&egrave; e, Grave Accent</option>');
w('<option value="&ugrave;">&ugrave; u, Grave Accent</option>');
w('<option value="«">« Left Angle Quote</option>');
w('<option value="»">» Right Angle Quote</option>');
w('<option value="©">© Copyright</option>');
w('<option value="®">® Registered</option>');
w('</select>');
}
function SelectFont(){
w('<select name="selectFont" onChange="FontCode(this); ">');
w('<option value="0" selected>-- '+strTxtFont+' --</option>');
w('<option value="FONT=ARIAL">Arial</option>');
w('<option value="FONT=COURIER">Courier New</option>');
w('<option value="FONT=TIMES">Times New Roman</option>');
w('<option value="FONT=VERDANA">Verdana</option>');
w('</select>');
}
function SelectFontSize(){
w('<select name="selectSize" onChange="FontCode(this); ">');
w('<option value="0" selected>-- '+strTxtFontSize +' --</option>');
w('<option value="SIZE=1">1</option>');
w('<option value="SIZE=2">2</option>');
w('<option value="SIZE=3">3</option>');
w('<option value="SIZE=4">4</option>');
w('<option value="SIZE=5">5</option>');
w('<option value="SIZE=6">6</option>');
w('</select>');
}				
function SelectFontColor(){
w('<select name="selectColour" onChange="AddColourCode(this); " >');
w('<option value="0" selected>-- '+strTxtFontColor+' --</option><option value="BLACK">Black</option>');
w('<option value="WHITE">White</option><option value="BLUE">Blue</option>');
w('<option value="RED">Red</option><option value="GREEN">Green</option>');
w('<option value="YELLOW">Yellow</option><option value="ORANGE">Orange</option>');
w('<option value="BROWN">Brown</option><option value="MAGENTA">Magenta</option>');
w('<option value="CYAN">Cyan</option><option value="LIME GREEN">Lime Green</option>');
w('</select>');
}
function PrintEditLine(Emoticons) {
w('<tr valign="bottom"><td><table border="0" cellspacing="0" cellpadding="0"><tr>');
w('<td><a href="JavaScript:AddMessageCode(\'B\',\'Введите текст для обозначения жирным шрифтом\', \'\')"><img src="forum_images/post_button_bold.gif" width="38" height="40" align="absmiddle" border="0" alt="Жирный"></a></td>');
w('<td><a href="JavaScript:AddMessageCode(\'I\',\'Введите текст для обозначения наклонным шрифтом\', \'\')"><img src="forum_images/post_button_italic.gif" width="38" height="40" align="absmiddle" border="0" alt="Наклонный"></a></td>');
w('<td><a href="JavaScript:AddMessageCode(\'U\',\'Введите текст для обозначения подчеркнутым шрифтом\', \'\')"><img src="forum_images/post_button_underline.gif" width="38" height="40" align="absmiddle" border="0" alt="Подчеркнутый"></a></td>'); 
w('<td><a href="JavaScript:AddCode(\'URL\')"><img src="forum_images/post_button_hyperlink.gif" width="38" height="40" align="absmiddle" border="0" alt="Добавить ссылку"></a></td>');
w('<td><a href="JavaScript:AddMessageCode(\'CENTER\',\'Введите текст для формата по центру\', \'\')"><img src="forum_images/post_button_centre.gif" width="38" height="40" align="absmiddle" border="0" alt="По центру"></a></td>'); 
w('<td><a href="JavaScript:AddCode(\'LIST\', \'\')"><img src="forum_images/post_button_list.gif" width="38" height="40" align="absmiddle" border="0" alt="Список"></a></td>');
w('<td><a href="JavaScript:AddCode(\'INDENT\', \'\')"><img src="forum_images/post_button_indent.gif" width="38" height="40" align="absmiddle" border="0" alt="Indent"></a></td>'); 
w('<td><a href="JavaScript:AddCode(\'IMG\')"><img src="forum_images/post_button_image.gif" width="38" height="40" align="absmiddle" border="0" alt="Добавить изображение"></a></td>'); 
w('</tr></table></td></tr>'); 
}

function PrintSmileyLine(){
w('<tr><td><table width=340 border="0" cellspacing="0" cellpadding="0"><tr>');
w('<td width=13><img src="forum_images/smiley1.gif" border="0" alt="[:)]" OnClick="AddSmileyIcon(\'[:)]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley2.gif" border="0" alt="[;)]" OnClick="AddSmileyIcon(\'[;)]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley3.gif" border="0" alt="[:p]" OnClick="AddSmileyIcon(\'[:p]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley4.gif" border="0" alt="[):]" OnClick="AddSmileyIcon(\'[):]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley5.gif" border="0" alt="[:D]" OnClick="AddSmileyIcon(\'[:D]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley6.gif" border="0" alt="[:|]" OnClick="AddSmileyIcon(\'[:|]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley7.gif" border="0" alt="[:rnr]" OnClick="AddSmileyIcon(\'[:rnr]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley8.gif" border="0" alt="[:?]" OnClick="AddSmileyIcon(\'[:?]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley9.gif" border="0" alt="[:((]" OnClick="AddSmileyIcon(\'[:((]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley10.gif" border="0" alt="[:devil]" OnClick="AddSmileyIcon(\'[:devil]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley11.gif" border="0" alt="[:))]" OnClick="AddSmileyIcon(\'[:))]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley12.gif" border="0" alt="[:love]" OnClick="AddSmileyIcon(\'[:love]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley13.gif" border="0" alt="[:(]" OnClick="AddSmileyIcon(\'[:(]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley14.gif" border="0" alt="[8|]" OnClick="AddSmileyIcon(\'[8|]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley15.gif" border="0" alt="[:beer]" OnClick="AddSmileyIcon(\'[:beer]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley16.gif" border="0" alt="[:spy]" OnClick="AddSmileyIcon(\'[:spy]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley17.gif" border="0" alt="[:lamo]" OnClick="AddSmileyIcon(\'[:lamo]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley18.gif" border="0" alt="[:gigi]" OnClick="AddSmileyIcon(\'[:gigi]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley19.gif" border="0" alt="[:maniac]" OnClick="AddSmileyIcon(\'[:maniac]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley20.gif" border="0" alt="[:moder]" OnClick="AddSmileyIcon(\'[:moder]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley21.gif" border="0" alt="[:lol]" OnClick="AddSmileyIcon(\'[:lol]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley22.gif" border="0" alt="[:sleep]" OnClick="AddSmileyIcon(\'[:sleep]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley23.gif" border="0" alt="[:wtf]" OnClick="AddSmileyIcon(\'[:wtf]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley24.gif" border="0" alt="[:angry]" OnClick="AddSmileyIcon(\'[:angry]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley25.gif" border="0" alt="[:mad]" OnClick="AddSmileyIcon(\'[:mad]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley26.gif" border="0" alt="[:bored]" OnClick="AddSmileyIcon(\'[:bored]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/smiley27.gif" border="0" alt="[:bad]" OnClick="AddSmileyIcon(\'[:bad]\')" style="cursor: hand;"></td>');
w('<td width=13><img src="forum_images/up.gif"       border="0" alt="[:up]" OnClick="AddSmileyIcon(\'[:up]\')" style="cursor: hand;"></td>');
w('</tr></table></td></tr>');
}

function CheckPost(SubmitButton,PostURL) {
    if (MessageBox == null) { return; }
    if (SubmitButton.form.submitted) { return; }
    var NewTopic = document.getElementById("NewTopic");
    var max = 1000;
    if (((strMode == "new") || (strMode == "edit")) && (NewTopic != null)){
        if (NewTopic.value.length == 0) 
        {
	       alert(strTxtNoPost);
	       NewTopic.focus();
	       return;        
        }
        if (NewTopic.value.length > max){
	        alert(strTxtPostToLong1+(NewTopic.value.length-max)+strTxtPostToLong2);
	        setCaretToPos(NewTopic, max);
	        return;
        }
    }

    max = (strMode == "comment")?4000:265000;

    if (MessageBox.value.length == 0){
	    alert(strTxtNoPost);
	    MessageBox.focus();
	    return;
    }
    if (MessageBox.value.length > max){
	    alert(strTxtPostToLong1+(MessageBox.value.length-max)+strTxtPostToLong2);
	    setCaretToPos(MessageBox, max);
	    return;
    }
    
    SubmitButton.disabled = true;
    document.getElementById('ForumResetButton').disabled = true;

    SubmitButton.form.action = PostURL;
    MessageBox.value = MessageBox.value.replace(/</gm,"&&lt;");
    MessageBox.value = MessageBox.value.replace(/>/gm,"&&gt;");
    SubmitButton.form.submit();
}

function PrintEditMessageField(strMessage,strMode,intMessageID) {
w('<tr><td valign="top" align="right" height="61">');
w('<table width="100%"><tr><td>');
w('<textarea id="ForumMessageArea" name="message" cols=105 rows=12 width="100%" class=n style="text-align: justify">');
w(strMessage);
w('</textarea>\r\n');
w('</td></tr></table>');
w('</td></tr>');
}

function setup_postform(){
    MessageBox = document.getElementById('ForumMessageArea');
    //ForumMessageArea = document.getElementById('ForumMessageArea');
    if (MessageBox !=null) {MessageBox.style.width="100%";} else { return; }
    promptOn = (!document.selection && !MessageBox.setSelectionRange);
}
