window.onload=setupEverything;



function setupEverything ()
{
	if(document.registration){
		onRegistrationFormLoaded();
	}

	if(document.topic){
		onTopicFormLoaded();
	}
}


function onTopicFormLoaded()
{
	lnk = document.getElementById('topic').action;
	document.getElementById('topic').action="javascript:submitTopicForm('"+lnk+"');";

}
function addListener(element, type, expression, bubbling)
{
	if(bubbling == null){
		bubbling = false;
	}
	if(window.addEventListener) { // Standard
		element.addEventListener(type, expression, bubbling);
		return true;
	} else if(window.attachEvent) { // IE
		element.attachEvent('on' + type, expression);
		return true;
	} else {
		return false;
	}
}

function toggleText(obj, deftext){
	if(obj.value==deftext) obj.value='';
	else if(obj.value=='') obj.value=deftext;
}


function onChkChanged (e)
{
	var targ;
	if (!e) {
		var e=window.event;
	}

	if (e.target) {
		targ=e.target;
	} else if (e.srcElement) {
		targ=e.srcElement;
	}

	if (targ.nodeType==3) {
		targ = targ.parentNode;
	}

	switch(targ.name){
		case 'chkDone1':
			toggleEnable('sel_year1');
			break;

		case 'chkDone2':
			toggleEnable('sel_year2');
			break;

		case 'chkInfo1':
			toggleDisplay('showInfo1');
			break;
		case 'chkInfo2':
			toggleDisplay('showInfo2');
			break

	}
	return false;

}

function onRegistrationFormLoaded()
{
	toggleEnable('sel_year1');
	toggleEnable('sel_year2');
	toggleDisplay('showInfo2');

	ck = document.getElementById('chkDone1');
	addListener(ck, 'change', onChkChanged);

	ck = document.getElementById('chkDone2');
	addListener(ck, 'change', onChkChanged);

	ck = document.getElementById('chkInfo1');
	addListener(ck, 'change', onChkChanged);

	ck = document.getElementById('chkInfo2');
	addListener(ck, 'change', onChkChanged);

	lnk = document.getElementById('registration').action;
	document.getElementById('registration').action="javascript:submitRegistrationForm('"+lnk+"')";
}


function isvalidstudentid(text)
{
	if(text == '') {
		return false;
	}

	var sid=/^[0-9]+-[0-9]+-[0-9]+-[0-9]+$/;

	if(!text.match(sid)){
		return false;
	}

	ar = text.split('-');


	if (ar[0].length!=4) {
		return false;
	}

	if (ar[1].length!=1){
		return false;
	}

	if (4 < ar[2].length || 1 > ar[2].length){
		return false;
	}

	if (ar[3].length>3){
		return false;
	}

	return true;

}

function submitUserForm(link)
{
	error= false;
	email=document.getElementById('id_email');
	if(!isvalidemail(email.value)){
		error=true;
		toggoleErrDisp(email, true);
		document.getElementById('msg_email').innerHTML='Mail address is not valid';
	} else {
		toggoleErrDisp(email, false );
		document.getElementById('msg_email').innerHTML='';
	}

	txt_name=document.getElementById('id_name');
	// if user's full name is ok
	if(!isvalidtext(txt_name.value)){
		toggoleErrDisp(txt_name, true);
		document.getElementById('msg_fname').innerHTML='Not a valid user Name, can only contain A-Z/a-z/0-9';
		error++;
	} else {
		toggoleErrDisp(txt_name, false);
		document.getElementById('msg_fname').innerHTML='';
	}


	if(!error){
		document.getElementById('id_dc').value='yes';
		document.registration.action=link
		document.registration.submit();
	}
}

function checkStudentInformation()
{
	haveone = false;
	if(document.registration.chkInfo1.checked){
		sid=document.getElementById('id_sid1');

		if(!isvalidstudentid(sid.value)){
			error++;
			toggoleErrDisp(sid, true);
			document.getElementById('msg_info1').innerHTML='Student id in information 1 is not valid';
		} else {
			toggoleErrDisp(sid , false );
			document.getElementById('msg_info1').innerHTML='';
			haveone = true;
		}
	}

	if(document.registration.chkInfo2.checked==true){
		sid=document.getElementById('id_sid2');
		if(!isvalidstudentid(sid.value)){
			error++;
			toggoleErrDisp(sid, true);
			document.getElementById('msg_info2').innerHTML='Student id in information 2 is not valid';
		} else {
			toggoleErrDisp(sid , false );
			document.getElementById('msg_info2').innerHTML='';
			haveone = true;
		}
	}

	if(!haveone){
		error++;
		msgbox = document.getElementById('student_info_error');
		msgbox.class="ErrorMsgBox";
		msgbox.innerHTML='You need to provide at least one Student ID';
		toggoleErrDisp(msgbox, true);
	}
	return error;
}

