/**********************************************************
 * BC - "Blah Code" script                                *
 * Copyright © 2001-2006 E-Blah.                          *
 * Part of the E-Blah Software.  Released under the GPL.  *
 * Amended and maintained by Journal Interactive under section 5 of the GPL *
 *                           Last Update: 9 October, 2006 – JI Oct 12th, 2009*
 **********************************************************/

function use(u,c,f)
{
    if (!u) u= '';
    if (!c) c= '';
    if (!f) f= 'element.description';

    var bb_obj= document.forms['post'].elements[f]; /*document.getElementById(f);*/
    
    bb_obj.focus();
    if (typeof document.selection!= 'undefined')
    {
        var r= document.selection.createRange();
        var iT= r.text;
        r.text= u+ iT+ c;
        if (iT.length!= 0) r.moveStart('character', bb_obj, iT.length);
        r.select();
    }
    else if (bb_obj.selectionStart || bb_obj.selectionStart == '0')
    {
        var ia= bb_obj.selectionStart, iz= bb_obj.selectionEnd;
        var iT= bb_obj.value.substring(ia, iz);
        bb_obj.value= bb_obj.value.substr(0,ia)+ u+ iT+ c+ bb_obj.value.substr(iz);
        var p= ia+ u.length+ iT.length+ c.length;
        bb_obj.focus();
        bb_obj.selectionStart= p;
        bb_obj.selectionEnd= p;
        bb_obj.focus();
    }
    else
    {
        bb_obj.value += u+c;
        bb_obj.focus();
    }
}
function openuse(u,f)
{
    if (!f) f= 'element.description'; 
    var bbo_obj = opener.document.forms['post'].elements[f];
    bbo_obj.value += u;
}
function AddNewValue(bc,thenewvalue)
{
    if(bc != '' && thenewvalue != '')
    {
        use("["+bc+"="+thenewvalue+"]","[/"+bc+"]");
        document.forms['post'].size.value = '';
        document.forms['post'].color.value = '';
        document.forms['post'].face.value = '';
    }
}
function funclu (lookup)
{
    document.getElementById('about').innerHTML = eval('func_'+lookup);
}

// -----------------------------------------------------------------------
// Copyright (c) 2008, Stone Steps Inc. 
// All rights reserved
// http://www.stonesteps.ca/legal/bsd-license/
// Amended and Maintained by Journal Interactive
//
// This is a BBCode parser written in JavaScript. The parser is intended
// to demonstrate how to parse text containing BBCode tags in one pass 
// using regular expressions.
//
// The parser may be used as a backend component in ASP or in the browser, 
// after the text containing BBCode tags has been served to the client. 
//
// Following BBCode expressions are recognized:
//
// [b]bold[/b]
// [i]italic[/i]
// [u]underlined[/u]
// [s]strike-through[/s]
//
// [url]http://blogs.stonesteps.ca/showpost.asp?pid=33[/url]
// [url=http://blogs.stonesteps.ca/showpost.asp?pid=33][b]BBCode[/b] Parser[/url]]
// url will prepend http:// to anything that doesn't already begin with http:// or /
//
// [img]http://www.google.com/intl/en_ALL/images/logo.gif[/img]
//
// [quote]inline quote[/quote]
//
// text containing [noparse] [brackets][/noparse]
//
// -----------------------------------------------------------------------
var opentags;           // open tag stack
var crlf2br = true;     // convert CRLF to <br>?
var noparse = false;    // ignore BBCode tags?
var urlstart = -1;      // beginning of the URL if zero or greater (ignored if -1)
var mailstart = -1;      // beginning of the MAILTO: if zero or greater (ignored if -1)
var storedURL = "";    // needed to hold contents between tag beginning and end in-between loops

// aceptable BBcode tags, optionally prefixed with a slash -- removed pre|samp|code|colou?r|size|blockquote added img|quote
var tagname_re = /^\/?(?:b|i|u|noparse|url|mail|s|quote|img)$/;

