var httpReq;

function sendRequest(page, queryString, postData, callback, skipLoadStatus) {
	httpReq = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    
    if(!page) {
    	page = 'view_controller.php';
    }
    
    if(httpReq) {
    	if(!skipLoadStatus)
			setLoadStatus(true);
    	
        httpReq.onreadystatechange = function() {processRequest(callback);};		
		// setup to handle GET or a POST, based on the data
		httpReq.open((postData == null ? "GET" : "POST"), page+'?'+queryString+'&ajax=yes', true);
		if(postData && postData.length > 0) {			
			httpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");			
		}
		
		httpReq.send(postData);
    }
}

function processRequest(callback) {
	if(httpReq.readyState == 4 && httpReq.status == 200) {
		setLoadStatus(false);
		if(!isAuthPage(httpReq.responseText)) {
			eval(callback);
		}

		//setLoadStatus(false);
    } else if (httpReq.readyState == 4 && httpReq.status != 200) {
		// oh noes, http error
		alert('HTTP error: '+httpReq.status);
		// NOTE: This console check looks perfectly valid to me - but it's throwing a Javascript error in FF. Switching to an alert for now.
		//if(console) {
		//	console.log(httpReq.responseText);
		//}
		alert(httpReq.responseText);
		setLoadStatus(false);
		return;
	}
}

function getPageDataDirect(url) {
	var req = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	
	if(req) {
		req.open("GET", url, false);
		req.send(null);
		
		if(isAuthPage(req.responseText)) {
			return null;
		}
		
		return req.responseText == null ? '' : req.responseText;
	}
}

function isAuthPage(data) {
	if(/!--isInAuth-->/.test(data)) {
		// populate the login slip contents
		var loginSlipContent = document.getElementById('loginSlipContent');
		if (loginSlipContent) {
			loginSlipContent.innerHTML = httpReq.responseText;
		}
		
		showSlip('login');
		
		var lsUsername = document.getElementById('lsUsername');
		
		if(lsUsername) {
			lsUsername.focus();
		}
		
		return true;
	} else {
		return false;
	}
}


function checkJS(what, where) {
	var needLoad;
	eval('needLoad = !document.'+what+';');
	if(needLoad)
		evalJSFrom(where);
}

function evalJSFrom(url) {
	var data = getPageDataDirect(url);
	
	if(data != null)
		eval(data);
}