function submitTopicForm(lnk)
{
	if (document.topic.txt_topic_title.value == '') {
		tobj = document.getElementById('tt_error');
		tobj.innerHTML='Title cannot be empty';
		toggoleErrDisp(tobj, true);
		return;
	}

	if (document.topic.txt_topic_desc.value == '') {
		tobj = document.getElementById('ts_error');
		tobj.innerHTML='Description cannot be empty';
		toggoleErrDisp(tobj, true);
		return;
	}

	document.topic.action=lnk;
	document.topic.submit();

}

function submitRegistrationForm(lnk)
{
	error = 0;
	er_msg ='';

	resFunc=function (data){document.getElementById('messagebox').innerHTML=data;}

	txt_id = document.getElementById('id_uid');

	// if user id is ok
	if(!isvaliduserId(txt_id.value)){
		toggoleErrDisp(txt_id, true);
		er_msg = "Not a valid user id, can only contain A-Z/a-z/0-9\n"
			document.getElementById('msg_uid').innerHTML= er_msg;
		error++;
	} else {
		toggoleErrDisp(txt_id, false);
		document.getElementById('msg_uid').innerHTML='';
	}

	txt_name=document.getElementById('id_name');
	// if user's full name is ok
	if(!isvalidtext(txt_name.value)){
		toggoleErrDisp(txt_name, true);
		er_msg = "Not a valid user Name, can only contain A-Z/a-z/0-9\n"
			document.getElementById('msg_fname').innerHTML=er_msg;
		error++;
	} else {
		toggoleErrDisp(txt_name, false);
		document.getElementById('msg_fname').innerHTML='';
	}

	upass=document.getElementById('id_pass');
	cpass=document.getElementById('id_cpass');

	if((upass.value).length<=5){
		toggoleErrDisp(upass, true);
		er_msg = 'Length of the Password should be greater then 5'
			document.getElementById('msg_pass').innerHTML= er_msg;
		error++;
	} else {
		// if password and the confirm password matchs
		if(upass.value!=cpass.value){
			toggoleErrDisp(upass, true);
			toggoleErrDisp(cpass, true);
			er_msg = 'Confirm password do not match'
				document.getElementById('msg_pass').innerHTML= er_msg;
			error++;
		} else {
			toggoleErrDisp(upass, false);
			toggoleErrDisp(cpass, false);
			document.getElementById('msg_pass').innerHTML='';
		}
	}

	// checking if the email is valid
	email=document.getElementById('id_email');
	if(!isvalidemail(email.value)){
		error++;
		toggoleErrDisp(email, true);
		er_msg = 'Mail address is not valid'
			document.getElementById('msg_email').innerHTML=er_msg;
	} else {
		toggoleErrDisp(email, false );
		document.getElementById('msg_email').innerHTML='';
	}

	error +=checkStudentInformation()

		if(error==0){
			document.getElementById('id_dc').value='yes';
			reg = document.getElementById('registration');
			reg.action=lnk;
			reg.submit();
		}
}
/*******************************************************************/

/* Evaluates a javascript text */
function displayResponseNormal(da, output_id)
{
	document.getElementById(output_id).innerHTML=eval(da);
}

/****
	This function take a form's id, loops through all the
	form elements under it and and post them, a validation
	function can be added, result of the submission will be
	displayed in the provided output_id
*/
function saveInfo(resFunc, obj_id, output_id, act, rt)
{
	// we get the form
	obj=document.getElementById(obj_id);

	// how many elements are in the form
	len=obj.length;

	// start processing the elements
	str='';

	for(i=0;i<len;i++){
		// validate the element
		switch (obj[i].type){
		case 'radio':
			if(obj[i].checked)
				str+=obj[i].name+'='+obj[i].value;
			break;

		case 'checkbox':
			if(obj[i].checked)
				str+=obj[i].name+'='+obj[i].value;
			break;

		default:
			str+=obj[i].name+'='+obj[i].value;
		}
		if(i!=len-1){
			str+='&';
		}
	}

	str=encodeURI(str);
	if(!makeRequest(resFunc, output_id ,"index.php?type=action&act="+act,"post", str , rt)){
		document.forms[0].action="index.php?type=page&pname=action&act="+act;
		document.forms[0].submit();
	}
}