// reserved, unreserved, escaped and alpha-numeric [RFC2396]
var uri_re = /^[-;\/\?:@&=\+\$,_\.!~\*'\(\)%0-9a-z]{1,512}$/i;

// main regular expression: CRLF, [tag=option], [tag] or [/tag]
var postfmt_re = /([\r\n])|(?:\[([a-z]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])(?:([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?|(?:\[\/([a-z]{1,16})\])/ig;
var smileyfmt_re = /\s(>:\()|(:B)|(8\))|(:'\()|(;D)|(\?\?\))|(:K\))|(:x)|(:D)|(::\))|(:\()|(:o)|(:\))|(:P)|(:-\/)|(;\))/ig;

// stack frame object
function taginfo_t(bbtag, etag)
{
   this.bbtag = bbtag;
   this.etag = etag;
}

// check if it's a valid BBCode tag
function isValidTag(str)
{
   if(!str || !str.length)
      return false;

   return tagname_re.test(str);
}

function textToSmileyCB(mstr, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, offset, string)
{
   if(m1 && m1.length) 
      return "<img src='http://media.journalinteractive.com/designimages/angry.gif'>";
   if(m2 && m2.length) 
      return "<img src='http://media.journalinteractive.com/designimages/blush.gif'>";
   if(m3 && m3.length) 
      return "<img src='http://media.journalinteractive.com/designimages/cool.gif'>";
   if(m4 && m4.length) 
      return "<img src='http://media.journalinteractive.com/designimages/cry.gif'>";
   if(m5 && m5.length) 
      return "<img src='http://media.journalinteractive.com/designimages/grin.gif'>";
   if(m6 && m6.length) 
      return "<img src='http://media.journalinteractive.com/designimages/huh.gif'>";
   if(m7 && m7.length) 
      return "<img src='http://media.journalinteractive.com/designimages/kiss.gif'>";
   if(m8 && m8.length) 
      return "<img src='http://media.journalinteractive.com/designimages/lipsx.gif'>";
   if(m9 && m9.length) 
      return "<img src='http://media.journalinteractive.com/designimages/lol.gif'>";
   if(m10 && m10.length) 
      return "<img src='http://media.journalinteractive.com/designimages/roll.gif'>";
   if(m11 && m11.length) 
      return "<img src='http://media.journalinteractive.com/designimages/sad.gif'>";
   if(m12 && m12.length) 
      return "<img src='http://media.journalinteractive.com/designimages/shock.gif'>";
   if(m13 && m13.length) 
      return "<img src='http://media.journalinteractive.com/designimages/smiley.gif'>";
   if(m14 && m14.length) 
      return "<img src='http://media.journalinteractive.com/designimages/tongue.gif'>";
   if(m15 && m15.length) 
      return "<img src='http://media.journalinteractive.com/designimages/undecided.gif'>";
   if(m16 && m16.length) 
      return "<img src='http://media.journalinteractive.com/designimages/wink.gif'>";
   return "";
}

//
// m1 - CR or LF
// m2 - the tag of the [tag=option] expression
// m3 - the option of the [tag=option] expression
// m4 - the contents in between opening and closing tags
// m5 - the end tag of the [/tag] expression
//
function textToHtmlCB(mstr, m1, m2, m3, m4, m5, offset, string)
{
   //
   // CR LF sequences
   //
   if(m1 && m1.length) {
      if(!crlf2br)
         return mstr;

      switch (m1) {
         case '\r':
            return "";
         case '\n':
            return "<br>";
      }
   }

   //
   // handle start tags
   //
   if(isValidTag(m2)) {
      // if in the noparse state, just echo the tag
      if(noparse)
         return "[" + m2 + "]" + m4;

      // ignore any tags if there's an open option-less [url] tag
      if(opentags.length && opentags[opentags.length-1].bbtag == "url" && urlstart >= 0)
         return "[" + m2 + "]" + m4;

      // ignore any tags if there's an open option-less [mail] tag
      if(opentags.length && opentags[opentags.length-1].bbtag == "mail" && mailstart >= 0)
         return "[" + m2 + "]" + m4;

      switch (m2) {
         case "s":
            opentags.push(new taginfo_t(m2, "</span>"));
            return "<span style=\"text-decoration: line-through\">" + m4;

         case "noparse":
            noparse = true;
            return m4;

         case "url":
            opentags.push(new taginfo_t(m2, "</a>"));
            
            // check if there's a valid option
            if(m3 && uri_re.test(m3)) {
               // if there is, output a complete start anchor tag
               urlstart = -1;
               var linkurl = m3;
               if(linkurl.length && linkurl.substr(0,1) != "/" && linkurl.substr(0,7).toLowerCase()  != "http://"){
                  linkurl = "http://" + linkurl;
               }
               return "<a href=\"" + linkurl + "\">" + m4;
            }

            // otherwise, remember the URL offset 
            urlstart = mstr.length + offset;

            // store the contents in between tags, for it won't be in scope when needed dealing with the end tag
            storedURL = m4;
            if(storedURL.length && storedURL.substr(0,1) != "/" && storedURL.substr(0,7).toLowerCase()  != "http://"){
               storedURL= "http://" + storedURL;
            }

            // and treat the text following [url] as a URL
            return "<a href=\"" + storedURL;

         case "mail":
            opentags.push(new taginfo_t(m2, "</a>"));
            
            // check if there's a valid option
            if(m3 && uri_re.test(m3)) {
               // if there is, output a complete start anchor tag
               mailstart = -1;
               return "<a href=\"mailto:" + m3 + "\">" + m4;
            }

            // otherwise, remember the mailto: offset 
            mailstart = mstr.length + offset;

            // store the contents in between tags, for it won't be in scope when needed dealing with the end tag
            storedURL = m4;

            // and treat the text following [mail] as a mailto-URL
            return "<a href=\"mailto:" + storedURL;

         case "quote":

            opentags.push(new taginfo_t(m2, "</fieldset>"));

            // check if there's a valid option
            if(m3 && uri_re.test(m3)) {
               return "<fieldset class='forumQuote'><legend class='quoteAuthor'>" + m3 + "</legend>" + m4;
            }

            return "<fieldset class='forumQuote'>" + m4;

         case "img":
            opentags.push(new taginfo_t(m2, "</img>"));
            return "<img src=\"" + m4;

         default:
            // [samp], [b], [i] and [u] don't need special processing
            opentags.push(new taginfo_t(m2, "</" + m2 + ">"));
            return "<" + m2 + ">" + m4;            
      }
   }

   //
   // process end tags
   //
   if(isValidTag(m5)) {
      if(noparse) {
         // if it's the closing noparse tag, flip the noparse state
         if(m5 == "noparse")  {
            noparse = false;
            return "";
         }
         
         // otherwise just output the original text
         return "[/" + m5 + "]";
      }
      
      // highlight mismatched end tags
      if(!opentags.length || opentags[opentags.length-1].bbtag != m5)
         return "<span style=\"color: red\">[/" + m5 + "]</span>";

      if(m5 == "url") {
         // if there was no option, use the content of the [url] tag
         if(storedURL) {
            var tempstr = storedURL;
            storedURL = "";
            return "\">" + tempstr + opentags.pop().etag;
         }
         
         // otherwise just close the tag
         return opentags.pop().etag;
      }
      else if(m5 == "mail") {
         // if there was no option, use the content of the [mail] tag
         if(storedURL) {
            var tempstr = storedURL;
            storedURL = "";
            return "\">" + tempstr  + opentags.pop().etag;
         }
         
         // otherwise just close the tag
         return opentags.pop().etag;
      }
      else if(m5 == "img") {
         return "\">" + opentags.pop().etag;
      }

      // other tags require no special processing, just output the end tag
      return opentags.pop().etag;
   }

   return mstr;
}

function parseSmileys(post)
{
   var result;

   // run the text through main regular expression matcher
   result = post.replace(smileyfmt_re, textToSmileyCB);
   return result;
}

//
// post must be HTML-encoded
//
function parseBBCode(post)
{
   var result, endtags, tag;

   // convert CRLF to <br> by default
   crlf2br = true;

   // create a new array for open tags
   if(opentags == null || opentags.length)
      opentags = new Array(0);

   // run the text through main regular expression matcher
   result = post.replace(postfmt_re, textToHtmlCB);

   // reset noparse, if it was unbalanced
   if(noparse)
      noparse = false;
   
   // if there are any unbalanced tags, make sure to close them
   if(opentags.length) {
      endtags = new String();
      
      // if there's an open [url] at the top, close it
      if(opentags[opentags.length-1].bbtag == "url") {
         opentags.pop();
         endtags += "\">" + post.substr(urlstart, post.length-urlstart) + "</a>";
      }

      // if there's an open [mail] at the top, close it
      if(opentags[opentags.length-1].bbtag == "mail") {
         opentags.pop();
         endtags += "\">" + post.substr(mailstart, post.length-mailstart) + "</a>";
      }

      // if there's an open [img] at the top, close it
      if(opentags[opentags.length-1].bbtag == "img") {
         opentags.pop();
         endtags += "\">" + post + "</img>";
      }
      
      // close remaining open tags
      while(opentags.length)
         endtags += opentags.pop().etag;
   }

   return endtags ? result + endtags : result;
}

// eg: outputBBCode("post", "element.description", "outputPreview", "outputPreview2");
function outputBBCode(formName, ctrlInput, ctrlHtmlOut, ctrlEscapedOut)
{
   var out_html = document.getElementById(ctrlHtmlOut);
   if(ctrlEscapedOut)
      var out_escape = document.getElementById(ctrlEscapedOut);
   var html = parseBBCode(document.forms[formName].elements[ctrlInput].value);
   html = parseSmileys(html);
   if(out_escape) {
      if(!out_escape.firstChild)
         out_escape.appendChild(document.createTextNode(html));
      else   
         out_escape.replaceChild(document.createTextNode(html), out_escape.firstChild);
   }      
   out_html.innerHTML = html;
}

///////////////////////////////////////////////////////////

function removeBBCode(post)
{
   var result, endtags, tag;

   // convert CRLF to <br> by default
   crlf2br = true;

   // run the text through main regular expression matcher
   result = post.replace(postfmt_re, textToHtmlNoCB);   

   return result;
}

function textToHtmlNoCB(mstr, m1, m2, m3, m4, m5, offset, string)
{
    //alert("textToHtmlNoCB\nmstr = " + mstr + "\nm1 = " + m1 + "\nm2 = " + m2 + "\nm3 = " + m3 + "\nm4 = " + m4 + "\nm5 = " + m5 
    //+ "\noffset = " + offset + "\nstring = " + string);

   // CR LF sequences
   if(m1 && m1.length) {
      if(!crlf2br)
         return mstr;

      switch (m1) {
         case '\r':
            return "";
         case '\n':
            return " ";
      }
   }

   // handle start tags
   if(isValidTag(m2)) {
      switch (m2) {
         case "img":
            return "";

         default:
            return m4;            
      }
   }
   
   // process end tags
   if(isValidTag(m5)) {      
      return "";
   }

   return mstr;
}

var smileyfmt2_re = /\s*?((>:\()|(:B)|(8\))|(:'\()|(;D)|(\?\?\))|(:K\))|(:x)|(:D)|(::\))|(:\()|(:o)|(:\))|(:P)|(:-\/)|(;\)))/ig;

function removeSmileys(post)
{
   var result;

   // run the text through main regular expression matcher
   result = post.replace(smileyfmt2_re, "");
   return result;
}
