var ajaxObj = new Array();
var isIE = false;

/*
* @Class Ajax
* @version 2.0 
* @author vasupat chantakeaw
* @email thaiajax@gmail.com
*/

function chatAjax(){
	
	this.xmlhttp;
	this.formElement;
	this.requestFile;
	this.URLString;
	this.innerDivID;
	this.method 		= 'GET';
	this.responseType 	= 'Text'; /*Text , XML*/
	this.loadingType 	= 0;
	this.async 			= true;
	this.onCompletion 	= function() { };
	this.onProcess 		= function() { };
	this.loading 		= function(v){
		var v;
		if(this.loadingType>0){
			if(this.loadingType==1){
				if(!g("loading")) {this.createLoaddingDiv();}
			}
			if(v==1){
				if(this.loadingType==1){ g("loading").style.visibility = "visible";}
			}else{
				if(this.loadingType==1){ g("loading").style.visibility = "hidden";}
			}
		}
	}
	
	this.ConnXmlHttp = function(){
		try{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				isIE = true;
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				xmlhttp = false;
			}
		}
	
		if(!xmlhttp && document.createElement){
			xmlhttp = new XMLHttpRequest();
		}
		
		return xmlhttp;
	}
	
	this.getRequestBody = function(myForm) {
		var aParams = new Array();  
			for (var i=0 ; i < myForm.elements.length; i++) {
				
				var formElement = myForm.elements[i];
				if(formElement.type=='checkbox' && !formElement.checked){ continue;} 
            	var sParam = encodeURIComponent(myForm.elements[i].name);
               	sParam += "=";
               	sParam += encodeURIComponent(myForm.elements[i].value);
               	aParams.push(sParam);
           	}     
           	return aParams.join("&");        
	}
	
	this.loadXMLDoc = function() {
	
		var self = this;
		this.xmlhttp = this.ConnXmlHttp();

		
		if (this.method == "GET") {
			this.xmlhttp.open(this.method, this.requestFile, this.async);
		}else{
			this.URLString = this.getRequestBody(this.formElement);
			this.xmlhttp.open(this.method,this.requestFile, this.async);
		}
		if (this.method == "POST"){
  			try {
				this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')  
			} catch (e) {}
		}
		this.xmlhttp.onreadystatechange = function(){
			if(self.xmlhttp.readyState==4){
				if(self.loadingType==1){ self.loading(0);}
				if (self.xmlhttp.status == 200) {
					if(self.responseType == "Text"){
						self.response = self.xmlhttp.responseText;
					}else{
						self.response = self.xmlhttp.responseXML;
					}	
					self.onCompletion();
				}
			}else{
				if(self.loadingType==1){ self.response = "Loading...";}
				if(self.loadingType==2){ 
					//self.response = "Loading...";
					self.response = '<img src="images/ajax-loader.gif" />';
					self.onCompletion();
				}
				if(self.loadingType==3){ 
					//self.response = "Loading...";
					self.response = '<img src="images/ajax-loader2.gif" />';
					self.onCompletion();
				}
			}
		}
		this.xmlhttp.send(this.URLString);
	}
	
	/*
	* Show Loading
	*/
	
	this.createLoaddingDiv = function(){
	
		var connLoading = document.createElement("DIV")
			connLoading.id = "loading";
			connLoading.style.position="absolute";
			connLoading.style.left="0px";
			connLoading.style.top="0px";
			connLoading.style.width="185px";
			connLoading.style.height="15px";
			connLoading.style.zIndex=99999;
			connLoading.style.backgroundColor="#FF0000";
			connLoading.style.visibility = "visible";
			connLoading.style.font = '11px Lucida Sans Unicode';
			connLoading.style.filter = 'alpha(opacity=60)';
			connLoading.innerHTML = "<strong><font color=\"#FFFFFF\">&nbsp;working on your request...</font></strong>";
		document.body.appendChild(connLoading);
		
	}
}


/*
* @XML Mobile Chat Ajax
* @version 1.0
* @author Chalermsak Benjakul
* @email chalermsak@thinksmart.co.th
*@2007-11-09
*/
//========Set Global variable=====
var RoomID; 
var RoomName;
var SubRoomID;
var colorRand = new Array("#f31879","#99d36a","#53bed3","#ffff00");
var timeSetInterval;
//========================

//============Start First : Get Chat Room Ajax============
function getChatRoom(){
		var index = 'chatroom'; 
		var requestFile = 'template/Applications/iME-FE/s.php?c=l0&bpm=1&'+Math.random();
		ajaxObj[index] = new chatAjax();
		ajaxObj[index].method="GET";
		ajaxObj[index].responseType="XML";
		ajaxObj[index].requestFile=requestFile;
		ajaxObj[index].onCompletion = function(){ chatRoom(index);};
		ajaxObj[index].loadXMLDoc();

}