/***************************************************************************

COMMON UTILITY FUNCTIONS STARTS FROM HERE...

*****************************************************************************/

/************************

Toggols visibility of a element

*************************/
function toggleDisplay(oid)
{
	obj=document.getElementById(oid)
	if(obj.style.display=='none')
		obj.style.display='block';
	else
		obj.style.display='none';
}

/***
toggols between error styles
***/
function toggoleErrDisp(obj, flag)
{
	if(flag==true){
			obj.style.border='2px solid #D1351B';

			obj.style.padding='4px';
			obj.style.font='bold';
	} else {
		obj.style.border='1px solid #ddd';
	}
}

function toggleEnable(objid)
{
	obj = document.getElementById(objid);
	if(obj.disabled == ""){
		obj.disabled="disabled";
	} else {
		obj.disabled="";
	}
}

function toggleObject(obj)
{
	if(obj.disabled == true){
		obj.disabled=false;
	} else {
		obj.disabled=true;
	}
}

/***
validates form info
***/
function validateFormInput(obj)
{
	if(obj.value==''){
		toggoleErrDisp(obj, true);
		return false;
	} else {
		toggoleErrDisp(obj, false);
		return true;
	}
}

/* tests if the given text is valid */
function isvaliduserId(text)
{
	var name=/^[a-zA-Z0-9][_a-zA-Z0-9.]+$/;
	if(text.match(name)){
		return true;
	}
	return false;
}
/* tests if the given text is valid */
function isvalidtext(text)
{
	if(text=='') {
		return false;
	}
	var name=/^[a-zA-Z0-9_][a-zA-Z0-9. \s-]+$/;
	if(text.match(name))
		return true;
	return false;
}

/* checks a valid email address */
function isvalidemail(text)
{
	var email=/^[a-zA-Z0-9][a-zA-Z0-9-._\s]+@[a-zA-Z0-9-\s].+\.[a-zA-Z0-9]{2,5}$/;
	if(text.match(email)){
		return true;
	}

	return false;
}

/**
		This script keeps track of the key
		pressed and can take actions according
		to which key was pressd
**/
function keypressed(e)
{
	if(window.event)
		keynum = e.keyCode;
	else if(e.which)
		keynum = e.which;

	if(keynum==13)
		document.write('Enter key was pressed');
}

