var sendReq = getXmlHttpRequestObject();    // object to send new shout
var receiveReq = getXmlHttpRequestObject(); // object to get new shouts
var delReq = getXmlHttpRequestObject(); // object to delete all shouts
var killReq = getXmlHttpRequestObject(); // object to delete a single shout
var lastMessage = 0;
var mTimer;
var shoutcolor = 0;
var call = 0;
var tolerance = xy_megaboxreload * 2 - 1;
var alt = 0;
   /* for Mozilla */
   if (document.addEventListener) {
       document.addEventListener("DOMContentLoaded", init, false);
   }

   /* for Internet Explorer */
   /*@cc_on @*/
   /*@if (@_win32)
       document.write("<script defer src=/megabox/js/ie_onload.js><"+"/script>");
   /*@end @*/
   /*@if (@_win32)
       init();
   /*@end @*/
   /* for other browsers */
  // window.onload = init;

/* For Opera : */
if (navigator.userAgent.indexOf("Opera")!=-1
    && document.getElementById) type="OP";

/* Internet Explorer e.g. IE4 upwards : */
if (document.all) type="IE";

/* For Netscape version 4 : */
if (document.layers) type="NN";

/* Mozila e.g. Netscape 6 upwards */
if (!document.all && document.getElementById) type="MO";

if (type=="IE") {
   init();

}
// Get messages for the first time side loads
//window.onload
   function init() {
       // quit if this function has already been called
       if (arguments.callee.done) return;

       // flag this function so we don't do the same thing twice
       arguments.callee.done = true;

       // get megabox content for the first time
       if(mbox_show == 1){
            mTimer = window.setTimeout("get_shouts()",1000);

       }
   }



// search and replace like in php single replacement
function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

// search and replace like in php with arrays
function array_replace(searcharray, replacearray, subject) {
    for (var i=0; i<searcharray.length;i++) {
        subject = subject.split(search[i]).join(replace[i]);
      }
    return subject;
}

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		document.getElementById('chatBox').innerHTML =
		'Status: Cound not create XmlHttpRequest Object.' +
		'Consider upgrading your browser.';
	}
}

//Function for handling the return of chat text
function handleGet_shouts() {
   window.clearTimeout(mTimer);

	if (receiveReq.readyState == 4) {
	  if(type == 'IE'){
        var chat_div = document.all('chatBox');
	  }
	  else 	var chat_div = document.getElementById('chatBox');
        var noautoscroll=document.getElementById('autoScroll');
        //if(lastMessage == 0) chat_div.innerHTML = '';
		var xmldoc = receiveReq.responseXML;
        var d = new Date();
        var timestamp = Math.round(d.getTime()/1000);
        if(xmldoc) {
          lastMessage = xmldoc.getElementsByTagName("lst")[0].firstChild.nodeValue;
          var ismessage = xmldoc.getElementsByTagName("shout")[0].firstChild.nodeValue;
        }

// newest shout on bottom (standard)
    if(xmldoc && lastMessage <= 100 || xmldoc && lastMessage > alt && ismessage != 0) {

		var message_nodes = xmldoc.getElementsByTagName("text");
        if(message_nodes.length < mbox_shoutnr) {
        var start = 0;
        }
        else var start = message_nodes.length - mbox_shoutnr;
        var n_messages = message_nodes.length;
        if(n_messages > 1) chat_div.innerHTML ='';
        var userid =  xmldoc.getElementsByTagName("shout");
		for (var i = start; i < n_messages; i++) {
   //empty shoutwindow if all messages are deleted
            if(userid[0].getAttribute('userid').value == 0 || userid.length ==1) chat_div.innerHTML ='';


			var text_node = message_nodes[i].getElementsByTagName("shout");
            if(text_node[0].firstChild.nodeValue!='') {
            if(shoutcolor % 2 == 0) text_node[0].firstChild.nodeValue = str_replace('sboxfirstrow','sboxsecondrow',text_node[0].firstChild.nodeValue);
		   	chat_div.innerHTML += unescape(text_node[0].firstChild.nodeValue);
            xymbox_image(xy_megabox_imagesize);
            shoutcolor++;
		}


     if(n_messages > 0 && text_node[0].firstChild.nodeValue != 'true') {
          var lastShouter = userid[n_messages-1].getAttribute('userid');

          if (lastShouter != 0 && lastShouter != shouterid && document.getElementById('Soundoff').checked!=true && call > 1 && parseInt(lastMessage) + parseInt(tolerance) > timestamp) {
              document.getElementById('mboxsign').innerHTML = '&nbsp;'+newshoutsign;
              }
        }

  }


          if(noautoscroll.checked!=true) {
            if(sortorder == 'ASC') chat_div.scrollTop = chat_div.scrollHeight;
            else chat_div.scrollTop = 0;
          }
          check_rights();
        }




	}
     alt = lastMessage;
    mTimer = window.setTimeout('get_shouts()',xy_megaboxreload*1000);
    delete receiveReq;
}

