/*-------------------------------------------------------------------
ASI2009.JS: Javascript functions for ASI 2009 webpages.

Written: 24th Sept. 2008
Last   : 17th Oct. 2008
Author : Reks <reks_AT_iiap.res.in>
--------------------------------------------------------------------*/

var request    = null;
var dField     = '';
var formInputs = '';
var bigTxt;

function createRequest()
{
	try
	{
		request = new XMLHttpRequest();
	} catch (trymicrosoft)
	{
		try
			{
				request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (tryothermicrosoft)
		{
			try
			{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed)
			{
				request = null;
			}
		}
	}
	if (request == null) alert("Unable to initialize AJAX functionalities");
}

function fetchAuthorFields()
{
	dField      = 'authInfo';
	var auCount = document.getElementById('authors').value;
	var url     = "/asi2009/scripts/addFields.php?auCount="+auCount;
	disableField('authors');
	fetchFields(url);
	enableField('authors');
}

function fetchRegInfo()
{
	dField = 'accDetails';
	var regEmail = document.getElementById('email').value;
	var url = "/asi2009/scripts/getRegInfo.php?emailID="+regEmail;
	fetchFields(url);
}

function fetchFields(url)
{
	document.getElementById(dField).innerHTML = 'Please wait..';
	createRequest();
	request.open("GET", url, true);
	request.onreadystatechange = updateForm;
	request.send('');
}

function updateForm()
{
	if (request.readyState == 4)
	{
		var newFields = request.responseText;
		document.getElementById(dField).innerHTML = newFields;
	}
}

function changeAccType()
{
	if (document.getElementById('accPackage').checked)
	{
		disableField('pdCount');
		disableField('startDate');
	}
	if (document.getElementById('accCustom').checked)
	{
		enableField('pdCount');
		enableField('startDate');
	}
}

function checkSupport()
{
	hideField('finSupport');
	if (document.getElementById('support').value == 'required') showField('finSupport');
}

function checkThesis()
{
	if (document.getElementById('pType').value == 'thesis')
	{
		enableField('thesisInfo');
		showField('thesisInfo');
	}
	else
	{
		disableField('thesisInfo');
		hideField('thesisInfo');
	}
}

function checkReg(count)
{
	var field1 = 'regUser'+count;
	var field2 = 'emailDiv'+count;
	var field3 = 'nameDiv'+count;
	showField('regChkBox'+count);
	if (document.getElementById(field1).checked)
	{
		showField(field2);
		hideField(field3);
	}
	else
	{
		hideField(field2);
		showField(field3);
	}
}

function checkRegForm()
{
	checkSupport();
	checkGuests();
}

function chkBothFinBoxes(count)
{
	var both = 'participant'+count;
	var trav = 'travelSupport'+count;
	var regf = 'regFee'+count;

	if (document.getElementById(both).checked)
	{
		document.getElementById(trav).checked=true;
		document.getElementById(regf).checked=true;
	}
	else if (document.getElementById(both).checked==false)
	{
		document.getElementById(trav).checked=false;
		document.getElementById(regf).checked=false;
	}
}

function chkFinBoxes(count)
{
	var both = 'participant'+count;
	var trav = 'travelSupport'+count;
	var regf = 'regFee'+count;

	if ((document.getElementById(trav).checked)&&(document.getElementById(regf).checked))
		document.getElementById(both).checked=true;
	else
		document.getElementById(both).checked=false;
}

function resetRegForm()
{
	hideField('finSupport');
	hideField('guest1div');
	hideField('guest2div');
	hideField('guest3div');
}

function checkGuests()
{
	hideField('guest1div');
	hideField('guest2div');
	hideField('guest3div');
	var nguests = parseInt(document.getElementById('guestCount').value);
	if (nguests == 1) showField('guest1div');
	if (nguests == 2)
	{
		showField('guest1div');
		showField('guest2div');
	}
	if (nguests == 3)
	{
		showField('guest1div');
		showField('guest2div');
		showField('guest3div');
	}
}

function checkPauth()
{
	var nAuth   = parseInt(document.getElementById('authors').value);
	var auCount = 1;
	if (nAuth > 5) nAuth = 5;
	if (nAuth > 1)
	{
		auCount = parseInt(document.getElementById('pAuthor').value);
		var i = 0;
		for (i = 1; i <= nAuth; i++) checkReg(i);
		showField('emailDiv'+auCount);
		hideField('nameDiv'+auCount);
		hideField('regChkBox'+auCount);
	}
}

function prepareAbs()
{
	checkThesis();
	fetchAuthorFields();
	var auselect = document.getElementById('authors');
	for (var i = 0; i<auselect.options.length; i++)
	{auselect.options[i].defaultSelected = auselect.options[i].selected;}
	document.getElementById('absText').value = '';
}

function showField(field){document.getElementById(field).className='show';}
function hideField(field){document.getElementById(field).className='hide';}
function disableField(field){document.getElementById(field).disabled=true;}
function enableField(field){document.getElementById(field).disabled=false;}
function tickField(field){document.getElementById(field).checked=true;}
function untickField(field){document.getElementById(field).checked=false;}
function showHide(field)
{
	var cDiv    = document.getElementById(field);
	var cButton = field+'button';
	if (cDiv.className == 'show')
	{
		hideField(field);
		document.getElementById(cButton).value = 'Show';
	}
	else
	{
		showField(field);
		document.getElementById(cButton).value = 'Hide';
	}
}

function toggleField(field)
{
	if (document.getElementById(field).checked) untickField(field);
	else tickField(field);
}
function countWords(field, countField)
{
	var wordCount = 0;
	var nWords    = '';
	var warn      = '';
	var limit     = '';
	bigTxt        = false;
	if (field == 'finJustify')
	{
		warn  = 125;
		limit = 150;
	}
	else
	{
		warn  = 180;
		limit = 200;
	}

	var absContents = trimString(document.getElementById(field).value);
	if (absContents != '') wordCount   = absContents.split(' ').length;

	if      (wordCount == 0) nWords = '';
	else if (wordCount == 1) nWords = wordCount+' word';
	else                     nWords = wordCount+' words';
	if (wordCount >= limit)
	{
		nWords  = '<span class="critical">'+nWords+'</span>';
		bigTxt  = true;
	}
	else if (wordCount >= warn) nWords = '<span class="warn">'+nWords+'</span>';
	document.getElementById(countField).innerHTML = nWords;
}

function trimString(str)
{
	str = str.replace(/(^\s*)|(\s*$)/gi,"");
	str = str.replace(/[ ]{2,}/gi," ");
	str = str.replace(/\n /,"\n");
	return str;
}

function chkEmail(field)
{
	var eMail = document.getElementById(field).value;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(eMail)) return true;
	else
	{
		alert('Invalid Email Address');
		document.getElementById(field).focus();
		return false;
	}
}

