/* NEW JS START */
SEN.BBCode =
   {
      Console:
         (function() {
            var x =
               function Console(d) {
                  this.id = SEN.BBCode.consoles.push(this);
                  this.node = this.generateConsoleDOM();
               };
            x.prototype =
               {
                  generateConsoleDOM:
                     function() {
                        var Node = $("<div class=''></div>");
                        
                     },
                  die:
                     function() {
                        SEN.BBCode.consoles[this.id] = null;
                     }
               };
            return x
         })(),
      consoles: [], // WARNING: Do not use any methods that would change indices. (Things like splice() or shift().)
      Tags:
         {
            generic:
               function(node, tag_name) {
                  var tstatus = $(node).hasClass("bbcode_open");
                  var rstatus = complex_insert("[" + tag_name + "]", "[/" + tag_name + "]", tstatus); // FIXME use new insert func.
                  if (rstatus == 0)
                     $(node).removeClass("bbcode_open").addClass("bbcode").attr("value", tag_name.toUpperCase()); // FIXME buttons like QUOTE should not be uppercased
                  else if (rstatus == 1)
                     $(node).removeClass("bbcode").addClass("bbcode_open").attr("value", "/" + tag_name.toLowerCase());
               },
            tag_font: // FIXME work with better interphase HTML
               function(node_select, tag_name) {
                  var tstatus = $("#bbcode_"+tag_name+"_close").css("display") != "none";
                  var rstatus = complex_insert("[" + tag_name + "=" + node_select.value + "]", "[/" + tag_name + "]", tstatus);

                  $("#bbcode_"+tag_name).css( "display" , ["","none"][rstatus] );
                  $("#bbcode_"+tag_name+"_close").css( "display" , ["none",""][rstatus] );
                  $("#bbcode_"+tag_name)[0].selectedIndex = 0;
               },
            tag_list:
               function() {
                  var s = "\
<div class='dialog-header'>\n\
   <span>BBCode: LIST</span>\n\
   <p>Enter your list items below. Use the button to add list items. Leave an item blank to omit it.</p>\n\
</div>\n\
<ul id='modal_list_items' style='margin-top:.6em'>\n\
   <li><input type='text'></li>\n\
   <li style='list-style:none;margin-top:.6em'><input type='submit' value='Add list item'></li></ul>";

                  var m =
                     SEN.GUI.Dialogs.spawn(
                        {
                           innerHTML: s,
                           buttons: ["Insert this list", "Cancel"],
                           default_button: -1 // default button is in the content
                        }
                     );

                  $("#modal_list_items").find("li>input[type=submit]").click(
                     function() {
                        $("<li><input type='text'></li>").insertBefore($(this).closest("li"));
                        $(this).closest(".modal").data("modal").updateDisplay();
                     }
                  );
                  $(m).bind("Close", function() {$("#xtext").focus()});
                  $(m).bind(
                     "ButtonClicked",
                     function(e, d) {
                        if (!d.index) {
                           var bbcode = "[LIST]\n";
                           var P = $.makeArray($("#modal_list_items").find("input")), PL = P.length - 1;
                           for(i=0;i<PL;i++)
                              if (P[i].value.replace(/\s/g,""))
                                 bbcode += "[*]" + P[i].value + "\n";
                           bbcode += "[/LIST]";

                           if (bbcode == "[LIST]\n[/LIST]")
                              return this.close();

                           // complex_insert( id[1] , "0", "0");
                           complex_insert("", bbcode, null);
                           this.close();
                        } else {
                           this.close();
                        }
                     }
                  );
               },
            tag_special:
               function(node_select) {
                  var tag_name = node_select.value,
                      tOpen, tClose;
                  if (tag_name == "collapse") {
                     tOpen = "[collapse=Collapse Box]";
                  } else if (tag_name == "table") {
                     tOpen = "[table=width:100%|class:outline|cell-padding:4]\n[tr]\n[td=width:50%][/td]\n[td=width:50%][/td]\n[/tr][tr]\n[td=width:50%][/td]\n[td=width:50%][/td]\n[/tr]";
                  } else {
                     tOpen = "[" + tag_name + "]";
                  }
                  tClose = "[/" + tag_name + "]";
                  node_select.selectedIndex = 0;
                  complex_insert(tOpen, tClose, null, true);
               },
            tag_trigger:
               function() {
                  var s = "\
<div class='dialog-header'>\n\
   <span>BBCode: TRIGGER</span>\n\
   <p>Enter information for a <i>StarCraft</i> trigger below.</p>\n\
</div>\n\
<label for='modal_trigger_description'>Description:</label> <input type='text' id='modal_trigger_description'><br>\n\
Players:\n\
<ul id='modal_trigger_players_list' class='checkbox-list two-column-list'>\n\
   <li><input type='checkbox' id='modal_trigger_players_1'><label for='modal_trigger_players_1'> Player 1</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_players_2'><label for='modal_trigger_players_2'> Player 2</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_players_3'><label for='modal_trigger_players_3'> Player 3</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_players_4'><label for='modal_trigger_players_4'> Player 4</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_players_5'><label for='modal_trigger_players_5'> Player 5</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_players_6'><label for='modal_trigger_players_6'> Player 6</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_players_7'><label for='modal_trigger_players_7'> Player 7</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_players_8'><label for='modal_trigger_players_8'> Player 8</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_force_1'><label for='modal_trigger_force_1'> Force 1</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_force_2'><label for='modal_trigger_force_2'> Force 2</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_force_3'><label for='modal_trigger_force_3'> Force 3</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_force_4'><label for='modal_trigger_force_4'> Force 4</label></li>\n\
   <li><input type='checkbox' id='modal_trigger_all_players'><label for='modal_trigger_all_players'> All Players</label></li>\n\
</ul>\n\
Conditions:\n\
<ul id='modal_trigger_condition_list' style='list-style:none'>\n\
   <li><input type='text'></li>\n\
   <li><input type='button' value='Add Condition'></li></ul>\n\
Actions:\n\
<ul id='modal_trigger_action_list' style='list-style:none'>\n\
   <li><input type='text'></li>\n\
   <li><input type='button' value='Add Action'></li></ul>";
                  var m =
                     SEN.GUI.Dialogs.spawn(
                        {
                           innerHTML: s,
                           buttons: ["Insert this trigger", "Cancel"],
                           default_button: 0
                        }
                     );
                  $("#modal_trigger_condition_list li>input[type=button], #modal_trigger_action_list li>input[type=button]").click(
                     function() {
                        $("<li><input type='text'></li>").insertBefore($(this).closest("li"));
                        $(this).closest(".modal").data("modal").updateDisplay();
                     }
                  );

                  $(m).bind("Close", function() {$("#xtext").focus()});
                  $(m).bind(
                     "ButtonClicked",
                     function(e, d) {
                        if (!d.index) {
                           var bbcode = "[TRIGGER]";

                           bbcode += "[DESCRIPTION]" + ($("#modal_trigger_description")[0].value||"[i]None specified.[/i]") + "[/DESCRIPTION]";

                           bbcode += "[PLAYERS]";
                           var P = $.makeArray($("#modal_trigger_players_list input")), PL = P.length;
                           for(var i=0;i<PL;i++)
                              if (P[i].checked)
                                 bbcode += "[*]" + P[i].nextSibling.innerHTML.substring(1);
                           if (bbcode.match(/\[PLAYERS\]$/))
                              bbcode += "[i]None specified.[/i]";
                           bbcode += "[/PLAYERS]";

                           bbcode += "[CONDITIONS]";
                           P = $.makeArray($("#modal_trigger_condition_list input")); PL = P.length - 1;
                           for(i=0;i<PL;i++)
                              if (P[i].value.replace(/\s/g,""))
                                 bbcode += "[*]" + P[i].value;
                           if (bbcode.match(/\[CONDITIONS\]$/))
                              bbcode += "[i]None specified.[/i]";
                           bbcode += "[/CONDITIONS]";

                           bbcode += "[ACTIONS]";
                           P = $.makeArray($("#modal_trigger_action_list input")); PL = P.length - 1;
                           for(i=0;i<PL;i++)
                              if (P[i].value.replace(/\s/g,""))
                                 bbcode += "[*]" + P[i].value;
                           if (bbcode.match(/\[ACTIONS\]$/))
                              bbcode += "[i]None specified.[/i]";
                           bbcode += "[/ACTIONS]";

                           bbcode += "[/TRIGGER]";

                           // complex_insert( id[1] , "0", "0");
                           complex_insert("", bbcode, null);
                           d.modal.close();
                        } else {
                           d.modal.close();
                        }
                     }
                  );
               },
            tag_quote_name:
               function(node) {
                  var s = "\
<div class='dialog-header'>\n\
   <span>BBCode: QUOTE</span>\n\
</div>\n\
<label class='above'>Type the name of the member you want to quote.</label>\n\
<input type='text'>";

                  var m =
                     SEN.GUI.Dialogs.spawn(
                        {
                           innerHTML: s,
                           buttons: ["OK", "Cancel"],
                           default_button: 0
                        }
                     );
                  $(m.contentNode).find("input").focus();
                  $(m).bind("Close", function() {$("#xtext").focus()});
                  $(m).bind(
                     "ButtonClicked",
                     function(e, d) {
                        if (!d.index) {
                           var value = $(d.modal.contentNode).find("input[type=text]").val();
                           var bbcode = "[quote" + (value ? "=name:" + value : "") + "][/quote]";
                           complex_insert("", bbcode, null);
                           d.modal.close();
                        } else {
                           d.modal.close();
                        }
                     }
                  );
               },
            tag_vari:
               function(node_select, tag_name) {
                  var s = "\
<div class='dialog-header'>\n\
   <span>BBCode: " + tag_name.toUpperCase() + "</span>\n\
</div>\n\
<label class='above'>";
                  s +=
                     ({
                        email: "Enter the e-mail address you wish to link to:",
                        img: "Enter the location of your image:",
                        line: "Enter a percentage width for your horizontal rule (between 25 and 100):",
                        progress: "Enter a percentage value for your progress bar (between 1 and 100):",
                        url: "Enter the URL you wish to link to:"
                     })[tag_name];
                  s += "\
</label>\n\
<input type='text'>\n\
<div class='modal-form-error e1'></div>"; // empty div is for error messages.
                  if ("email url".indexOf(tag_name) >= 0)
                     s += "<label class='above'>You may also enter an optional title for your link:</label><input type='text'>";
                  if (tag_name == "img")
                     s += "<label class='above'>Width (optional):</label>\n<input type='text'><div class='modal-form-error e2'></div><label class='above'>Height (optional):</label>\n<input type='text'><div class='modal-form-error e3'>";

                  var m =
                     SEN.GUI.Dialogs.spawn(
                        {
                           innerHTML: s,
                           buttons: ["OK", "Cancel"],
                           default_button: 0
                        }
                     );
                  m.loltype = tag_name; // expandos ftw
                  $(m.contentNode).find("input").eq(0).focus();
                  $(m).bind("Close", function() {$("#xtext").focus()});
                  $(m).bind(
                     "ButtonClicked",
                     function(e, d) {
                        if (!d.index) {
                           var value1 = $(d.modal.contentNode).find("input")[0].value;
                           var value2 = ($(d.modal.contentNode).find("input")[1]||{value:""}).value;
                           var value3 = ($(d.modal.contentNode).find("input")[2]||{value:""}).value;
                           var error_output_1 = $(d.modal.contentNode).find("div.modal-form-error.e1");
                           var error_output_2 = $(d.modal.contentNode).find("div.modal-form-error.e2");
                           var error_output_3 = $(d.modal.contentNode).find("div.modal-form-error.e3");

                           var tag = this.loltype;

                           var bbcode = "";

                           switch (tag) {
                              case "img":
                                 if (!value1)
                                    return d.modal.close();
                                 bbcode = "[img=" + value1;
                                 if (value2 || value3) {

                                    if (isNaN(parseInt(value2)))
                                       $(error_output_2).html("The width must be a number. You can leave it blank to avoid resizing.");
                                    if (isNaN(parseInt(value3)))
                                       $(error_output_3).html("The height must be a number. You can leave it blank to avoid resizing.");
                                    if (isNaN(parseInt(value2)) || isNaN(parseInt(value3)))
                                       return;

                                    bbcode += "|" + Math.max(700,Math.min(15, parseInt(value2||"100")));
                                    bbcode += "|" + Math.max(450,Math.min(15, parseInt(value3||"100")));
                                 }
                                 bbcode += "]";
                                 break;
                              case "line":
                                 value1 = parseInt(value1);
                                 if (value1 < 25 || value1 > 100) {
                                    $(error_output_1).html("The horizontal rule cannot be thinner than 25% or wider than 100%.");
                                    return;
                                 }
                                 if (value1 != value1)
                                    return d.modal.close();
                                 bbcode = "[line=" + value1 + "]";
                                 break;
                              case "progress":
                                 value1 = parseInt(value1);
                                 if (value1 < 1 || value1 > 100) {
                                    $(error_output_1).html("The progress bar cannot be less than 1% or greater than 100%.");
                                    return;
                                 }
                                 if (value1 != value1)
                                    return d.modal.close();
                                 bbcode = "[progress=" + value1 + "]";
                                 break;
                              case "email":
                              case "url":
                                 if (!value1)
                                    return d.modal.close();
                                 bbcode = "[" + tag + "=" + value1 + "]" + (value2 || "") + "[/" + tag + "]";
                                 break;
                              default:
                                 return d.modal.close();
                           }
                           complex_insert("", bbcode, null);
                           d.modal.close();
                        } else {
                           d.modal.close();
                        }
                     }
                  );
               },
            tag_ytube:
               function() {
                  var m =
                     SEN.GUI.Dialogs.spawn(
                        {
                           innerHTML: "\
<div class='dialog-header'>\n\
   <span>BBCode: YOUTUBE</span>\n\
</div>\n\
<label class='above'>Paste the URL of the YouTube video here:</label>\n"+
                                      "<input type='text'><div class='modal-form-error'></div>", // empty DIV is for error messages.
                           buttons: ["OK", "Cancel"],
                           default_button: 0
                        }
                     );
                  $(m.contentNode).find("input").focus();
                  $(m).bind("Close", function() {$("#xtext").focus()});
                  $(m).bind(
                     "ButtonClicked",
                     function(e, d) {
                        if (!d.index) {
                           var URL = $(d.modal.contentNode).find("input")[0].value;
                           if (!URL) {
                              $(d.modal.contentNode).find(".modal-form-error").html("You need to enter a URL.");
                              return;
                           }
                           var id = URL.match(/^(?:[^@]*@)?https?\:\/{1,}(?:[\w-]+\.)?youtube\.com[\/\\]watch\?(?:[^\b]*&)?v=([a-zA-Z0-9_-]+)(?:&[^\b]*)?/);
                           if (!id || id.length == 1) {
                              // apparently an invalid URL; warn.
                              $(d.modal.contentNode).find(".modal-form-error").html("The URL you entered does not appear to be a valid YouTube video address.");
                              return;
                           }
                           complex_insert("[youtube="+id[1]+"]", "0", "0");
                           d.modal.close();
                        } else {
                           d.modal.close();
                        }
                     }
                  );
               }
         },
      init:
         function() {
         }
   };
