// JavaScript Document
var autoScroll=true; // important, toggle for manual or auto


$(document).ready(function() {  
  
   	recordActivity();
	showRoom();
	
	$("#talk").click(function () { if($("#talk").val()=='start chatting here..') { $("#talk").val(""); } });
	
	$("#rocker").click(function () { 
			if(autoScroll) { 
				autoScroll=false;
				$("#rocker").css("background-position","-36px 0px");
				$("#notify #autoscroll").text("autoscroll:OFF");
			} else {
				autoScroll=true;
				$("#rocker").css("background-position","0px 0px");
				$("#notify #autoscroll").text("autoscroll:ON");
			} 
	});
	
	
		$("#reporter").click(function () { 
									   
		if($('#reporterform').length == 0) { 
		$('<form id="reporterform" name="reporterform" method="post" action="reporter.php" style="display:none"><textarea name="reportcontent" id="reportcontent" cols="" rows=""></textarea></form>').appendTo('body');
		}
		$("#reportcontent").val( $("#chatRoom").html() );
		document.reporterform.submit();
		return false;
	});
	
	
	
 });
	
	 
//$().ajaxStart($.blockUI).ajaxStop($.unblockUI);
var last_msg_id=1;
var msgTimerID='';
var usrTimerID='';
var roomStatus='';
var lastAction=0;
var jsTimeout=1200000;
var maxMessages=100;
var updateChat = 0;
var updateUserlist = 0;
var firstRun=true;

function startIntervals() {
	// start at general frequency
	msgTimerID=setInterval ("update()", 2000);
	usrTimerID=setInterval ("userlist()", 3000);
}

function update() {
    //if (updateChat == 1) return;
    updateChat = 1;
	
	if(theTime()>(lastAction+jsTimeout)) {
		document.location.href='index.php?timeout';
		
	} else {
            var qstring = "action=getmessages&id="+last_msg_id;	
            qstring += "&roomlength="+$('#chatRoom p').length;

			$.ajax({
			  type: "POST",
			  url: "chat_server.php",
			  cache: false, 
			  data: qstring,
			  dataType: "json",
			  success: function(msgs){
				  last_msg_id = msgs.lastmsgid;
                  scrollChat(msgs.messages);	  
			  },
              complete: function(XMLHttpRequest, textStatus) {
                  updateChat = 0;				  
              }
			});		
			
	}
	
}

function removeParagraphs()
{
    var offset = 0;
    var paranum = $('#chatRoom p').length;
    if (maxMessages <  paranum) {
         var delnum = paranum - maxMessages;
         for (var i=0; i < delnum; i++) {
             offset += $('#chatRoom p:first').height() + 10;
             $('#chatRoom p:first').remove();
         }
    }

    return offset;
}

function goChat() {
    var im = encodeMessage($("#talk").val());
    var qstring = "action=chatins&message="+im; 
	
    qstring += "&roomlength="+$('#chatRoom p').length;

	if($("#talk").val().length>0) {	
	
		$.ajax({
		  type: "POST",
		  url: "chat_server.php",
		  cache: false,
		  data: qstring,
		  success: function(msg){

               //$("#chatRoom").append(prepMessage(msg));

				$("#talk").val('');
				$("#chatSendBtn").val('SEND');

                scrollChat(msg);
				recordActivity();
		  }
		});
	} else {
		alert('no text entered!');
	}

    return false;
}