function refresh() {
window.clearTimeout(mTimer);
lastMessage = '0';
if(type == 'IE') {
  document.all('chatBox').innerHTML='';
}
else document.getElementById('chatBox').innerHTML = '';
clear();
get_shouts();
}

//Get the current messages from the server
function get_shouts() {

	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
        if(lastMessage == '') lastMessage = 100;
		receiveReq.open("GET", 'xy_megabox.php?action=getmessages&last=' + lastMessage + '&wiwsite=' + wiwsite + '&sid=' + sessionhash, true);
		receiveReq.onreadystatechange = function(){handleGet_shouts();};
        receiveReq.send(null);
        call++;
	}
       //lastMessage = get_last_shouttime();
}

//Add a message.
function do_shout(shouts,shoutername) {
    if (can_mboxshout != 1) alert(unescape(XY_MEGABOX_J_MESSAGE_NOGUESTSHOUTS));
    else if(trim(shoutername)=='') alert(unescape(XY_MEGABOX_J_NOGUESTNAME));
    else {
      if(checkban(shouts)==true) {
      	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
              search = new Array('\%B4','\%60');
              replace = new Array('\%27','\27');
              shouts = array_replace(search,replace,shouts);
      		sendReq.open("POST", 'xy_megabox.php?action=addshout', true);
      		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
              sendReq.onreadystatechange = handleDo_shout;
      		  var param = '&message='+ addslashes(str_replace('&','&amp;',shouts));
              param += '&name='+ shoutername;
              param += '&sid='+ sessionhash;

      		sendReq.send(param);
      	}
      }
    }
}

//Update page after shout.
function handleDo_shout() {
	get_shouts();
    clear();
}


// send message (submit) on ENTER
function sendMessage(e,message,shoutername)  {
	var key = (e.keyCode ? e.keyCode : e.which);

    if(message.length > shoutlength) {
      document.getElementById('message').value = message.substr(0,shoutlength);
    }
    if (key == 13) {
      do_shout(escape(message),shoutername);
      return false;
    }
    else {
      return false;
    }
      if(navigator.appName == 'Microsoft Internet Explorer') {
        refresh();
      }
}


// resize images
function xymbox_image(maxsize) {
    var mboximages = document.getElementsByName('xymboxImage');
    for(i=0;i<mboximages.length;i++){
        imgw = mboximages[i].width;
        imgh = mboximages[i].height;
          if((imgw > maxsize) && (imgw > imgh)){
          mboximages[i].width=maxsize;
          }
          else if(imgh > maxsize) {
          mboximages[i].height = maxsize;
          }
        }
    }

// delete all shouts
function del_all(){
  var really=confirm(unescape(XY_MEGABOX_J_DELETE_REALLYALL));
  if(really==true) {
	if (delReq.readyState == 4 || delReq.readyState == 0) {
		delReq.open("POST", 'xy_megabox.php?action=deleteall', true);
		delReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		var param = '&sid=' + sessionhash;
		delReq.send(param);
        lastMessage=0;
        refresh();
        clear();
        }
  }
  else {
     return false;
   }
   //get_shouts();
   //clear();
}

// delete all shouts
function kill_thisshout(id){
    mTimer = window.clearTimeout(mTimer);
	if (killReq.readyState == 4 || killReq.readyState == 0) {
		killReq.open("POST", 'xy_megabox.php?action=kill_thisshout', true);
		killReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		var param = '&sid=' + sessionhash;
        param += '&id=' + id;
		killReq.send(param);
        window.setTimeout('refresh()',200);
        call = 0;
    }

    else return false;
    mTimer = window.setTimeout('get_shouts()',xy_megaboxreload*1000);
    delete killReq;
}

// Clear massage field
function clear() {
  document.getElementById('message').value='';
  document.getElementById('message').focus();
}

// ###############
// megabox bbcodes
// ###############
function insert_plate() {
   var platetext = prompt('Schildertext eingeben','');
   if(trim(platetext)!='') {
   insert('[SCHILD=random]'+platetext,'[/SCHILD]');
   }
   else return;
}
function insert_url() {
   var name = prompt('Geben sie einen Linknamen ein','Ich bin ein Link');
   if(name!=null) {
   var url = prompt('URL eingeben','http://');
   if(trim(url)!='http://' && trim(url)!='') {
   insert('[URL='+url+']'+name,'[/URL]');
   }
   else return;
   }
   else return;
  }

