function addOption(selectbox, value, text)
{
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}

function removeAllOptions(selectbox)
{
	var i;
	for(i=selectbox.options.length-1;i>=0;i--)
	{
		//selectbox.options.remove(i);
		selectbox.remove(i);
	}
}

function addToSelect(selectbox, options, sort, addDefault)
{
	removeAllOptions(selectbox);
	if(addDefault) addOption(selectbox, "Select", "Select");
	if(sort) options.sort();
	for (var i = 0; i < options.length; i++) {
		addOption(selectbox, options[i], options[i])
	}
}

function getValFromCombo(comboId)
{
	var elem = document.getElementById(comboId);
	return elem.options[elem.selectedIndex].value;
}

function sendAjaxRequest1(url)
{
	try
	{
		xml_http = new XMLHttpRequest();
	}
	catch(e)
	{
		xml_http = new ActiveXObject("Msxml2.XMLHTTP");
	}
        var d1 = new Date();
        if(url.match(/\?.*\=.*$/)) url = url + "&time=" + d1.getTime();
        else if(url.match(/\?$/)) url = url + "time=" + d1.getTime();
        else url = url + "?time=" + d1.getTime();
	xml_http.open("GET", url, false);
	xml_http.send(null);
	return xml_http.responseText;
}

function getAjaxResponse2(url)
{
	//alert("url: " + url)
	var json_data = sendAjaxRequest1(url);
	//alert(json_data);

	if(!isset(json_data))
	{
		alert("No valid response from server");
		return "";
	}

	var json_resp = eval('('+ json_data + ')');
	/*if(isset(json_resp['error']))
	{
		alert("Error from server: " + json_resp['error']);
		return "";
        }*/

	return json_resp;
}
function getAjaxResponse(url)
{
	//alert("url: " + url)
	var json_data = sendAjaxRequest1(url);
	//alert(json_data);

	if(!isset(json_data))
	{
		alert("No valid response from server");
		return "invalid";
	}

	var json_resp = eval('('+ json_data + ')');
	if(isset(json_resp['error']))
	{
		alert("Error from server: " + json_resp['error']);
		return 'error';
        }

	return json_resp;
}

//check if string has a valid value
function isset(str)
{
        if(str === undefined) return 0;
        if(str === null) return 0;
				//convert to str
				str += "";
        if(str.match(/^\s*$/)) return 0;
        return 1;
}

function eduCeil(a, b)
{
	if(a % b == 0) return (a / b);
	else return (((a - (a % b)) / b) + 1);
}

function loginFunc(ev)
{
	var xy = getMouseXY(ev);
	document.getElementById('loginDiv').style.top = xy[1];
	document.getElementById('loginDiv').style.left = xy[0] - 300;
	document.getElementById('loginDiv').style.display="block";
	document.getElementById('userLogin').focus();
}

function logoutFunc()
{
	var url = "/common/ajax-login/logout";
	var result = getAjaxResponse(url); // logout
        if(result) window.location="/";

	/*document.getElementById('loginSuccessDiv').style.display="none";
	document.getElementById('topLogin').style.display="block";
	document.getElementById('userLogin').value = "";*/
}

function logoutAdminFunc()
{
	var url = "/common/ajax-login/logout-admin";
	var result = getAjaxResponse(url); // logout
        window.location="/";
}

function adminLoginSubmit(idField,passwordField,errorField,rembCheck) 
{
	var userName = document.getElementById(idField).value;
	var password = document.getElementById(passwordField).value;
	if(userName == "")
	{
		document.getElementById(errorField).innerHTML= "*please enter the username";
		document.getElementById(idField).focus();
		return;
	}

	if(password == "")
	{
		document.getElementById(errorField).innerHTML= "*please enter the password";
		document.getElementById(passwordField).focus();
		return;
	}

	var url = "/common/ajax-login/adminlogin?";
	url += "&adminname=" + userName;
	url += "&password=" + password;
        if(document.getElementById(rembCheck).checked == true) url += "&rembme=1";
        else url += "&rembme=0";
	// password is sensitive; don't keep it
	document.getElementById(passwordField).value = "";

	result = getAjaxResponse(url);
        if(result != 1) document.getElementById(errorField).innerHTML= "*username/password is incorrect";
        return result;
}