/* END   NEW JS */

var b_tag = 0;
var i_tag = 0;
var u_tag = 0;
var s_tag = 0;
var sup_tag = 0;
var sub_tag = 0;
var quote_tag = 0;
var font_tag = 0;
var size_tag = 0;
var color_tag = 0;
var xtext_height = 0;
var align_tag = 0;
var youtube = 0;
var youtubeobj = 0;

function xtext_chars(maxx)
{
	var xtext = get_by_id('xtext');
	var maxxx = get_by_id('xtext_max');
	maxxx.innerHTML = maxx - xtext.value.length;
}

// optimize these ;o





function enlarge(text_element, start_height)
{
	var obj = get_by_id(text_element);
	xtext_height++;
	do_height(obj, start_height);
}
function shorten(text_element, start_height)
{
	var obj = get_by_id(text_element);
	xtext_height--;
	do_height(obj, start_height);
}
function do_height(obj, start_height)
{
	if (xtext_height == 0)
		var change = start_height;
	else if (xtext_height < -1)
		var change = start_height - 75;
	else
		var change = start_height + xtext_height * 75;
	obj.style.height = change + "px";	
}





function ytube2(obj)
{
	youtubeobj = obj;
	var lol = get_by_id('vars1a');
	inline_popup_3("Youtube Code (BETA)", "Working on this... <input style='width:200px;' class='text' id='vars1a' type='text'><br><input type='button' class='submit' value='Insert' onclick='javascript:ytube2(\""+ lol.value +"\")'>", "void");
}




