/*	
	Name: Bang dien chung khoan
	Version: 1.0
	CreatedDate: Mar 4th 2008
	LastUpdate: Mar 4th 2008
	Description: Update cho vang, HTML Version
	Author: Tran Thach Anh
	Copyright: Release under Artistic License.
	Changes:
		- THACHANH20080313: make script more fault tolerant
*/

//Global variable;
var xmlHttpReq = null;
var delaytime = 5000;
var LockFlag = 0;
var LockCount = 0;

var counter = 0;
var debug = 0;
var debugdiv = '';
var errmsgobj = null;

function showErr(s) {
	window.status = s;
	if(errmsgobj) {
		//alert(s);
		errmsgobj.innerHTML = s;
		errmsgobj.style.display = 'block';
	}
}

function hideErr() {
	if(errmsgobj && errmsgobj.style.display == 'block') {
		errmsgobj.style.display = 'none';
		errmsgobj.innerHTML = '';
	}
}

function bangckGetUpdate(bang) {
	
	if (LockFlag == 0) {
		LockFlag = 1;
		LockCount = 0;
		bangckHTTPCall('POST', 'bangdien.php', 'data='+bang,bang);
	} else {
		LockCount++;
		if (LockCount > 10) { // Bi lock qua lau, co the do dg truyen cham, reset xmlHttpReq
			showErr('Network may be too slow or there is a problem, try again...');
			xmlHttpReq.abort();
			delete xmlHttpReq;
      		xmlHttpReq = null;
			LockFlag = 0;
		} else 
			showErr('Slow network...');
	}
	setTimeout("bangckGetUpdate('"+bang+"')",delaytime);
}

function bangckHTTPCall(sHttpMethod, sURL, sParam, result) {
    if (sHttpMethod == null) sHttpMethod = 'GET'; 
		
		if (xmlHttpReq == null)    
    // Mozilla/Safari
	    if (window.XMLHttpRequest) {
	        xmlHttpReq = new XMLHttpRequest();
	    }
	    // IE
	    else if (window.ActiveXObject) {
			try {
		    	xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
		    }
			catch (e) {
		    	xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		    }
	        //xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	    } else {//Not support
	    	alert('Not supported browser');
	    }
    if (sParam && sHttpMethod == 'GET') 
    	sURL += "?"+sParam;
    xmlHttpReq.open(sHttpMethod, sURL, true); // Async
    if (sHttpMethod == 'POST')
    	xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttpReq.onreadystatechange = function() {
    	try {
	      if (xmlHttpReq.readyState == 4) {
	      	if (xmlHttpReq.status == 200) {
						if (tab = document.getElementById(result))        		
	        			tab.innerHTML = xmlHttpReq.responseText;
	       		LockFlag = 0; // release lock
	       		counter++;
	       		window.status = 'Update counting: '+counter;
	       		hideErr();
	      	} else {//may be an error
	      		showErr('Problem with the network, retry... (code '+xmlHttpReq.status+')');
	      		LockFlag = 0; // release lock
	      	}
	      }
      }
    	catch(err) {
    		showErr('Problem with the network, retry...');
    		xmlHttpReq.abort();
				delete xmlHttpReq;
    		xmlHttpReq = null;
				LockFlag = 0;
    	}
    }
    if (sHttpMethod == 'GET')
    	xmlHttpReq.send(null);
    else
    	xmlHttpReq.send(sParam);
}