function manageCheckBoxes(mode, formType)
{
	var idName   = '';
	var fieldID  = '';
	if (formType == 'regUsers')
	{
		idName  = 'nUsers';
		fieldID = 'participant';
	}
	else if (formType == 'abstract')
	{
		idName  = 'nAbs';
		fieldID = 'abstract';
	}
	else
	{
		alert('manageCheckBoxes: Unknown formType');
	}
	var nParties = parseInt(document.getElementById(idName).value);
	var i = 0;
	if (mode == 'toggle')
	{
		for (i = 1; i <= nParties; i++){toggleField(fieldID+i);}
	}
	if (mode == 'select')
	{
		for (i = 1; i <= nParties; i++){tickField(fieldID+i);}
	}
	if (mode == 'unselect')
	{
		for (i = 1; i <= nParties; i++){untickField(fieldID+i);}
	}
}

function validateReg()
{
	formInputs = '';
	if (!chkField('fname', 'First Name/Initials')) return false;
	if (!chkField('lname', 'Last Name')) return false;
	if (!chkField('affiliation', 'Affiliation')) return false;
	if (!chkField('address', 'Address')) return false;
	if (!chkField('state', 'State')) return false;
	if (!chkField('country', 'Country')) return false;
	if (!chkField('pincode', 'Pincode')) return false;
	if (!chkField('email', 'Email')) return false;
	if (!chkEmail('email')) return false;

	var gCount = parseInt(document.getElementById('guestCount').value);
	if (gCount > 0)
	{
		formInputs = formInputs+'\nAccompanying Guests: '+gCount+'\n';
		for (var j = 1; j <= gCount; j++) if (!chkField('gname'+j, 'Guest '+j)) return false;
		var guestReg = gCount*500.0;
		formInputs = formInputs+'\n';
	}

	formInputs = formInputs+'ASI Membership: '+
		         document.getElementById('membership').value+'\n';

	var finSupport = document.getElementById('support').value;
	formInputs = formInputs+'Financial Support: '+finSupport+'\n';
	if (finSupport == 'required')
	{
		for (var i = 0; i < document.regForm.supportType.length; i++)
		{
			if (document.regForm.supportType[i].checked)
			{
				formInputs = formInputs+'Support Type: '+document.regForm.supportType[i].value+'\n';
			}
		}
		if (!chkField('finJustify', 'Support Justification')) return false;
		if (bigTxt)
		{
			alert('Justification is too long');
			document.getElementById('finJustify').focus();
			return false;
		}
	}
	var totalCash = 1000.0 + (gCount*500.0);
	formInputs = formInputs+'\nTotal Reg. Fee to be paid: Rs.'+totalCash+'\n';

	formInputs = '[Please verify your inputs before you submit]\n'+
				'      ---------------------------------------------\n\n'+
				formInputs;

	return confirm(formInputs);
}

