var cancel = new Image();
cancel.src = 'cancel.gif';

function chat(cid,vName){
open(baseurl+'/applications/messanger/?cid='+cid+'&usr=b&sid='+sid+'&catId='+catId+'&vName='+encodeURIComponent(vName)+'','','location=no,resizable=no,status=no,scrollbars=no,width=375,height=630');
}
function getVisitors(){
	if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
		xmlHttp.open("GET","./?xml=TRUE",true);
		xmlHttp.onreadystatechange = getVisitorsResponse;
		xmlHttp.send(null);
	}
	else setTimeout('getVisitors()',1000);	
}
function getVisitorsResponse(){
	if(xmlHttp.readyState == 4){
		if(xmlHttp.status == 200){
			sendNotice('');
			var xmlResponse = xmlHttp.responseXML; 
 			var xmlElement = xmlResponse.documentElement; 
 			var xmlVisitors = xmlElement.getElementsByTagName('visitor');
			var docVisitors = document.getElementById('visitors');
			var docVisitorsSubDiv = docVisitors.getElementsByTagName('div');
			var xmlVisitorsLength = Number(xmlVisitors.length);
			var waitingDiv = document.getElementById('waitingDiv');
			var waitingNum = xmlElement.getAttribute('waitingNum');
			var thisDate = xmlElement.getAttribute('date');
			var username = xmlElement.getAttribute('username');

      if(!username) return window.location.reload(1);
      
			if(xmlVisitorsLength > 0){
				docVisitors.style.visibility = 'visible';
			}
			else docVisitors.style.visibility = 'hidden';

			for(m = 0; m < docVisitorsSubDiv.length; m++){
				var thisElem = docVisitorsSubDiv[m].getAttribute('id');
				if(String(thisElem).substring(0,7) != 'waiting') continue; 
				for(z = 0; z < xmlVisitorsLength; z++){
					if(thisElem != 'waiting'+xmlVisitors[z].getAttribute('cid')){
						var stillConnected = false;
					}
					else{
						var stillConnected = true;
						break;
					}
				}
				if(stillConnected != true) docVisitors.removeChild(docVisitorsSubDiv[m]);	
			}
			var newVisitor;
			for(j = 0; j < xmlVisitorsLength; j++){
				var vName = xmlVisitors[j].firstChild.nodeValue;
				var logCount = Number(xmlVisitors[j].getAttribute('logCount')); 
				var status = xmlVisitors[j].getAttribute('status'); 			
				var xmlCid = xmlVisitors[j].getAttribute('cid');
				var transfer = xmlVisitors[j].getAttribute('transfer');
				var statusText = status == '' ? 'Waiting for attention...' : 'Conversation on-going.';
				
				function endImage(){
					return "<img name=\"cancel\" alt=\"Cancel\" title=\"Disconnect\" onclick=\"if(confirm('Do you really want to:\\nDisconnect "+vName.toUpperCase()+" from the Chat Centre') == true) cancelChat("+xmlCid+");\" onmouseover=\"hoverEffect("+xmlCid+",1)\" onmouseout=\"hoverEffect("+xmlCid+",0)\"/>";
				}
				
				for(n = 0; n < docVisitorsSubDiv.length; n++){
					var thisElem = docVisitorsSubDiv[n].getAttribute('id');
					//alert(thisElem);
					if(thisElem == 'waiting'+xmlCid+''){
						newVisitor = false;
						break;
					}
					else newVisitor = true;
				//	if(String(thisElem).substring(0,7) != 'waiting') continue;
				}
				if(newVisitor == true){
					var div = document.createElement('div');
					div.setAttribute('id','waiting'+xmlCid+'');
					div.setAttribute('log',logCount);
					div.className = 'visitor';
					div.innerHTML = "<div class=\"endChatDiv\">"+endImage()+"</div><div class=\"status\">Checking...</div><div class=\"name\"><a href=\"javascript: link()\" class=\"chatLink\" onclick=\"chat("+xmlCid+",\'"+vName+"\');\"onmouseover=\"hoverEffect("+xmlCid+",1)\" onmouseout=\"hoverEffect("+xmlCid+",0)\">"+vName+"</a></div>";
					div.firstChild.firstChild.src = cancel.src;
					docVisitors.appendChild(div);
					window.focus();
				}
				var thisDiv = document.getElementById('waiting'+xmlCid+'');
				var oldLogCount = Number(thisDiv.getAttribute('logCount'));
				var timeOut = Number(thisDiv.getAttribute('timeOut'));
				//thisDiv.setAttribute('timeOut',''+logCount - oldLogCount+'');
				
				if(logCount - oldLogCount == 0)	thisDiv.setAttribute('timeOut',''+(Number(timeOut) + 1)+''); 
				else thisDiv.setAttribute('timeOut',0);
				var logged = '';
				if(thisDiv.getAttribute('cancel') != 1){
					if(timeOut > 10){
						logged = 'out';
						thisDiv.childNodes[1].innerHTML = 'Appears to have discontinued with the chat.';
					}
					else if(timeOut > 5)thisDiv.childNodes[1].innerHTML = 'Checking for current status...';
					else if(transfer > 0)thisDiv.childNodes[1].innerHTML = 'Transfered...';
					else thisDiv.childNodes[1].innerHTML = statusText;
				}
				if(logged == 'out') thisDiv.firstChild.style.visibility = 'visible';
				else if(status != '') thisDiv.firstChild.style.visibility = 'visible';
				else if(status == '' && logged != 'out') thisDiv.firstChild.style.visibility = 'hidden';
				
				thisDiv.setAttribute('logCount',logCount);

			}
			with(waitingDiv){
				getElementsByTagName('b')[0].firstChild.nodeValue = waitingNum;
				style.visibility = 'visible';
			}
			document.getElementById('date').innerHTML = ''+thisDate+'';
		}
		else sendNotice('Problem reaching the server, system retrying...');
		setTimeout('getVisitors()',1000);
	}
}
function hoverEffect(cid,type){
	var color = type == 1 ? '#ffffee' : '#eeffee';
	var theDiv = document.getElementById('waiting'+cid+'');
	theDiv.style.backgroundColor = ''+color+'';
}
function cancelChat(cid){
	var theDiv = document.getElementById('waiting'+cid+'');
	theDiv.setAttribute('cancel',1);
	theDiv.childNodes[1].innerHTML = 'Disconnecting...';
	if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
		xmlHttp.open("GET","./?xml=TRUE&cancel=TRUE&cid="+cid+"",true);
		xmlHttp.onreadystatechange = getVisitorsResponse;
		xmlHttp.send(null);
	}
	else setTimeout('cancelChat('+cid+')',1000);
}
function sendNotice(info){
	document.getElementById('alert').innerHTML = ''+info+'';
}