/****
Making XMLHttp Requests
resFunction> Function to work on the result
act> the request
req_type> what kind of request we are making (POST/GET)
content> only when req_type is POST, contains the variable we want to POST
res_type> what kind of response we are expecting
***/
function makeRequest(resFunction, output_id, act, req_type, content, res_type)
{
	//return false;
	var httpRequest;
	url = act;

	if (window.XMLHttpRequest){
		httpRequest = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try	{
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e)	{
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}

	if (!httpRequest) {
		alert('Giving up :( Cannot create an XMLHTTP instance. will fall back to basic html view');
		return false;
	}

	if(req_type==null) req_type='GET';

	if(res_type=='js'){
		httpRequest.onreadystatechange = function()	{
			da=alertContents(httpRequest, res_type, output_id);

			if(!da) {
				da="document.getElementById('msgbox_erro_id').style.display='block'";
				da+="document.getElementById('msgbox_erro_id').innerHTML='There was a problem with the request'";
			}

			resFunction(da, output_id);
		};
	} else {
		httpRequest.onreadystatechange = function() {
			da=alertContents(httpRequest, res_type, output_id);
			if(!da) {
				da="There was a problem with the request";
			}
			resFunction(da, output_id);
		};
	}

	httpRequest.open(req_type, url, true);

	if(req_type=='post') {
		httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		httpRequest.setRequestHeader("Content-length", content.length);
		httpRequest.setRequestHeader("Connection", "close");
		httpRequest.send(content);
	} else httpRequest.send(null);

	return true;
}

// called from makeRequest
function alertContents(httpRequest, res_type, output_id)
{
	imgsrc="<div style=\"padding: 0 50% 0 50%;\">loading...<img src=\"images/ajax-loader.gif\"</div>";

	if (httpRequest.readyState == 4) {
		if (httpRequest.status == 200) return httpRequest.responseText;
		else {
			if(res_type=='js') return false;
			else return 'There was a problem with the request';
		}

	} else {
		if(res_type=='js') return "document.getElementById('"+output_id+"').innerHTML='"+imgsrc+"';";
		else return imgsrc;
	}
}

function displayCalendar()
{
	popupCalendar = InitCalendar();
	openPopupCalendar(popupCalendar, 1970);
}
function InitCalendar()
{
	popupCalendar = new Object();

	// CONFIGURATION:

	popupCalendar.windowWidth = 230;
	popupCalendar.windowHeight = 260;
	popupCalendar.windowBgColor = '#FFFFFF';

	popupCalendar.dayCellFontColor = '#000000';
	popupCalendar.dayCellFontFace = 'verdana,arial';
	popupCalendar.dayCellFontSize = 2;
	popupCalendar.dayCellBgColor = '#FFFFFF';

	popupCalendar.dateCellFontColor = '#000000';
	popupCalendar.dateCellFontFace = 'verdana,arial';
	popupCalendar.dateCellFontSize = 2;
	popupCalendar.dateCellWeekdayBgColor = '#CCCCCC';
	popupCalendar.dateCellWeekendBgColor = '#BBBBBB';
	popupCalendar.dateCellTodayBgColor = '#FF0000';

	popupCalendar.firstYear = 1970;
	popupCalendar.lastYear = 2050;
	popupCalendar.firstDayOfWeek = 0;

	// MAIN:

	popupCalendar.monthList = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	popupCalendar.dayList = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

	popupCalendar.isOpen = false;
	return popupCalendar
}
function openPopupCalendar(popupCalendar, STARTYEAR,STARTMONTH) {
	var currentDate = new Date();
	if (STARTYEAR == null) {
		STARTYEAR = currentDate.getFullYear();
	}
	if (STARTMONTH == null) {
		STARTMONTH = currentDate.getMonth();
	}
	if (!popupCalendar.isOpen)
	{
		popupCalendar.winObj = window.open('','calendarWin','width=' + popupCalendar.windowWidth + ',height=' + popupCalendar.windowHeight + ',location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no,left=100,screenX=100,top=100,screenY=100');
	}
	popupCalendar.winObj.document.bgColor = popupCalendar.windowBgColor;
	writeCalendar(STARTYEAR,STARTMONTH, popupCalendar);
}

function writeCalendar(STARTYEAR,STARTMONTH, popupCalendar) {
	if (arguments[3] != null) {
		var yearMonthStr = arguments[3];
		STARTYEAR = parseInt(yearMonthStr.substring(0,yearMonthStr.indexOf(',')));
		STARTMONTH = parseInt(yearMonthStr.substring(yearMonthStr.indexOf(',') + 1));
	}
	popupCalendar.nextMonthMonth = STARTMONTH + 1;
	popupCalendar.nextMonthYear = STARTYEAR;
	if (popupCalendar.nextMonthMonth == 12) {
		popupCalendar.nextMonthMonth = 0;
		popupCalendar.nextMonthYear = STARTYEAR + 1;
	}
	popupCalendar.previousMonthMonth = STARTMONTH - 1;
	popupCalendar.previousMonthYear = STARTYEAR;
	if (popupCalendar.previousMonthMonth == -1) {
		popupCalendar.previousMonthMonth = 11;
		popupCalendar.previousMonthYear = STARTYEAR - 1;
	}
	var todayDateTime = new Date();
	var todayYear = todayDateTime.getFullYear();
	var todayMonth = todayDateTime.getMonth();
	var todayDate = todayDateTime.getDate();
	var calendarMonthDateTime = new Date(STARTYEAR,STARTMONTH);
	var calendarMonthStartDay = calendarMonthDateTime.getDay();
	var calendarMonthStartDayOffset = calendarMonthStartDay - popupCalendar.firstDayOfWeek;
	if (calendarMonthStartDayOffset < 0) calendarMonthStartDayOffset += 7;
	var calendarMonthDays = 31;
	if (STARTMONTH == 3 || STARTMONTH == 5 || STARTMONTH == 8 || STARTMONTH == 10) calendarMonthDays = 30;
	if (STARTMONTH == 1 && STARTYEAR % 4 == 0) calendarMonthDays = 29;
	if (STARTMONTH == 1 && STARTYEAR % 4 != 0) calendarMonthDays = 28;
	var dateCellText = new Array();
	for (var dateCellPos = 0; dateCellPos < calendarMonthStartDayOffset; dateCellPos++) dateCellText[dateCellPos] = '&nbsp;';
	for (var dateCellPos = calendarMonthStartDayOffset; dateCellPos < calendarMonthDays + calendarMonthStartDayOffset; dateCellPos++) dateCellText[dateCellPos] = dateCellPos - calendarMonthStartDayOffset + 1;
	for (var dateCellPos = calendarMonthStartDayOffset + calendarMonthDays; dateCellPos < 42; dateCellPos++) dateCellText[dateCellPos] = '&nbsp;';
	var windowHtml = '<html><head><title>' + popupCalendar.monthList[STARTMONTH] + ' ' + STARTYEAR + '</title></head>\r';
	windowHtml += '<body bgcolor="' + popupCalendar.windowBgColor + '" link="' + popupCalendar.dateCellFontColor + '" vlink="' + popupCalendar.dateCellFontColor + '" alink="' + popupCalendar.dateCellFontColor + '" marginwidth="0" marginheight="0" leftmargin="0" topmargin="0">\r';
	windowHtml += '<form>\r';
	windowHtml += '<table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%"><tr><td align="center" valign="middle">\r';
	windowHtml += '<table cellpadding="3" cellspacing="0" border="0"><tr>\r';
	windowHtml += '<td valign="middle"><input type="button" value="&nbsp;&lt;&nbsp;" onClick="javascript:window.opener.writeCalendar(' + popupCalendar.previousMonthYear + ',' + popupCalendar.previousMonthMonth + ');"></td>\r';
	windowHtml += '<td valign="middle"><select onChange="javascript:window.opener.writeCalendar(null,null,this.value);">\r';
	var monthOptionLength = (popupCalendar.lastYear - popupCalendar.firstYear + 1) * 12;
	for (var monthOption = 0; monthOption < monthOptionLength; monthOption++) {
		var optionYear = Math.floor(monthOption / 12) + popupCalendar.firstYear;
		var optionMonth = monthOption % 12;
		windowHtml += (optionYear == STARTYEAR && optionMonth == STARTMONTH) ? '<option selected ' : '<option ';
		windowHtml += 'value="' + optionYear + ',' + optionMonth + '">' + popupCalendar.monthList[optionMonth] + ' ' + optionYear + '</option>\r';
	}
	windowHtml += '</select></td>\r';
	windowHtml += '<td valign="middle"><input type="button" value="&nbsp;&gt;&nbsp;" onClick="javascript:window.opener.writeCalendar(' + popupCalendar.nextMonthYear + ',' + popupCalendar.nextMonthMonth + ');"></td>\r';
	windowHtml += '</tr></table>\r';
	windowHtml += '<table cellpadding="5" cellspacing="1" border="0">\r';
	windowHtml += '<tr>\r';
	for (var posLoop = popupCalendar.firstDayOfWeek; posLoop < 7 + popupCalendar.firstDayOfWeek; posLoop++) {
		var dayLoop = posLoop;
		if (dayLoop > 6) dayLoop -= 7;
		windowHtml += '<td bgcolor="' + popupCalendar.dayCellBgColor + '" align="center" valign="middle"><font color="' + popupCalendar.dayCellFontColor + '" face="' + popupCalendar.dayCellFontFace + '" size="' + popupCalendar.dayCellFontSize + '"><b>' + popupCalendar.dayList[dayLoop].charAt(0) + '</b></font></td>\r';
	}
	windowHtml += '</tr>\r';
	for (var posLoop = 0; posLoop < 42; posLoop++) {
		if (posLoop % 7 == 0) windowHtml += '<tr>\r';
		var cellBgColor = posLoop % 7 + popupCalendar.firstDayOfWeek;
		if (cellBgColor > 6) cellBgColor -= 7;
		cellBgColor = (cellBgColor == 0 || cellBgColor == 6) ? popupCalendar.dateCellWeekendBgColor : popupCalendar.dateCellWeekdayBgColor;
		if (todayYear == STARTYEAR && todayMonth == STARTMONTH && todayDate == dateCellText[posLoop]) cellBgColor = popupCalendar.dateCellTodayBgColor;
		windowHtml += '<td bgcolor="' + cellBgColor + '" align="center" valign="middle"><font color="' + popupCalendar.dateCellFontColor + '" face="' + popupCalendar.dateCellFontFace + '" size="' + popupCalendar.dateCellFontSize + '">\r';
		windowHtml += dateCellText[posLoop] + '</font></td>\r';
		if (posLoop % 7 == 6) windowHtml += '</tr>\r';
	}
	windowHtml += '</tr>\r';
	windowHtml += '</table>\r';
	windowHtml += '</td></tr></table>\r';
	windowHtml += '</form></body></html>\r';
	popupCalendar.winObj.document.write(windowHtml);
	popupCalendar.winObj.document.close();
	popupCalendar.winObj.focus();
}
