// Get Scroller for IE
function getScrollerWidth(){var inner=document.createElement('p');inner.style.width='100%';inner.style.height='200px';var outer=document.createElement('div');outer.style.position='absolute';outer.style.top='0px';outer.style.left='0px';outer.style.visibility='hidden';outer.style.width='200px';outer.style.height='150px';outer.style.overflow='hidden';outer.appendChild(inner);document.body.appendChild(outer);var w1=inner.offsetWidth;outer.style.overflow='scroll';var w2=inner.offsetWidth;if(w1===w2){w2=outer.clientWidth;};document.body.removeChild(outer);return (w1-w2);}

// Startup variables
var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Helpline messages
b_help = "{L_BBCODE_B_HELP}";
i_help = "{L_BBCODE_I_HELP}";
u_help = "{L_BBCODE_U_HELP}";
q_help = "{L_BBCODE_Q_HELP}";
c_help = "{L_BBCODE_C_HELP}";
l_help = "{L_BBCODE_L_HELP}";
o_help = "{L_BBCODE_O_HELP}";
p_help = "{L_BBCODE_P_HELP}";
w_help = "{L_BBCODE_W_HELP}";
a_help = "{L_BBCODE_A_HELP}";
s_help = "{L_BBCODE_S_HELP}";
f_help = "{L_BBCODE_F_HELP}";

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','\n[quote]','[/quote]','\n[code]','[/code]','\n[list]\n[*]','\n[/list]','\n[list=1]\n[*]','\n[/list]','\n[img]','[/img]','[url]','[/url]', '\n[*]', '');
imageTag = false;