function userlist(action)
{
    if (updateUserlist == 1) return;

    updateUserlist = 1;

    if (action)
        post = "action=userlist&param=" + action;
    else
        post = "action=userlist";

	$.ajax({
	  type: "POST",
	  cache: false, 
	  url: "chat_server.php",
	  data: post,
	  success: function(list){
        $("#chatUsers").html(list);
		
				if(list.indexOf("inroom")!=-1) {
					$("#chatControls").removeClass("outside");
					$("#chatControls").addClass("inside");
					$("#chatRoom").height(390);
					$("#led").css("background-position","0px -50px");
					$("#notinroom").hide('fast');
					$("#vbcChat form").show('fast');
					$("#chatRoomBG").fadeTo("slow", 0.90);
					$("#chatUsersBG").fadeTo("slow", 0.95);
				} else {
					$("#chatControls").removeClass("inside");
					$("#chatControls").addClass("outside");
					$("#chatRoom").height(290);
					$("#led").css("background-position","0px 0px");
					$("#vbcChat form").hide('fast');
					$("#notinroom").show('fast');
				}
				
	  },
      complete: function() {
            updateUserlist = 0;	
      }
	});
}

function showRoom() {
	update();
	userlist();
	startIntervals();	
}

function scrollChat(msg) {

    if (msg) {	msg=formatMessage(prepMessage(msg));   
	$("#chatRoom").append(decodeMessage(msg));  }
	
	if(autoScroll) {
	$("#chatRoom").attr({ scrollTop: $("#chatRoom").attr("scrollHeight") });
	}
		
}


	
/* UTLITIES */

function encodeMessage(msg) {
	msg=msg.replace(/\%/g,'PERCENT');
	msg=encodeURIComponent(msg);
	return msg;
}

function decodeMessage(msg) {
	msg=decodeURIComponent(msg);
	msg=msg.replace(/PERCENT/g,'%');
	return msg;
}

function addslashes(str) {
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\0/g,'\\0');
return str;
}
function formatMessage(str) {
str=str.replace(/\\'/g,'\'');
str=str.replace(/\\"/g,'"');
str=str.replace(/\\\\/g,'\\');
str=str.replace(/\\0/g,'\0');
str=str.replace(/\\&quot;/g,'&quot;');
str=replaceURLWithHTMLLinks(str);
return str;
}

function replaceURLWithHTMLLinks(text) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(exp,"<a target='blank' href='$1'>$1</a>"); 
}


/* SMILIES */
var smile=new Array(":)",":|",":(",":D",":o",";)",":/",":P",":lol:",":mad:",":rolleyes:",":cool:");
var smileimage=new Array('smile','neutral','sad','big_smile','yikes','wink','hmm','tongue','lol','mad','roll',	'cool');

function prepMessage(msg) {

	var linkpos=msg.indexOf('http://');
	
	var parseSmilies=(linkpos!=-1)? false : true;
		
	if(parseSmilies) {
		for(var i=0;i<smile.length;i++) {
			var str="<img src='images/smilies/"+smileimage[i]+".png' width='15' height='15' />";
			var cool = RegExp.escape(smile[i]);
			var sRegExInput = new RegExp(cool, "g");
			msg= msg.replace(sRegExInput, str);
		}
	} else {
	// ignore smilies - make clickable link when have time
	
	//alert(msg);
			
		//msg= msg.replace('http:','ALINK http:');
	
	}
	

	return msg;
}



function insertSmiley(n) {	
	if($("#talk").val().length==0) {
			$("#talk").val(smile[n]+' ');
	} else {
			$("#talk").val($("#talk").val()+' '+smile[n]);
	}
	$("#talk").focus();
}


function getLocalHM() {
	// return Hour:Seconds in Local Time
	var d = new Date();
	var h = d.getHours().toLocaleString();
	var s = d.getMinutes().toLocaleString();
	return h+':'+s;
}

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

function recordActivity() {
	lastAction=theTime();
}

function theTime() {
	d = new Date();
	return d.getTime();
}

function clearRoom() {
	// for testing
	$("#chatRoom").html('');
}

function chatenter() {
	$("#chatRoom").attr({ scrollTop: $("#chatRoom").attr("scrollHeight") });
	userlist('enter');
}

function chatleave() {
	$("#chatRoom").attr({ scrollTop: $("#chatRoom").attr("scrollHeight") });
	userlist('leave');
}


function zeroPad(n) {
	if(n<10) {
		return '0'+n;
	}
	return n;
}