function validateAbs()
{
	formInputs = '';
	if (!chkField('pTitle', 'Title of Presentation')) return false;

	var pType = document.getElementById('pType').value;
	var eAuthors;
	formInputs = formInputs+'Presentation Type: '+pType+'\n';
	if (pType == 'thesis')
	{
		formInputs = formInputs+'Thesis Submission date: '+
					document.getElementById('day').value+'-'+
					document.getElementById('month').value+'-'+
					document.getElementById('year').value+'\n';
	}

	if (pType != 'invited')
	{
		formInputs = formInputs+'Presentation Category: '+
					 document.getElementById('catagory').value+'\n';
	}
	var nAuthors = document.getElementById('authors').value;
	if (nAuthors > 5)
	{
		nAuthors = 5;
		eAuthors = true;
	}

	var i = 1;
	if (nAuthors == 1)
	{
		if (!chkField('email1', 'Email Address')) return false;
		if (!chkEmail('email1')) return false;
		if (pType == 'invited')
		{
			if (!chkField('fname1', 'Author First Name/Initials')) return false;
			if (!chkField('lname1', 'Author Last Name')) return false;
			if (!chkField('affiliation1', 'Affiliation')) return false;
		}
	}
	else
	{
		formInputs = formInputs+'Number of Authors: '+nAuthors+'\n';
		formInputs = formInputs+'\n';
		for (i = 1; i<=nAuthors; i=i+1)
		{
			if ((document.getElementById('regUser'+i).checked)||
				(document.getElementById('pAuthor').value == i))
			{
				if (document.getElementById('pAuthor').value == i)
				{
					formInputs = formInputs+'Author-'+i+' is the Presenting Author\n';
				}
				else
				{ 
					formInputs = formInputs+'Author-'+i+' is a Registered Participant\n';
				}
				if (!chkField('email'+i, 'Author-'+i+' Email')) return false;
				if (!chkEmail('email'+i)) return false;
			}
			else
			{
				if (!chkField('fname'+i, 'Author-'+i+' First Name/Initials')) return false;
				if (!chkField('lname'+i, 'Author-'+i+' Last Name')) return false;
				if (!chkField('affiliation'+i, 'Author-'+i+' Affiliation')) return false;
			}
			formInputs = '\n'+formInputs+'\n';
		}
		if (eAuthors == true)
		{
			var lastAuthors = document.getElementById('lastAuthors').value;
			if (/;$/.test(lastAuthors)) lastAuthors = lastAuthors.replace(/;$/, "");
			document.getElementById('lastAuthors').value = lastAuthors;

			lastAuthors.replace(/(\r|\n)/, "");
			lastAuthors.replace(/s*$/, "");

			var lAuthorList = lastAuthors.split(";");
			var j           = 0;
			var authInfo    = '';
			for (j = 0; j < lAuthorList.length; j++)
			{
				var aFields = lAuthorList[j].split(",");
				if (aFields.length != 3)
				{
					alert('Incorrect format in co-Author Fields ');
					document.getElementById('lastAuthors').focus();
					return false;
				}
				var k  = 0;
				for (k = 0; k < aFields.length; k++)
				{
					if (trimString(aFields[k]) == "")
					{
						alert('Co-Authors name/Affiliation is empty');
						document.getElementById('lastAuthors').focus();
						return false;
					}
				}
				authInfo = authInfo+lAuthorList[j]+'\n'+'                   ';
			}
			formInputs = formInputs+'Other Authors: '+authInfo+'\n';
		}
	}
	if (!chkField('absText', 'Abstract')) return false;
	if (bigTxt)
	{
		alert('Abstract is too long');
		document.getElementById('absText').focus();
		return false;
	}
	formInputs = '[Please verify your inputs before you submit]\n'+
				 '      ---------------------------------------------\n'+formInputs;
	return confirm(formInputs);
}