function ytube(node) {
   SEN.BBCode.Tags.tag_ytube();
}
function tag(node, tag_name) {
   SEN.BBCode.Tags.generic(node, tag_name);
}
function font(node, tag_name) {
   SEN.BBCode.Tags.tag_font(node, tag_name);
}
function vari(node, tag_name) {
   SEN.BBCode.Tags.tag_vari(node, tag_name);
}
function special(node) {
   SEN.BBCode.Tags.tag_special(node);
}
function trigger() {
   SEN.BBCode.Tags.tag_trigger();
}
function tag_list() {
   SEN.BBCode.Tags.tag_list();
}
function quoteaa(node) {
   SEN.BBCode.Tags.tag_quote_name(node);
}
function quote(node) {
   SEN.BBCode.Tags.tag_quote_name(node);
}

function smilie(display) {
   complex_insert("", " " + display + " ", null);
}

/* fixxy?  Ain't fucking with this now */
// Reformatted. Shouldn't require too many other changes, as
// it seems to work in all browsers. ~ DavidJCobb
function complex_insert(topen, tclose, tstatus, tdoboth, tobj) {
   var obj = tobj || $("#xtext")[0],
       xinput = "",
       rvalue = false,
       rstatus = null;
   if (obj.selectionStart == null) {
      obj.focus();
      var stext = document.selection;
      var range = stext.createRange();
      //range.colapse; // 0_o misspelled and doesn't do anything
      if(range.text.length > 0)
         xinput = topen + range.text + tclose;
      else {
         rvalue = true;
         xinput = tstatus == 0 ? topen : tclose;
      }
      range.text = xinput;
      range.select();
   } else if (obj.selectionStart != null) {
      scrollsave = obj.scrollTop;
      tlength = obj.textLength;
      selstart = obj.selectionStart;
      selend = obj.selectionEnd;
      tstart = "";
      tmiddle = "";
      tend = "";
      if (selstart == selend) {
         rvalue = true;
         if (tdoboth)
            tmiddle = topen + tclose;
         else if (tstatus == 1)
            tmiddle = tclose;
         else if (tstatus == 0)
            tmiddle = topen;
         else
            tmiddle = tclose;
      } else
         tmiddle = topen + (obj.value).substring(selstart, selend) + tclose;
      tstart = (obj.value).substring(0, selstart);
      tend = (obj.value).substring(selend, tlength);
      obj.value = tstart + tmiddle + tend;
      var position = selstart + (tmiddle.length);
      obj.selectionStart = position;
      obj.selectionEnd = position;
      obj.scrollTop = scrollsave;
   }	
   if (tstatus != null && rvalue)
      rstatus = 0 + !(tstatus == 1);
   obj.focus();
   return rstatus;
}