function loginSubmit(idField,passwordField,errorField,rembCheck) 
{
	var userName = document.getElementById(idField).value;
	var password = document.getElementById(passwordField).value;
	if(userName == "")
	{
		document.getElementById(errorField).innerHTML= "*please enter the username";
		document.getElementById(idField).focus();
		return;
	}

	if(password == "")
	{
		document.getElementById(errorField).innerHTML= "*please enter the password";
		document.getElementById(passwordField).focus();
		return;
	}

	var url = "/common/ajax-login/login?";
	url += "&username=" + userName;
	url += "&password=" + password;
        if(document.getElementById(rembCheck).checked == true) url += "&rembme=1";
        else url += "&rembme=0";
	// password is sensitive; don't keep it
	document.getElementById(passwordField).value = "";

	result = getAjaxResponse(url);
        if(result != 1) document.getElementById(errorField).innerHTML= "*username/password is incorrect";
        return result;
}

function loginSubmitFunc3(redirect_url) {
        result = loginSubmit('login_username1','login_password1','login_error1','login_remb1');
        if (result == 1) {
            if(redirect_url) window.location = redirect_url;
            else window.location = "/index";
        } else {
            document.getElementById('login_error1').style.display = "block";
	    return;
        }
}

function loginSubmitFunc2(redirect_url) {
        result = loginSubmit('login_username','login_password','login_error','login_remb');
        if (result == 1) {
            if(redirect_url) window.location = redirect_url;
            else window.location = "/index";
        } else {
            document.getElementById('login_error_div').style.display = "block";
	    return;
        }
}

function loginSubmitFunc()
{
        result = loginSubmit('userLogin','userPassword');
	if(result == 0) // unsuccessful
	{
		document.getElementById('loginWinInv').style.display="block";
		document.getElementById('userPassword').focus();
		return;
	}

	loginDiv.style.display="none";
	document.getElementById('topLogin').style.display="none";

	document.getElementById('currentUserDiv').innerHTML = "Hi " + userName;
	document.getElementById('loginSuccessDiv').style.display="block";
}

function adminValidation() 
{
    var adminname = getActiveAdmin();
    if(adminname == "") {
        alert("This area can only be accessd by admin, please login as admin");
        window.location="/";
        return;
    } else {
	document.getElementById('adminNameDiv').innerHTML = "Welcome <b>" + adminname + "</b>";
	document.getElementById('loginSuccessDiv').style.display="block";
        return;
    }
}

function getActiveAdmin()
{
	var url = "/common/ajax-login/get-active-admin?";
	var result = getAjaxResponse2(url);
	return result;
}

function getActiveUser()
{
	var url = "/common/ajax-login/get-active-user?";
	var result = getAjaxResponse(url);
	return result;
}

function userLoggedIn()
{
	var usr = getActiveUser();
	if(usr != "") return 1;
	//alert("You are not logged in; please login first. Thank you!");
	return 0;
}

function adjustLoginMenu()
{
	var url = "/common/ajax-login/get-active-user?";
	var result = getAjaxResponse(url);
	if(result == "") // no active user
	{
		document.getElementById('loginSuccessDiv').style.display="none";
		document.getElementById('topLogin').style.display="block";
	}
	else
	{
		document.getElementById('topLogin').style.display="none";
		document.getElementById('currentUserDiv').innerHTML = "Hi " + result;
		document.getElementById('loginSuccessDiv').style.display="block";
	}
}

function getMouseXY(ev)
{
	var e = ev ? ev : window.event;
	var xy = new Array();

	xy[0] = e.clientX;
	xy[1] = e.clientY;

	/*var IE = document.all ? true : false;
	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	}
	else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}
  
	if (tempX < 0){tempX = 0;}
	if (tempY < 0){tempY = 0;}*/
	
	return xy;
}

function yetToCome()
{
	alert("We are yet to come here :(");
}

function eduSetNextPrevLinksOld(divId, func, min, max, maxIndex, cur, maxPerPage)
{
	// alert("min: " + min + " max: " + max + "  maxIndex: " + maxIndex + " cur: " + cur + " maxPerPage: " + maxPerPage);
	var ip = new Array();
	ip["min"] = min;
	ip["max"] = max;
	ip["maxIndex"] = maxIndex;
	ip["cur"] = cur;
	ip["maxPerPage"] = maxPerPage;
	eduSetNextPrevDiv(ip, divId, func);
}