function validateAcc()
{
	formInputs = '';
	formInputs = 'Accommodation for participant: ';
	if (document.getElementById('accPackage').checked)
	{
		pcost      = 1500.00;
		formInputs = formInputs+' 4 nights Package\n(17th - 20th Feb.) \n';
	}
	else
	{
		var ndays  = parseInt(document.getElementById('pdCount').value);
		var dbeg   = parseInt(document.getElementById('startDate').value);
		var dend   = dbeg+ndays-1;
		var pcost  = ndays*500.0;
		formInputs = formInputs+ndays+' nights (@ Rs.500.00 per night)\n';
		formInputs = formInputs+'Duration of Stay: '+dbeg+' to '+dend+' Feb. 2009 \n';
	}
	formInputs = formInputs+'Cost: Rs.'+pcost+'\n\n';

	var nGuest  = parseInt(document.getElementById('nGuests').value);
	if (nGuest > 0)
	{
		var gdays  = parseInt(document.getElementById('gpdCount').value);
		var gdbeg  = parseInt(document.getElementById('gstartDate').value);
		var gdend  = gdbeg+gdays-1;
		var gcost  = gdays*750.0*nGuest;
		var tcost  = pcost + gcost;
		formInputs = formInputs+'Number of Guests: '+nGuest+'\n';
		formInputs = formInputs+'Accommodation for Guests: '+gdays+' nights \n(@ 750.00 per night per guest)\n';
		formInputs = formInputs+'Duration of Stay: '+gdbeg+' to '+gdend+' Feb. 2009 \n';
		formInputs = formInputs+'Cost: Rs.'+gcost+'\n\n';
		formInputs = formInputs+'Total Cost: Rs.'+tcost+'\n';
	}
	formInputs = '[Please verify your inputs before you submit]\n'+
				 '      ---------------------------------------------\n\n'+
				 formInputs;
	return confirm(formInputs);
}

function resetAcc()
{
	document.getElementById('email').value = '';
	document.getElementById('accDetails').innerHTML  = '';
}

function chkField(field, fName)
{
	var fValue = document.getElementById(field).value;
	if(trimString(fValue) == "")
	{
		alert('A mandatory field, "'+fName+'" is empty');
		document.getElementById(field).focus();
		return false;
	}
	formInputs = formInputs+fName+': '+fValue+'\n';
	return true;
}


/* Some date/time routines.. we are astronomers :-) */
function checkDate()
{
	var day   = parseFloat(document.getElementById('day').value);
	var year  = parseFloat(document.getElementById('year').value);
	day  = Math.round(day);
	year = Math.round(year);

	var month = document.getElementById('month').value;
	var ndays = getDaysinMonth(month, year);
	if (day > ndays) day = ndays;
	if (day < 1) day = 1;

	document.getElementById('day').value   = parseInt(day + 0.5);
	document.getElementById('month').value = month;
	document.getElementById('year').value  = parseInt(year + 0.5);
}

function getDaysinMonth(mm, yy)
{
	mm = parseFloat(mm);
	yy = parseFloat(yy);
	var ndays = 31;
	if ((mm == 4)||(mm == 6)||(mm == 9)||(mm == 11)) ndays = 30;
	if  (mm == 2) {
		ndays = 28;
		if ((yy %   4) == 0) ndays = 29;
		if ((yy % 100) == 0) ndays = 28;
		if ((yy % 400) == 0) ndays = 29;
	}
	return ndays;
}