function resetCredentials(){
   var rc = document.forms['reset_credentials_form'].elements;
   var button = rc['continue'];
   for(var i = 0; i < rc.length; i++){
      if(rc[i].value == '') return doGlobalAlert('The information provided are not complete and your password was not changed. All the fields are required.'); 
   }
   
   var u = encodeURIComponent(rc['rusername'].value);
   var p = encodeURIComponent(rc['rcpassword'].value);
   var np = encodeURIComponent(rc['npassword'].value);
   var cnp = encodeURIComponent(rc['cnpassword'].value);
   
   if(np != cnp) return doGlobalAlert('The new password does not match the comfirmation password!'); 
   
   var url = '../includes/json.php?operation=resetCredentials&u='+u+'&p='+p+'&np='+np+'&cnp='+cnp+'&sid='+sid+'';
   button.value = 'Working...';
   button.disabled = true;
   simpleXHR(url,'credentialResponse','credentialError');
}
function credentialResponse(response){
   reset_reset_credentials_form()
   reset_password_reminder_form()
   popup.close('reset_credentials');
   popup.close('password_reminder');
   doGlobalAlert(response.info); 
}
function reset_reset_credentials_form(){
   var rc = document.forms['reset_credentials_form'].elements;
    rc['rusername'].value = '';
    rc['rcpassword'].value = '';
    rc['npassword'].value = '';
    rc['cnpassword'].value = '';
    rc['continue'].value = 'Continue >>';
    rc['continue'].disabled = false;
}
function reset_password_reminder_form(){
   var pr = document.forms['password_reminder_form'].elements; 
   pr['username'].value = '';
   pr['secret_answer'].value = '';
   pr['continue'].value = 'Continue >>';
   pr['continue'].disabled = false;
}
function passwordReminder(){
   var u =  document.forms['password_reminder_form'].elements['username'].value;
   var a =  document.forms['password_reminder_form'].elements['secret_answer'].value;
   var button = document.forms['password_reminder_form'].elements['continue'];
   if(u == '') return doGlobalAlert('Please enter your username.');
   else if(a == '') return doGlobalAlert('Please answer the authorization question.');
   var url = '../includes/json.php?operation=passwordReminder&u='+encodeURIComponent(u)+'&sid='+sid+'&a='+encodeURIComponent(a);
   button.value = 'Working...';
   button.disabled = true;
   simpleXHR(url,'credentialResponse','credentialError');
   
}
function credentialError(){
   doGlobalAlert('Error getting information to the server!!');
}