function eduSetNextPrevDivOld(ip, divId, func)
{
	var min = parseInt(ip["min"]);
	var max = parseInt(ip["max"]) + 1;
	var cur = parseInt(ip["cur"]);
	var maxIndex = parseInt(ip["maxIndex"]); // total indices to be shown
	var maxPerPage = parseInt(ip["maxPerPage"]);

	var numIdx = (max - min - ((max - min) % maxPerPage)) / maxPerPage;
	if((max - min) % maxPerPage != 0) numIdx++;

	var firstIdx = 1;
	var lastIdx = firstIdx + maxIndex - 1;
	if(cur > (maxIndex / 2))
	{
		var tmp = parseInt(maxIndex / 2);
		firstIdx = cur - tmp;
		lastIdx = cur + tmp;
		if(maxIndex % 2 == 0) lastIdx--;
	}
	if(lastIdx > numIdx) lastIdx = numIdx;
	if(lastIdx - firstIdx < (maxIndex - 1)) firstIdx -= (maxIndex - 1 - (lastIdx - firstIdx));
	if(firstIdx < 1) firstIdx = 1;
	// alert("firstIdx: " + firstIdx + " lastIdx: " + lastIdx + " numIdx: " + numIdx);

	var str = "";
	str += "<table frame=void border=1 > <tr>";
	str += "<td width=20%> </td>";
	for(var i = -4, idx = firstIdx; idx <= (lastIdx + 4); i++, idx++)
	{
		var nidx;
		var disp;
		var align = "center";
		var link = 1;
		var width = 5;

		if(idx == (lastIdx + 4))
		{
			// if(lastIdx == cur) link = 0;
			if(lastIdx == numIdx) continue;
			nidx = numIdx;
			disp = "Last >>";
			// align = "left";
			width = 10;
		}
		else if(idx == (lastIdx + 1))
		{
			if(lastIdx + 10 > numIdx) continue;
			nidx = lastIdx + 10;
			// disp = "Next";
			disp = nidx;
			// align = "left";
		}
		else if(idx == (lastIdx + 2))
		{
			if(lastIdx + 60 > numIdx) continue;
			nidx = lastIdx + 60;
			// disp = "Next";
			disp = nidx;
			// align = "left";
		}

		else if(idx == (lastIdx + 3))
		{
			if(lastIdx == cur) continue;
			nidx = cur + 1;
			// disp = "Next";
			disp = ">";
			// align = "left";
		}
		else if (i == -3)
		{
			idx--;
			if(cur <= 1) continue;
			nidx = cur - 1;
			// disp = "Previous";
			disp = "<";
			// align = "right";
		}
		else if (i == -4)
		{
			idx--;
			if(firstIdx <= 1) continue;
			nidx = 1;
			// disp = "Previous";
			disp = "<< First";
			// align = "right";
			width = 10;
		}
		else if (i == -1)
		{
			idx--;
			if(firstIdx <= 10) continue;
			nidx = firstIdx - 10;
			// disp = "Previous";
			disp = nidx;
			// align = "right";
		}
		else if (i == -2)
		{
			idx--;
			if(firstIdx <= 60) continue;
			nidx = firstIdx - 60;
			// disp = "Previous";
			disp = nidx;
			// align = "right";
		}
		else
		{
			if(idx == cur) link = 0;
			nidx = idx;
			disp = idx;
		}

		str += "<td width=" + width + "% align=" + align + ">";
		if(link)
		{
			str += "<a style='text-decoration:none' href=\"\" onclick=\"" + func + "(" + nidx  + "); return false;\">";
			str += disp;
			str += "</a>";
		}
		else str += "<b>" + disp + "</b>";
		str += "</td>";
	}
	str += "<td width=20%> </td>";
	str += "</tr> </table>";

	document.getElementById(divId).innerHTML = str;
}

function getViewPortDetails()
{
	var width, height;

	// std browsers e.g. mozilla/netscape/opera/IE7
	if(typeof window.innerWidth != 'undefined')
	{
		width = window.innerWidth;
		height = window.innerHeight;
	}
	// IE6 in std compliant mode (i.e. with a valid doctype as the first line in document)
	else if(typeof document.documentElement != 'undefined' &&
		typeof document.documentElement.clientWidth != 'undefined' &&
		document.documentElement.clientWidth != 0)
	{
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	}
	// older versions of IE
	{
		width = document.getElementsByTagName('body')[0].clientWidth;
		height = document.getElementsByTagName('body')[0].clientHeight;
	}

	var viewPort = new Array();
	viewPort['width'] = width;
	viewPort['height'] = height;

	return viewPort;
}

