var xmlHttp;
var resolution = screen.width + "-" + screen.height;

function getXmlHttp() {

	if (window.XMLHttpRequest) { //Mozilla
		xmlHttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}
	}
}
function sendRequest(url) {
	getXmlHttp();
	if (xmlHttp == null) {
		alert("Browser does not support HTTP Request");
		return null;
	}
	url = url + "&sid=" + Math.random();
	xmlHttp.onreadystatechange = stateChanged;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function stateChanged() {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
		if (xmlHttp.status == 200) { //
			updatePage();
		} else { //abnormal response
			window.alert("Error code: " + XMLHttpReq.status);
		}
	}
}

//this  should be overrided in calling file.
function updatePage() {
	alert("Error, please implement function updatePage()");
}

//update view count for article and application page
function updateViewCount(targetid, targetType, username, resolution, actionType) {
	//alert("/s/ajaxServer.php?op=updateStats&type="+targetType+"&targetid="+targetid+"&username="+username+"&resolution="+resolution+"&actionType="+actionType);
	sendRequest("/s/ajaxServer.php?op=updateStats&targetType=" + targetType
			+ "&targetid=" + targetid + "&username=" + username
			+ "&resolution=" + resolution + "&actionType=" + actionType);
}

//check form element ID's value. If null, return false and alert with element's title
function isNotNullAfterTrim(ID, title) {
	var theValue = document.getElementById(ID).value;
	theValue = trimAll(theValue);
	if (title == "") {
		title = ID;
	}
	if (theValue == "") {
		alert(title + " is missing.");
		return false;
	}
	document.getElementById(ID).value = theValue;
	return true;
}

//get value and trim all
function trimIt(ID) {
	//alert(ID);
	var theValue = document.getElementById(ID).value;
	theValue = trimAll(theValue);
	document.getElementById(ID).value = theValue;
}

//get value and trim all
function getTrimedValueById(ID) {
	var theValue = document.getElementById(ID).value;
	theValue = trimAll(theValue);
	return theValue;
}

//delete items, including app, article, user
function deleteItem(targetid, targetType) {
	var answer = confirm("Do you want to delete?");
	if (!answer) {
		return 1;
	}
	var url = "/s/ajaxServer.php?op=deleteItem&targetid=" + targetid
			+ "&targetType=" + targetType;
	sendRequest(url);
}

// trim left and right blank space
function trimAll(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g, "");
}

function startsWith(String, str) {
	return (String.match("^" + str) == str);
}

function endsWith(String, str) {
	return (String.match(str + "$") == str);
}