function chatRoom(index){	
	response =  ajaxObj[index].response;	
	var arrXML = xmlParseRoom(response);
	//========Global Variable=======
	RoomID = arrXML['RoomID'] ; 
	RoomName = arrXML['RoomName'];
	SubRoomID = arrXML['SubRoomID'];
	innitChat();
	timeSetInterval = setInterval("innitChat()",10000); //setTime Reload function innitChat() 10 second
}

//===========Start Innitial Subroom and get Chat Message=========
function innitChat(){
	try{
		if(RoomID!=""){
				for(i=0;i<4;i++){
						name = RoomName[i];
						if(name=='เด็กมัธยม' || name=='เด็กมหาลัย' || name=='หาเพื่อน' || name=='หากิ๊ก'){
								if(SubRoomID[i].length>=1){
										var num= SubRoomID[i].length-1;	                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
										getChatMsg(SubRoomID[i][num],0,RoomID[i]);
										document.getElementById('tmp_'+RoomID[i]).value= i+':'+num; //set for check notfound message
								}else{
										getChatMsg(SubRoomID[i][0],0,RoomID[i]);
										document.getElementById('tmp_'+RoomID[i]).value= i+':0'; //set for check notfound message
								}
						}
				}
		}
	}catch(e){
	}
}

function searchID(RoomID){
			tmp = document.getElementById('tmp_'+RoomID).value.split(":");
			i=tmp[0];
			num=tmp[1];
			if(num!=0){
					num = num-1;
					document.getElementById('tmp_'+RoomID).value= i+':'+num; //set for check notfound message
					getChatMsg(SubRoomID[i][num],0,RoomID);
			}
}

function getChatMsg(subroomID,startID,roomID){
		var index = 'chat_'+roomID; 
		var requestFile = 'template/Applications/iME-FE/s.php?r='+subroomID+'&bpm=1&t='+startID+'&'+Math.random();

		ajaxObj[index] = new chatAjax();
		ajaxObj[index].method="GET";
		ajaxObj[index].responseType="XML";
		ajaxObj[index].requestFile=requestFile;
		ajaxObj[index].onCompletion = function(){ genMsgHTML(index);};
		ajaxObj[index].loadXMLDoc();
}

function genMsgHTML(index){
	try{
		response =  ajaxObj[index].response;
		var arrMSG = xmlParseMSG(response);
		if(arrMSG['message']!=""){
			document.getElementById('field_'+index).value = arrMSG['message'];
			printChat(index);
			//document.getElementById(index).innerHTML= arrMSG['message'];
		}else{
			RoomID = index.split("_");
			searchID(RoomID[1]) // Search New If Message Is Empty
		}
	}catch(e){
	}
}

function printChat(index){
			var requestFile = 'template/Applications/printChat.php?field=field_'+index+'&'+Math.random();
			//var requestFile = 'printChat.php?field=field_'+index;
			ajaxObj[index] = new chatAjax();
			ajaxObj[index].method="POST";
			ajaxObj[index].formElement = document.getElementById('chat'); //formRegister
			ajaxObj[index].responseType="Text";
			ajaxObj[index].requestFile=requestFile;
			ajaxObj[index].onCompletion = function(){ showMSG(index);};
			ajaxObj[index].loadXMLDoc();
}

function showMSG(index){
	if(timeSetInterval!=""){
		response =  Trim(ajaxObj[index].response);
		if(response!=null && response !=""){
			document.getElementById(index).innerHTML= response;
			var div = document.getElementById(index);
			  //h = div.scrollHeight;
			  //div.scrollTop = h;
			  div.scrollTop = 100;
		}
	}
}

function xmlParseMSG(xmlDoc) {
	var arrResult = new Array();
	var message = "";
	if(xmlDoc!=null){
		var publicTag = xmlDoc.childNodes[1].childNodes[2].childNodes;	
		//var message = "<font color='#FFFFFF'>"+xmlDoc.childNodes[1].childNodes[2].getAttribute('id')+"</font><br/>";
		for(k=0;k<publicTag.length;k++){
					colorID = k%4; //Math.floor(Math.random()*3)
					//message = message+"<font color='#0000FF'>"+publicTag[k].getAttribute('id')+"</font>: "+publicTag[k].text+'<br/>';
					message = message+"<font color='"+colorRand[colorID]+"'>"+publicTag[k].text+"</font><br/>";
					//arrResult['lastID']= child[k].getAttribute('id');
		}
	}
	arrResult['message']=message;
	return arrResult;
}