if(document.getElementById('bbTools')){
  // Shows the help messages in the helpline window
  function helpline(help) {
    document.post.helpbox.value = eval(help + "_help");
  }
  
  // Replacement for arrayname.length property
  function getarraysize(thearray) {
    for (i = 0; i < thearray.length; i++) {
      if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
        return i;
    }
    return thearray.length;
  }
  
  // Replacement for arrayname.push(value) not implemented in IE until version 5.5
  // Appends element to the array
  function arraypush(thearray,value) {
    thearray[ getarraysize(thearray) ] = value;
  }
  
  // Replacement for arrayname.pop() not implemented in IE until version 5.5
  // Removes and returns the last element of an array
  function arraypop(thearray) {
    thearraysize = getarraysize(thearray);
    retval = thearray[thearraysize - 1];
    delete thearray[thearraysize - 1];
    return retval;
  }
  
  function checkForm() {
    formErrors = false;
  
    if (formErrors) {
      alert(formErrors);
      return false;
    }
    else {
      bbstyle(-1);
      //formObj.preview.disabled = true;
      //formObj.submit.disabled = true;
      return true;
    }
  }
  
  // include the insert smilies fixes for Mozilla
  function emoticon(text) {
    //emoticon_insert(document.post.message, text);
    emoticon_insert(document.getElementById('composerInput'), text);
  }
  
  function emoticon_insert(txtarea, text) {
    text = ' ' + text + ' ';
    if (txtarea.createTextRange && txtarea.caretPos) {
      var caretPos = txtarea.caretPos;
      var baseHeight;
      if ( is_ie ) {
        baseHeight = document.selection.createRange().duplicate().boundingHeight;
      }
      if (baseHeight != txtarea.caretPos.boundingHeight) {
        txtarea.focus();
        storeCaret(txtarea);
      }
      caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
      txtarea.focus();
    }
    else if ( (txtarea.selectionEnd | txtarea.selectionEnd == 0) && (txtarea.selectionStart | txtarea.selectionStart == 0) ) {
      mozInsert(txtarea, text, "");
    }
    else {
      txtarea.value  += text;
      txtarea.focus();
    }
  }
  
  // insert smilies fixes for Mozilla
  function mozInsert(txtarea, openTag, closeTag) {
    var scrollTop = ( typeof(txtarea.scrollTop) == 'number' ? txtarea.scrollTop : -1 );
    if (txtarea.selectionEnd > txtarea.value.length) {
      txtarea.selectionEnd = txtarea.value.length;
    }
  
    var startPos = txtarea.selectionStart;
    var endPos = txtarea.selectionEnd + openTag.length;
    txtarea.value = txtarea.value.slice(0, startPos) + openTag + txtarea.value.slice(startPos);
    txtarea.value = txtarea.value.slice(0, endPos) + closeTag + txtarea.value.slice(endPos);
    txtarea.selectionStart = startPos + openTag.length;
    txtarea.selectionEnd = endPos;
    txtarea.focus();
    if (scrollTop >= 0) {
      txtarea.scrollTop = scrollTop;
    }
  }
  
  function bbfontstyle(bbopen, bbclose) {
    //var txtarea = document.post.message;
    var txtarea = document.getElementById('composerInput');
  
    if ((clientVer >= 4) && is_ie && is_win) {
      theSelection = document.selection.createRange().text;
      if (!theSelection) {
        txtarea.value += bbopen + bbclose;
        txtarea.focus();
        return;
      }
      document.selection.createRange().text = bbopen + theSelection + bbclose;
      txtarea.focus();
      return;
    }
    else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0)) {
      mozWrap(txtarea, bbopen, bbclose);
      return;
    }
    else {
      txtarea.value += bbopen + bbclose;
      txtarea.focus();
    }
    storeCaret(txtarea);
  }
  
  
  function bbstyle(bbnumber) {
    //var txtarea = document.post.message;
    txtarea = document.getElementById('composerInput');
  
    txtarea.focus();
    donotinsert = false;
    theSelection = false;
    bblast = 0;
      
    if (bbnumber == -1) { // Close all open tags & default button names
      while (bbcode[0]) {
        butnumber = arraypop(bbcode) - 1;
        txtarea.value += bbtags[butnumber + 1];
        
        //buttext = eval('document.post.addbbcode' + butnumber + '.value');
        //eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
        
        elementId = 'addbbcode' + butnumber;
        document.getElementById(elementId).firstChild.className = 'closed';
      }
      imageTag = false; // All tags are closed including image tags :D
      txtarea.focus();
      return;
    }
  
    if ((clientVer >= 4) && is_ie && is_win) {
      theSelection = document.selection.createRange().text; // Get text selection
      if (theSelection) {
        // Add tags around selection
        document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
        txtarea.focus();
        theSelection = '';
        return;
      }
    }
    else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0)) {
      mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
      return;
    }
    
    // Find last occurance of an open tag the same as the one just clicked
    for (i = 0; i < bbcode.length; i++) {
      if (bbcode[i] == bbnumber+1) {
        if(bbnumber == 18) {
        }
        else {
          bblast = i;
          donotinsert = true;
        }
      }
    }
  
    if (donotinsert) {    // Close all open tags up to the one just clicked & default button names
      while (bbcode[bblast]) {
        butnumber = arraypop(bbcode) - 1;
        txtarea.value += bbtags[butnumber + 1];
          
        //buttext = eval('document.post.addbbcode' + butnumber + '.value');
        //eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
          
        elementId = 'addbbcode' + butnumber;
        document.getElementById(elementId).firstChild.className = 'closed';
          
        imageTag = false;
      }
      txtarea.focus();
      return;
    }
    else { // Open tags
      if (imageTag && (bbnumber != 14)) {    // Close image tag before adding another
        txtarea.value += bbtags[15];
        lastValue = arraypop(bbcode) - 1;  // Remove the close image tag from the list
        //document.post.addbbcode14.value = "Img";  // Return button back to normal state
        imageTag = false;
      }
      
      // Open tag
      txtarea.value += bbtags[bbnumber];
      if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
         
      arraypush(bbcode,bbnumber+1);
      
      //eval('document.post.addbbcode'+bbnumber+'.value += "*"');
      
      elementId = 'addbbcode' + bbnumber;
      document.getElementById(elementId).firstChild.className = 'active';
      
      txtarea.focus();
      return;
    }
    storeCaret(txtarea);
  }
  
  // From http://www.massless.org/mozedit/
  function mozWrap(txtarea, open, close) {
    var selLength = txtarea.textLength;
    var selStart = txtarea.selectionStart;
    var selEnd = txtarea.selectionEnd;
    if (selEnd == 1 || selEnd == 2) 
      selEnd = selLength;
  
    var s1 = (txtarea.value).substring(0,selStart);
    var s2 = (txtarea.value).substring(selStart, selEnd)
    var s3 = (txtarea.value).substring(selEnd, selLength);
    txtarea.value = s1 + open + s2 + close + s3;
    return;
  }
  
  // Insert at Claret position. Code from
  // http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
  function storeCaret(textEl) {
    if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
  }
}


