/*------------------------------------------------------------------------------
 * Agotcha!
 * Version 1.4.2
 * by Boris Ding P H, http://borisding.com/agotcha/
 * Copyright (c) 2009 Boris Ding P H. All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *------------------------------------------------------------------------------
 */  

var agotcha = (function(){
    var ajaxChat = {
	   // validate inputs of user
	    validation: function(){
		var userName = document.getElementById("userNameID");
		var userMessage = document.getElementById("userMessageID");
		var userURL = document.getElementById("userURLID");
		
		  if(userName.value == "" || userName.value == null){
		   document.getElementById(att.errorID).innerHTML = " Oops! \"Name\" field is empty.";
		   userName.focus();
		  }else if(userMessage.value == "" || userMessage.value == null){
		   document.getElementById(att.errorID).innerHTML = " Oops! \"Message\" field is empty.";
		   userMessage.focus();
		  }else if(userURL.value != ""){
		   var checkURL = new RegExp();
		   checkURL.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
		   if(!checkURL.test(userURL.value)) { 
		     document.getElementById(att.errorID).innerHTML = " Oops! Please provide valid URL.";
		     userURL.focus();
		   }else{
		    this.initSend();
		   }		    
		  }		  
		  else{
		    this.initSend();
		  }
		},
		
		initSend: function(){
		  document.getElementById(att.loaderID).innerHTML = att.loader;
		  document.getElementById("sendID").disabled = true;
		  setTimeout('agotcha.sendChat();',500);
		},
		
		retrieveChat: function(){
		 var retrieveXHR = att.retrieveXHR;
		 // retrieve the chat messages		 
		 var lastChat = parseInt(att.lastChat);
		 if(retrieveXHR.readyState == 4 || retrieveXHR.readyState == 0) // 4=loaded, 0= uninitialized
		  {
		     var parameters = "lastChat=" + lastChat + "&action=get&sid=" + Math.random();
			 var retrievePage = att.page;
            
			 retrieveXHR.open("POST", retrievePage, true);
			 retrieveXHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
			 retrieveXHR.onreadystatechange = this.callBackChatMessage; 
			 retrieveXHR.send(parameters);
		  }			
		},
		
		// sending chat
		sendChat: function(){
		// create XHR object for sending
		var sendXHR = att.sendXHR;
		
		 if(sendXHR.readyState == 4 || sendXHR.readyState == 0) // 4=loaded , 0= uninitialized
		 {		 
		  var userName = document.getElementById("userNameID");
		  var userMessage = document.getElementById("userMessageID");
		  var userURL = document.getElementById("userURLID");
		  
		  var sendPage = att.page;
		  var parameters = "user=" + this.encodeURLChar(userName.value) + "&message=" + this.encodeURLChar(userMessage.value) + "&url=" + userURL.value + "&action=send&sid=" + Math.random();
		  
		  sendXHR.open("POST", sendPage, true);
		  sendXHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
		  sendXHR.onreadystatechange = this.messageSent;
		  sendXHR.send(parameters);
		  
		  userMessage.value = ""; 
		  userURL.value = "";
		  document.getElementById(att.loaderID).innerHTML = "";
		 }//end if
		},
		
		// manage the interval and message after sent
		messageSent: function(){
		// clear the interval time to make sure only one interval time is running...
		clearInterval(att.intervalTime);
		// clear error message
        document.getElementById(att.errorID).innerHTML = "";
		// call back retrieveChat and get the chat messages		
		agotcha.retrieveChat();
		},
		
		// get the retrieved result in JSON format, deal and display...
     	callBackChatMessage: function(){
		
		 if(att.retrieveXHR.readyState == 4) 
		 {
		  if(att.retrieveXHR.status == 404){
		  alert("ERROR 404: Page was not found!");
		  return false;
		  }else{
		   var chatRoom = document.getElementById("chatRoomID");
		   var jsonResult = att.retrieveXHR.responseText;
   		   document.getElementById("sendID").disabled = false;
		  
		   // check if it's valid json format
		   var jsonChat =  eval("(" + jsonResult + ")");
		  if(jsonChat != null){

			var i = 0, className, user;
			var dataLength = jsonChat.chat.message.length;
           
			while(i < dataLength)
			{
     		 (att.sn % 2 != 0) ? className = "chatStyle1" : className = "chatSytle2";
			  
			 if(jsonChat.chat.message[i].url != ""){
			  var hyperlink = jsonChat.chat.message[i].url;
			  user = "<a href='"+ hyperlink +"' target='_blank'>"+ jsonChat.chat.message[i].user +"</a>";
			 }else{
			  user = jsonChat.chat.message[i].user;
			 }// end if
			 
			  chatRoom.innerHTML += "<div class='" + className + "'><img src='image/person.png'><b>" + user + ":</b> <br>" 
			  + "\"" + jsonChat.chat.message[i].text + "\"<div class=\"time\" align=\"right\">" + jsonChat.chat.message[i].time  
			  +" <img src='image/ip.png' title='IP: "+ jsonChat.chat.message[i].ip +"'></div>";
			  chatRoom.innerHTML += "</div>"
			   			   
			  chatRoom.scrollTop = chatRoom.scrollHeight;
			  att.lastChat = jsonChat.chat.message[i].id;
      
	  		  att.sn = att.sn + 1;
			  i++;
			}// end while
   		    document.getElementById(att.loaderID).innerHTML = "";
			att.intervalTime = setTimeout('agotcha.retrieveChat();',att.timer); //Refresh chat in 2 seconds
		   }
		   else{
		    alert("ERROR: Returned invalid format of JSON data!");
			return false;
		   } 
		  }
		 }// end if loaded..
		},
		
		// clear all messages
		clearMessages: function(){
		  var sendXHR = att.sendXHR;
		  var sendPage = att.page;
		  var parameters = "action=del&sid=" + Math.random();
		  
		  sendXHR.open("POST", sendPage, true);
		  sendXHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
		  sendXHR.onreadystatechange = this.messageCleared;
		  sendXHR.send(parameters);
		},
		
		messageCleared: function(){
		 if(att.sendXHR.readyState == 4){
		 
		 var result =  att.sendXHR.responseText;
		 if(result == "done"){
            document.getElementById("chatRoomID").innerHTML = "";
            agotcha.retrieveChat();
		  }
		 }//end if cleared
     	},
		
		encodeURLChar: function(input){
		 return encodeURIComponent(input);	
		},
		
		// create XHR object		
	    createChatXHR: function(){
		 var chatXHR = null;
		if(typeof XMLHttpRequest != "undefined"){ 
		   chatXHR = new XMLHttpRequest();
		   return chatXHR;
		 }else if(window.ActiveXObject){
		   var arrayMSXML2Version = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0"]; 
		   for(var i = 0; i < arrayMSXML2Version.length; i++){
		    try{
				chatXHR = new ActiveXObject(arrayMSXML2Version[i]);
		        return chatXHR;
			}catch(oError)
			{}//catch nothing
		   }// end for
		 }// end if
		 throw new Error("ERROR: Failed to create XMLHttpRquest object!");
	  },//end createChatXHR	  
	  
	  // added on: 22/08/2009
	  // purpose: Implementing Colour Options
	  
	  // get colour option and set it to chatroom
	  setColour: function(cOpt){
	  var colour;

	  // if cOpt is defined, set the picked colour to cookie
	  if(typeof cOpt != "undefined"){
		   this.setColourCookie(cOpt);		   
	   }else{
		   // check if cookie does not exist, set colour with default colour
		   if(this.getColourCookie() == ""){
			 this.setColourCookie("#e8eefa");
		   }
		   // reset the existing and extend the expired date
		   cOpt = this.getColourCookie();
		   this.setColourCookie(cOpt);
	   }
	   
	   // get colour from cookie
	   colour = this.getColourCookie();
	   	     
	   //set colour to outer frame
       document.getElementById("outerFrameID").style.border = "4px solid " + colour;
	   //set colour to inner frame
	   document.getElementById("innerFrameID").style.border = "1px solid " + colour;
	   document.getElementById("innerFrameID").style.backgroundColor = colour;
	   
	},// end changeTheme
	  
	   
	  // check if cookie is available
	 getColourCookie: function(){
		 var cLength = document.cookie.length;
		 var startCookie;
		 var endCookie;
		 var colour = "";
		 
		 if(cLength > 0){	
		 
			 startCookie = document.cookie.indexOf(att.cookieName + "=");
			 if(startCookie != -1){
				 
				startCookie = startCookie + att.cookieName.length + 1; 
				endCookie = document.cookie.indexOf(";", startCookie);

				if(endCookie == -1){
					endCookie = cLength;
				}
			    //if reach the end, and found, return cookie colour
				 colour = document.cookie.substring(startCookie, endCookie);
				return colour;				  
			 }
		  }
			  
		return colour;
	  },	  
	  
	  // set particular colour option to cookie
	  setColourCookie: function(ccOpt){	
	   var expDate = new Date();
	   var cookieStr = "";
	   
	   // set expired day after 14 days
	   expDate.setDate(expDate.getDate() + att.day);
	   // set cookie for colour
	   cookieStr = att.cookieName + "=" + ccOpt + "; expires=" + expDate.toGMTString();
	   document.cookie = cookieStr;	   
	  }
	};
	
	return ajaxChat;
})();

var att = {
    retrieveXHR: agotcha.createChatXHR(),
	sendXHR: agotcha.createChatXHR(),
	page: "retrieve_chat.php",
	loaderID: "loaderID",
	loader: "<img src=\"image/chat-loader.gif\">",
	errorID: "errorID",
	lastChat: 0,
	timer: 2000,
	intervalTime: null,
	sn: 0,
	
	// value for colour cookie
	cookieName: "colourOption",
	//set your expired day here
	day: 14
};