function insert_email() {
   var name = prompt('Geben sie einen Linknamen ein','meine Emailadresse');
   if(name!=null) {
   var email = prompt('Email-Adresse eingeben','meine@adresse.tld');
   if(trim(email)!='meine@adresse.tld' && trim(email)!='') {
   insert('[EMAIL='+email+']'+name,'[/EMAIL]');
   }
   else return;
   }
   else return;
  }

function insert_quote() {
   var quote = prompt('Zitat eingeben','');
   if(trim(quote)!='' && trim(quote)!=null) {
   do_shout('[QUOTE]'+quote+'[/QUOTE]',shoutername);
   }
   else return;
  }

function smilies(code){
 insert(code,'');
}

function insert(aTag, eTag) {
  var input = document.getElementById('message');
  input.focus();
  /* Internet Explorer */
  if(typeof document.selection != 'undefined') {
    /* Einfügen des Formatierungscodes */
    var range = document.selection.createRange();
    var insText = range.text;
    range.text = aTag + insText + eTag;
    /* correct cursorposition */
    range = document.selection.createRange();
    if (insText.length == 0) {
      range.move('character', -eTag.length);
    } else {
      range.moveStart('character', aTag.length + insText.length + eTag.length);
    }
    range.select();
  }
  /*  Gecko based Browser */
  else if(typeof input.selectionStart != 'undefined')
  {
    /* insert codes */
    var start = input.selectionStart;
    var end = input.selectionEnd;
    var insText = input.value.substring(start, end);
    input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end);
    /* correct cursorposition */
    var pos;
    if (insText.length == 0) {
      pos = start + aTag.length;
    } else {
      pos = start + aTag.length + insText.length + eTag.length;
    }
    input.selectionStart = pos;
    input.selectionEnd = pos;
  }
  /* all other browser */
  else
  {
    /* check insertposition */
    var pos;
    var re = new RegExp('^[0-9]{0,3}$');
    while(!re.test(pos)) {
      pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
    }
    if(pos > input.value.length) {
      pos = input.value.length;
    }
    /* insert codes */
    var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
    input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
  }
}

// htmlspecialchars like in php
function htmlspecialchars(str){
    str = str.replace(/&/g, "&amp;" );
    str = str.replace(/</g, "&lt;" );
    str = str.replace(/>/g, "&gt;" );
    return str;
   }

function showTooltip(id,tip){
    document.getElementById(id).style.display = "block";
    document.getElementById(id).innerHTML=tip;
}

function hideTooltip(id){
    document.getElementById(id).style.display = "none";
}

function addslashes(str) {
  str=str.replace(/\'/g,'\\\'');
  str=str.replace(/\"/g,'\\"');
  str=str.replace(/\+/g,'::|::');
 // str=str.replace(/\`/g,'\\`');
 // str=str.replace(/\´/g,'\\´');
  str=str.replace(/\\/g,'\\\\');
  str=str.replace(/\0/g,'\\0');
  return str;
}

function check_rights() {
  if (is_megabox_admin == 0 && can_delete_in_megabox == 0) {
    var delimg = document.getElementsByName("killit");
    for(var i=0; i < delimg.length; i++) {
      delimg[i].style.display = "none";
    }
  }
}

// hide and show menues
function mboxshow(id) {
 if(document.getElementById)
document.getElementById(id).style.display = "inline";
}

function mboxhide(id) {
 if(document.getElementById)
   document.getElementById(id).style.display = "none";
}

// ban anban megaboxuser
function checkban(message) {
    clear();
    message = trim(message);

    if(message.substr(0,4)=="/ban") {
    window.open("xy_megabox.php?action=ban&message="+message+"&sid="+sessionhash, "Megabox", "width=450,height=35,left=100,top=200,resizeable=yes");
    return;
    }
    else if(message.substr(0,6)=="/unban") {
    window.open("xy_megabox.php?action=ban&message="+message+"&sid="+sessionhash, "Megabox", "width=450,height=35,left=100,top=200,resizeable=yes");
    return;
    }
    else {
      return true;
    }
}


// get rid of whitespaces
function trim(text)
{
	return text.replace(/^\s+/i, '').replace(/\s+$/i, '');
}

function umlEncode(text){
    var entext = str_replace("€", "&euro;", text) ;
    return entext;
    }

// hide megabox, personal user setting
function mboxswitch(on) {
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
        window.clearTimeout(mTimer);
		sendReq.open("POST", 'xy_megabox.php?action=mboxhide', true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		var param = '&sid=' + sessionhash;
        param += '&hide=' + on;
		sendReq.send(param);
        }
      window.setTimeout ('window.location.href = "index.php?sid=" + sessionhash',300);
}