// SHOUTBOX JAVASCRIPT

// Global Variables
var shoutBox = false;
var shoutBoxLastUpdate = false;
var timestamp = parseInt(new Date().getTime().toString().substring(0, 10));
var refreshId = false;
var shoutboxHTML = '';
var newShoutBox = true;
var scrollWidth = false;

window.addEvent('domready', function(el) {

  // Shoutbox Functionality
  if ($('shoutbox')) {
    // Variables
    var aniDuration = 500;
    //var tStamp = timestamp;
    if (is_logged_in == 1)
      var refreshInterval = 5000;
    else
      var refreshInterval = 10000;

    // REQUEST URLS
    shoutBox = $('shoutbox');
    var shoutContent = $('shoutboxContent');
    var shoutRender = $('shoutboxRender');
    var shoutConsole = $('shoutboxConsole');
    var shoutMessageConsole = $('shoutboxMessageConsole');
    var shoutLog = $('shoutLog');
    var shoutMessageLog = $('shoutMessageLog');
    var minLink = $('shoutboxMinimizeLink');
    var toggler = $('expandToggler');

    function update() {
      shoutBox.fireEvent('update');
    }

    // All events related to Shoutbox
    shoutBox.addEvents({
      'initialize': function() {
        scrollWidth = getScrollerWidth();
        cName = 'setShoutboxCookieKeepOpen=';
        cCookie = document.cookie + ";";
        str = cCookie.indexOf(cName);
        end = cCookie.indexOf(";",str);
        openShoutbox = unescape(cCookie.substring(str + cName.length, end));

        if (openShoutbox != 'open' && openShoutbox != 'close') {
          openShoutbox = 'open';
        }

        // Check Cookie to see if shoutbox should open
        if (openShoutbox == 'open') {
          //alert(scrollWidth);
          //alert($('shoutMessages').getSize().y +'::'+ $('sbMessages').getSize().y);
          if($('shoutMessages').getSize().y > $('sbMessages').getSize().y){
            $('shoutMessages').setStyle('width', $('sbMessages').getSize().y - scrollWidth);
          }
          
          var keepSize = $('sbMessages').getSize().x;
          var myResize = $('sbMessages').makeResizable({
                'handle': $('sbHandle'),
                'limit': {'x': [296, 296], 'y': [200, 600]}
          });
          
          var getComments = new Request({
                url: 'shoutbox_ajax.php?shoutbox_id=' + shoutRoom,
                onSuccess: function(commands) {
                  eval(commands);
                  refreshId = update.periodical(refreshInterval);
                }
          });
          getComments.send();

          // BUILD BUTTON EVENTS
          $('shoutboxExpandLink').removeEvents('click');
          $('shoutboxExpandLink').addEvent('click', function(e){shoutBox.fireEvent('maximize');});
          $('shoutboxMinimizeLink').addEvent('click', function(e){shoutBox.fireEvent('minimize');});
        
          $('shoutboxContent').setStyle('display', 'block');
          
          shoutBox.fireEvent('toNewest');
          shoutBox.fireEvent('buildComposer');
          
          minLink.style.display = 'inline';
          $('shoutboxExpandLink').style.display = 'none';
          toggler.style.display = 'block';
          
          newShoutBox = false;
        }
        else {
          $('shoutboxExpandLink').addEvent('click', function(e) {
            //openShoutbox = true;
            openShoutbox = 'open';
            shoutBox.fireEvent('initialize');
            shoutBox.fireEvent('setCollapsible', {'open': 'open'});
          });
          
          $('shoutboxExpandLink').style.display = 'inline';
          toggler.style.display = 'block';
        }
      },

      'setCollapsible': function(param) {
        cName = "setShoutboxCookieKeepOpen=";// cookie name for collapsible
        cDays  = 30;                         // data save days
        setPre = new Date();
        setPre.setTime(setPre.getTime() + (cDays*1000*24*3600));
        prd = setPre.toGMTString();
        document.cookie = cName + param['open'] + ";expires=" + prd;

        // if expanding shoutbox
        if (param['open'] == 'open' && newShoutBox) {
          shoutBox.fireEvent('initialize');
        }
      },

      'update': function() {
        var updateComments = new Request({
              method: 'post',
              //url: 'shoutbox_ajax.php?mode=refresh&shoutbox_id=' + shoutRoom + '&time=' + tStamp,
              url: 'shoutbox_ajax.php?mode=refresh&shoutbox_id=' + shoutRoom,
              onSuccess: function(commands) {
                eval(commands);
              }
        });
        updateComments.send();
      },

      'resetInterval': function() {
        $clear(refreshId);
        refreshId = update.periodical(refreshInterval);
      },

      'clearInterval': function() {
        $clear(refreshId);
      },

      'shoutLogger': function(param) {
        param['element'].innerHTML = param['string'];
      },

      'toggleConsole': function(param) {
        if (param['toggle']) {
          param['element'].set('opacity', 0);
          param['element'].style.display = 'block';
          param['element'].fade(1);
        }
        else {
          param['element'].fade(0);
          var action = function(){param['element'].style.display = 'none'}.delay(aniDuration + 10);
        }
      },

      'minimize': function() {
        $('shoutboxMinimizeLink').style.display = 'none';
        $('shoutboxExpandLink').style.display = 'inline';
        $('shoutboxContent').setStyle('display', 'none');
                
        shoutBox.fireEvent('setCollapsible', {'open': 'close'});
        shoutBox.fireEvent('clearInterval');
      },

      'maximize': function() {
        $('shoutboxContent').setStyle('display', 'block');
        shoutBox.fireEvent('toNewest');
        
        $('shoutboxExpandLink').style.display = 'none';
        $('shoutboxMinimizeLink').style.display = 'inline';
                
        // Set Cookie to save Shoutbox open State
        shoutBox.fireEvent('setCollapsible', {'open': 'open'});
        shoutBox.fireEvent('resetInterval');
      },

      'delete': function(param) {
        var shout_id = param['shout_id'].replace('shout_', '');
        var deleteComments = new Request({
              method: 'post',
              url: 'shoutbox_ajax.php?mode=delete&p=' + shout_id + '&shoutbox_id=' + shoutRoom,
              onSuccess: function(commands) {
                eval(commands);
              }
        });

        deleteComments.send();
      },

      'removeComment': function(param) {
        $('shout_' + param['shout_id']).destroy();  
      },

      'submitComment': function(param) {
        shoutBox.fireEvent('shoutLogger', {'element': shoutMessageLog, 'string': sht_submitAlert});
        shoutBox.fireEvent('toggleConsole', {'element': shoutMessageConsole, 'toggle': true}, 50);

        var commentString = $('composerInput').value;
        //if ($('timestamp'))
        //    var timestamp = $('timestamp').className;

        // Validate Sumbission before Ajaxing
        if (commentString === '' || commentString === sht_enterComment || commentString === ' ' || commentString === '  ' || commentString === '   ') {
          // Display 'Enter a Comment Message'
          $('shoutboxMessageConsole').className = 'error';
          shoutBox.fireEvent('shoutLogger', {'element': shoutMessageLog, 'string': 'Please Enter a Comment'});

          var hideit = function(){ $('shoutMessageLog').fade(0) }.delay(750);
          var showit = function(){ $('shoutMessageLog').fade(1) }.delay(1255);
          var hideit = function(){ $('shoutMessageLog').fade(0) }.delay(2250);
          var showit = function(){ $('shoutMessageLog').fade(1) }.delay(2755);
          var errorit = function() {
                $('composerInput').className = 'error';
                $('composerInput').value = sht_enterComment;
                $('composerInput').blur();
          }.delay(3000);

          shoutBox.fireEvent('toggleConsole', {'element': shoutMessageConsole, 'toggle': false}, 3500);
          shoutBox.fireEvent('shoutLogger', {'element': shoutMessageLog, 'string': ''}, 4200);
          var revertit = function(){$('shoutboxMessageConsole').className = '';}.delay(4250);

          shoutBox.fireEvent('toggleSubmitAbility', true, 3000);          
        }
        else if(true) {
          // Clear auto refresh 
          refreshId = $clear(refreshId);

          // prevent Duplicate Sending
          shoutBox.fireEvent('preventSubmit');
          shoutBox.fireEvent('toggleConsole', {'element': shoutMessageConsole, 'toggle': false}, 1000);

          // Reset Update Timer so as not to overlap Requests
          shoutBox.fireEvent('resetInterval');

           // send data as POST
           var sendComments = new Request({
                 method: 'post',
                 //url: 'shoutbox_ajax.php?mode=submit&shoutbox_id=' + shoutRoom + '&time=' + tStamp,
                 url: 'shoutbox_ajax.php?mode=submit&shoutbox_id=' + shoutRoom,
                 data: {'data' : $('composerInput').value},
                 onSuccess: function(commands) {
                   eval(commands);
                   shoutBox.fireEvent('allowSubmit', true, 6000);
                 }
           });
           sendComments.send();

           shoutBox.fireEvent('focusComposer',{}, 900);
           shoutBox.fireEvent('emptyComposer',{}, 1000);

           var countdown5 = function(){$('sendComment').innerHTML = '<strong class="waiting">' + sht_waiting + ' (5)</strong>'}.delay(1001);
           var countdown4 = function(){$('sendComment').innerHTML = '<strong class="waiting">' + sht_waiting + ' (4)</strong>'}.delay(2000);
           var countdown3 = function(){$('sendComment').innerHTML = '<strong class="waiting">' + sht_waiting + ' (3)</strong>'}.delay(3000);
           var countdown2 = function(){$('sendComment').innerHTML = '<strong class="waiting">' + sht_waiting + ' (2)</strong>'}.delay(4000);
           var countdown1 = function(){$('sendComment').innerHTML = '<strong class="waiting">' + sht_waiting + ' (1)</strong>'}.delay(5000);

          // Reset Update Timer so as not to overlap Requests
          shoutBox.fireEvent('resetInterval');
        }
      },

      'injectComment': function(param) {
        var comment = param['string'];
        var username = param['username'];
        var userId = param['user_id'];
        var date = param['date'];
        var rank = param['rank'];
        var delIcon = param['del_icon'];
        var newTimestamp = param['timestamp'];

//        if (newTimestamp || newTimestamp !== '') {
//          tStamp = newTimestamp;
//        }

        shoutBoxLastUpdate = date;
        date = date.replace('Today, at', '');
        var hasRank = '';
        var rankString = '';
        if (rank != '') {
          rankString = '<span class="rank">' + rank +  '</span>';
          hasRank = ' ranked';
        }
        var delString = '';
        if (delIcon != '') {
          delString = '<div class="deleteShout">' + delIcon + '</div>';  
        }
        
        commentClass = hasRank + ' aComment';
                
        // CHECK TO MAKE SURE COMMENT IS NOT ALREADY ENTERED
        if(!$('shout_' + param['shout_id'])) {
          // Build and Inject Comment
          var newHtml = delString + '<div class="shoutComment"><span class="name"><a href="' + url_profile + '/user/' + userId  + '">' + username + '</a></span><span class="rankingTitle">' + rankString + '</span><span class="date">&nbsp;&raquo;&nbsp;' + date + '</span><br /><span class="comment">' + comment + '</span></div>';
          var newCommentT = new Element('div', {
                'id': 'shout_' + param['shout_id'],
                'class': commentClass + ' newComment',
                'html': newHtml
          });
          newCommentT.inject('shoutMessages');
        }
      },

      'toNewest': function() {
        var messageScroller = new Fx.Scroll('sbMessages');
        messageScroller.toBottom();
        messageScroller= false;
                
        $$('#shoutbox .deleteComment').each(function(element) {
          element.removeEvents('click');
          element.addEvent('click', function(event) {
            shoutBox.fireEvent('delete', {'shout_id': element.getParent('.newComment').getProperty('id')});
          });
        });
      },

      'buildComposer': function() {
        if ($('composerInput')) {
          $('composerInput').addEvents({
            'focus': function(){
              this.className = '';
              if ($('composerInput').value.contains(sht_enterComment)) {
                $('composerInput').value = '';
              }
            },
            'blur': function(){
              if ($('composerInput').value === '') {
                $('composerInput').value = sht_enterComment;
              }
            },
            'keypress': function(event){
              if (event.key === 'enter') {
                event.stop();
                shoutBox.fireEvent('preventSubmit');
                shoutBox.fireEvent('submitComment');
              }
              else if(this.value.length >= 150) {
                //event.stop();
              }
            },
            'keydown': function(event) {
              CONTROL = event.control;
              KEY = event.key;
            
              if(CONTROL && KEY === 'b'){event.preventDefault();bbstyle(0);}
              if(CONTROL && KEY === 'u'){event.preventDefault();bbstyle(4);}
              if(CONTROL && KEY === 'i'){event.preventDefault();bbstyle(2);}
              if(CONTROL && KEY === 'l'){event.preventDefault();bbstyle(16);}
            
              if(CONTROL && KEY === 'ü'){event.preventDefault(bbstyle(-1));}
            }
          });

          // Submit Button fires submitComment event
          $('sendComment').addEvent('click', function(e) {
            e.stop();
            shoutBox.fireEvent('preventSubmit');
            shoutBox.fireEvent('submitComment');
          });
        }
      },

      'emptyComposer': function() {
        $('composerInput').value = '';
      },
            
      'focusComposer': function() {
        $('composerInput').focus();
      },

      'refreshComments': function() {
      },

      'allowSubmit': function(toggle) {
        $('sendComment').innerHTML = '<strong>' + sht_submitButton + '</strong>';
        
        $('sendComment').removeEvents('click');
        $('composerInput').removeEvents('keypress');
                
        $('sendComment').addEvent('click', function(e) {
          shoutBox.fireEvent('submitComment');
        });
        $('composerInput').addEvent('keypress', function(event) {
          if (event.key === 'enter') {
            event.stop();
            shoutBox.fireEvent('submitComment');
          };
        });
      },

      'preventSubmit': function(){
        $('sendComment').removeEvents('click');
        $('composerInput').removeEvents('keypress');
        $('composerInput').addEvent('keypress', function(event){
          if (event.key === 'enter') {
            event.stop();
          }
        });
      }
    });

    // SHOUTBOX INITIALIZE
    shoutBox.fireEvent('initialize');
  }
  ////////////////////////// END SHOUTBOX //////////////////////
});