//=============XML Parse String Room Message===========
function xmlParseRoom(xmlDoc) {
				var arrResult = new Array();
				var child = xmlDoc.childNodes[1].childNodes;
				var childLength = child.length;
				//=======get Value in response Tag========
				var arrRoomID = new Array();
				var arrRoomName = new Array();
				var arrSubRoomID= new Array();
				
				var j = 0;
				for(k=0;k<childLength;k++){					
					if(k<=1){
						arrResult[child[k].tagName] = child[k].text; //get Result search res_code and res_detail
					}else{
						if(child[k].getAttribute('id')=='55551146740993' || child[k].getAttribute('id')=='55551147052638' || child[k].getAttribute('id')=='55551147153613' || child[k].getAttribute('id')=='55551147153707'){
									arrRoomID[j] = child[k].getAttribute('id');
									arrRoomName[j] = child[k].getAttribute('name');
									arrSubroom = new Array();					

									//=====find and get Subroom apply>=3 && cos=='B'  only=====
									numarr = 0;
									for(a=0;a<child[k].childNodes.length;a++){
										var apply = child[k].childNodes[a].getAttribute('apply');
										var cos = child[k].childNodes[a].getAttribute('cos');
										if(apply>=3 && cos=='B'){
											arrSubroom[numarr] = child[k].childNodes[a].getAttribute('id');
											numarr++;
										}
									}
									
									//=====not have Subroom apply>=3 && cos=='B'  get All Subroom ID=====
									if(numarr==0){								
											for(a=0;a<child[k].childNodes.length;a++){
													arrSubroom[a] = child[k].childNodes[a].getAttribute('id');
											}
									}
									arrSubRoomID[j] = arrSubroom;
									j=j+1;
						}
					}
				}				
				arrResult['RoomID'] = arrRoomID;
				arrResult['RoomName'] = arrRoomName;
				arrResult['SubRoomID'] = arrSubRoomID;

	return arrResult;
}

function LTrim(str){
	if (str==null){
		return null;
	}
	for(var i=0;str.charAt(i)==" ";i++);
	return str.substring(i,str.length);
}
function RTrim(str){
	if (str==null){
		return null;
	}
	for(var i=str.length-1;str.charAt(i)==" ";i--);
	return str.substring(0,i+1);
}
function Trim(str){
	return LTrim(RTrim(str));
}

//=============XML Parse String Chat Message===========
/*
function xmlParseMSG(xmlDoc) {
	var arrResult = new Array();
	var parent = xmlDoc.childNodes;
	var parentLength = parent.length;
	//========search response Tag===========
	for (i=1;i<parentLength ;i++ ){
			if(parent[i].tagName=='response'){
				var child = parent[i].childNodes;
				var childLength = parent[i].childNodes.length;
				//=======get Value in response Tag========
				var message = "";
				for(k=0;k<childLength;k++){					
					if(k<=1){
						arrResult[child[k].tagName] = child[k].text; //get Result search res_code and res_detail
					}else{
						var publicTag = child[k].childNodes;
						for(j=0;j<publicTag.length;j++){
								message = message+publicTag[j].text+'<br/>';
						}
						//message =message+'<br/>'+child[k].getAttribute('id');
						arrResult['lastID']= child[k].getAttribute('id');
					}
				}
				arrResult['message']=message;
				break;
			}
	}

	return arrResult;
}

//=============XML Parse String Room Message===========
function xmlParseRoom(xmlDoc) {
	var arrResult = new Array();
	var parent = xmlDoc.childNodes;
	var parentLength = parent.length;
	//========search response Tag===========
	for (i=1;i<parentLength ;i++ ){
			if(parent[i].tagName=='response'){
				var child = parent[i].childNodes;
				var childLength = parent[i].childNodes.length;
				//=======get Value in response Tag========
				var arrRoomID = new Array();
				var arrRoomName = new Array();
				var arrSubRoomID= new Array();
				
				var j = 0;
				for(k=0;k<childLength;k++){					
					if(k<=1){
						arrResult[child[k].tagName] = child[k].text; //get Result search res_code and res_detail
					}else{
						arrRoomID[j] = child[k].getAttribute('id');
						arrRoomName[j] = child[k].getAttribute('name');
						arrSubroom = new Array();
						for(a=0;a<child[k].childNodes.length;a++){
							arrSubroom[a] = child[k].childNodes[a].getAttribute('id');
						}
						arrSubRoomID[j] = arrSubroom;

						j=j+1;
					}
				}
				
				arrResult['RoomID'] = arrRoomID;
				arrResult['RoomName'] = arrRoomName;
				arrResult['SubRoomID'] = arrSubRoomID;
				break;
			}
	}

	return arrResult;
}
*/