var email_warned=false; //global variable, used when validating the email form.
var orig_email = false;
var orig_email_status = false;
var button_pressed='';

function emailKeyPress(obj) {
	if (orig_email == false) { 
		orig_email=obj.value;
		orig_email_status=obj.className;
	}
	if (obj.value==orig_email) { 
		obj.className=orig_email_status;
	} else {
		obj.className='';
	}
}

function show_other(textfield,trigger) {
	var text = document.getElementById(textfield)
	if(trigger.value==0 || trigger.value==58) {
		text.style.display="inline";
		} else {
		text.style.display="none";
	}
}
function nat_advise(sel) {
	var val=sel.options[sel.selectedIndex].value;
	var txt=sel.options[sel.selectedIndex].text;
	var s=sel.options[sel.selectedIndex].className;
	if (s!='listhi' && val!=0) {
		var msg='You have stated that your country of Nationality is '+txt+'.<br><br>Please be aware that if you are a non-EU national<br>without official refugee status in Ireland you will be required<br>to pay the full academic course fee which at the time<br>of writing was 3,654 Euro.<br><br>'
		overlib(msg,STICKY,CAPTION,'Please NOTE',FIXX,420,FIXY,100);
	}
	
}

function mousedown(id) {
  button_pressed=id;
}

function validate(page,mode) {
	var err='';
	var msg='';
    if (button_pressed=='button_next' || button_pressed=='button_finish') topage=page+1;
    if (button_pressed=='button_prev') topage=page-1;
    //alert('going from page '+page+' to page '+topage);
    if (page==8 && topage==9) show_wait() //'Please wait while we process your data<br>This make take a few seconds.');
    if (page==9 && topage==10) show_wait('Processing Application...<br>This could take up to 30 seconds.') //'Please wait while we process your data<br>This make take a few seconds.');
	switch (mode) {
	case "alumni":
	if (page==1) {
		var f=document.a.firstname.value;
		var s=document.a.surname.value;
		var e=document.a.email.value;
		var status=document.getElementById('email_status').innerHTML;
		var mta_msg=document.getElementById('mta_msg').value;
		var register=document.getElementById('register').innerHTML;
		if (f=="" || s=="") {
			err+='- Please enter your Name\n';
		}
		if (e=="") {
			// err+='- Please enter your Email Address\n';
		}
		if (((e!="") || register=='true') && !echeck(e)) {
			if(register=='true') {
				err+='- You must enter a valid email to Pre-Register.\n';
				err+='- If you are not pre-registering, click the red x above right to start again.\n';
			} else {
				err+='- Please enter a valid email Address or leave blank.\n';
			}
		}
		if (status!="") {
			var txt="Email warned State: "+email_warned+", Status: "+status.toLowerCase();
			//alert(txt);
			if (status.toLowerCase()=="undeliverable") {
				err+='- An attempt to deliver to your email address - "'+e;
				err+='"\n- has failed definitively with this error:\n';
				err+=' - '+mta_msg;
				err+='\n\n - Please enter your email address again.';
			} else if (status.toLowerCase()!="undeliverable" && status.toLowerCase()!="deliverable" && !email_warned) {
				err+='- An attempt to verify your email address - "'+e;
				err+='"\n has failed\n';
				err+='- Please double check that you have entered\n- your email address correctly\n';
				err+='- and then click the Next button again.';
				if(email_warned) { // If we have already displayed the warning.
					msg=err;
					err=''; // unset the error
				}
			}
		} // end if status
	}	
	break;

	case "application":
	if (page==1) {
	    if (document.a.coursecode[document.a.coursecode.selectedIndex].value!='22') return true;
		var ok=document.a.agree_mpm.checked;
        if (ok) {
          return true;
        } else {
          alert('- Sorry, You cannot apply for this course.\n- You do not have the required qualifications.')
        return false;
        }
	}
	if (page==2) {
		var f=document.a.firstname.value;
		var s=document.a.surname.value;
		var a=document.a.termaddress.value;
        var ct=document.a.termcountry.options[document.a.termcountry.selectedIndex].value;
        var cn=document.a.termcounty.options[document.a.termcounty.selectedIndex].value;
        var ps=document.a.dublinpostcode.options[document.a.dublinpostcode.selectedIndex].value;
		var e=document.a.email.value;
		var p=document.a.phonecontact.value;
		var h=document.a.phonehome.value;
		var m=document.a.mobile.value;
		var status=document.getElementById('email_status').innerHTML;
		var mta_msg=document.getElementById('mta_msg').value;
		if (f=="" || s=="") {
			err+='- Please enter your Name\n';
		}
		if (a=="") {
			err+='- Please enter your Address\n';
		}
        if (ct=="0") {
			err+='- Please select a Country\n';
		}
        if (ct='107' && cn=='') {
			err+='- Please select a County\n';
		}
        if (ct='107' && cn=='1' && ps=='0') {
			err+='- Please select your postcode in Co. Dublin\n';
		}

		if (p=="" && m=="" && h=="") {
			err+='- Please enter at least one Phone Number.\n';
		}
        if (e=="") {
			err+='- Please enter your Email Address\n';
		}
		if (e!="" && !echeck(e)) {
			err+='- Please enter a valid email address.\n';
		}
		if (status!="") { // This is duped here.. revise and extract to function.
			var txt="Email warned State: "+email_warned+", Status: "+status.toLowerCase();
			//alert(txt);
			if (status.toLowerCase()=="undeliverable") {
				err+='- An attempt to deliver to your email address - "'+e;
				err+='"\n- has failed definitively with this error:\n';
				err+=' - '+mta_msg;
				err+='\n\n - Please enter your email address again.';
			} else if (status.toLowerCase()!="undeliverable" && status.toLowerCase()!="deliverable" && !email_warned) {
				err+='- An attempt to verify your email address, ';
                err+='  "'+e+'"\n';
				err+='- has failed.\n\n';
				err+='- PLEASE DOUBLE-CHECK that you have entered\n- your email address correctly\n';
				err+='- and then click the Next button again.';
				if(email_warned) { // If we have already displayed the warning.
					msg=err;
					err=''; // unset the error
				}
			}
		} // end if status
	}

    if (page==3) {
		var nk=document.a.nextofkin.value;
        var nkp=document.a.nokphoneno.value;
        if (nk=="") {
			err+='- Please Enter the Name of your Next of Kin \n';
		}
        if (nkp=="") {
			err+='- Please Enter Next of Kin Phone Details\n';
		}



    }
	if (page==4) {
		var d=document.a.dobday.value;
		var m=document.a.dobmonth.value;
		var y=document.a.dobyear.value;
		var n=document.a.nationality.value;
		var g=document.a.gender.value;
        var dyes=$('#disabilityyes').attr('checked');
        var dno=$('#disabilityno').attr('checked');
        var dtext=document.a.disabilitydesc.value;
		var dd=m+'-'+d+'-'+y;
		if (!isDate(dd)) {
			var err="- Date of Birth Invalid\n";
		}
		if (n==0 || n=="") {
			err+="- Please select your country of nationality\n";
		}
		if (g==0) {
			err+="- Please select your gender\n";
		}
        if (!dno && !dyes) {
            err+="- Please specifiy either Yes or No for special needs/disability/medical condition\n";
        }
        if (dyes && dtext=='') {
            err+="- Please enter a description of your special needs/disability/medical condition\n";
        }
	}
	} // end switch mode

	if (err) {
		alert(err);
		email_warned=true;
		return false;
	}
	if (msg) {
		alert(msg);
	}
	return true;
}

function echeck(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
//		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
//		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
//		    alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
//		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
//		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
//		    alert("Invalid E-mail ID")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
//		    alert("Invalid E-mail ID")
		    return false
		 }

 		 return true					
	}


var dtCh= "-";
var minYear=1920;
var maxYear=2000;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var dob="- Error in Date of Birth:\n- ";
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert(dob+"The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert(dob+"Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert(dob+"Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert(dob+"Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert(dob+"Please enter a valid date")
		return false
	}
return true
}

function change(source,dest) {
	s=eval('document.forms[\'a\'].'+source)
	d=eval('document.forms[\'a\'].'+dest)
	x=s.options[s.selectedIndex].value;
	l=s.length;
	for (i=0;i<l;i++) {
		d.selectedIndex=i;
		if (d.options[d.selectedIndex].value==x) return(x);
	}
    d.selectedIndex=0;
}

function countrychange(t) {
	obj1=eval('document.forms.a.'+t+'country')
	obj2=eval('document.forms.a.'+t+'county')
	if	(obj1.options.selectedIndex!=108) {
		obj2.selectedIndex=1;
	} else {
		obj2.selectedIndex=0;
	}
}
		

function countychange(t) {
	obj1=eval('document.forms.a.'+t+'country')
	obj2=eval('document.forms.a.'+t+'county')
	if (obj2.selectedIndex > 1) {
	obj1.selectedIndex=108;
	}
}

function nocookies() {
	var s='Your browser must support cookies to use this Web Application'
	alert(s);
}

function bad_foto() {
	var s='Sorry, We could not recognize the file you uploaded as a photo'
	alert(s);
}

function too_young(age) {
	var s='Sorry, You have to be at least 16 years of age on the 1st of September to apply.'
	alert(s);
}
function force_pps() {
    var s='You must include your PPS Number with your application.';
    alert(s);
}

function reg_quit() {
	//alert('Are you sure');
	return true;
}
function check_lists(form,use_year) {
	var code_ob=form.elements['classlist[code]'];
	var year_ob=form.elements['classlist[year]'];
	var code=code_ob.options[code_ob.selectedIndex].value;
	if (use_year==0) {
		if (code==0) {
			var c=confirm('Class code is not selected, continue?');
		} 
	} else {
		var year=year_ob.options[year_ob.selectedIndex].value;
		if (year==0 || code==0) {
			var c=confirm('Class code or year is not selected, continue?');
		} 
	}
	if (c==false) { return false; }
	var cb=false;	
	for (i=2;i<18;i++) { // the checkboxes
		if (form.elements[i].checked) {
			cb=true;
		}
	}
	if (cb==false) {
		var cbc=confirm('Do you really want an empty report?');
	}
	if (cbc==false) { return false; }
	return true;
}
//function validate() {
//var a=validate.arguments;
//for (i=0; i<a.length; i++) {
//	alert(a[i]);
//	}
//}
function doage() {
	var today=new Date();
	var t=0;
	y=document.forms.a.dobyear;
	yy=y.options[y.selectedIndex].value;
	m=document.forms.a.dobmonth
	mm=m.options[m.selectedIndex].value;
	d=document.forms.a.dobday
	dd=d.options[d.selectedIndex].value;
	n=2012; // needs to be the year of entry, not today.getYear();
	//n=today.getYear() // beacause this year was not necesarily the year we are calculating for.. this is history anyway
	// Why was I calculating age in js and storing it in the db ???
	if (n<2000) { n=n+1900; }
	if (mm>9) {
		if (!(mm==10 && dd==1)) {
			n=n-1;
		}
	}
	var t=n-yy;
	if ((mm>=1) && (yy>1)) {
	document.forms.a.age.value=t;
	//alert(t);
	} else {
	document.forms.a.age.value="??";
	}
}
function view_myapp() {
	var myapp=window.open('myapp.php?ans=1','MyApp','scrollbars=yes,width=800,height=600');
    myapp.blur();
	myapp.focus();
}
function view_app_pdf() {
	var myapp_pdf=window.open('app_pdf.php?ans=1','MyAppPDF','scrollbars=yes,width=800,height=600');
    myapp_pdf.blur();
	myapp_pdf.focus()
}
function view_studentapp(id) {
	var url='myapp.php?admin_view=1&id='+id;
	var myapp=window.open(url,'MyApp','scrollbars=yes,width=800,height=600');
    myapp.blur();
	myapp.focus();
}
function view_alumni(id) {
	var url='myalumni.php?id='+id;
	var myapp=window.open(url,'MyApp','scrollbars=yes,width=650,height=480');
	myapp.focus();	
}

function ucwords (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // *     example 1: ucwords('kevin van zonneveld');
    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'

    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}

function showhidedublinpostcode(pvar) {
	if(pvar==1) {
		document.getElementById('postcode').style.display="inline";
	} else {
		document.getElementById('postcode').style.display="none";
	}
}

// Borrowed from lightbox by Lokesh Dhakar - http://www.huddletogether.com
function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

function show_wait(msgstr) {
    var wait=document.getElementById('wait')
    var wait_msg=document.getElementById('wait_msg')
    var wait_img=document.getElementById('wait_img')
    wait_img.innerHTML='<img src="images/loading.gif" width="32" height="32" hspace="5" align="left">';
    if (msgstr!=undefined) {
      //alert(wait.innerHTML)
      wait_msg.innerHTML=msgstr
    }

    if (navigator.appName != 'Netscape') { // IE6 don't do position:fixed.
        if (document.all && !window.opera && !window.XMLHttpRequest) {
          //alert('IE');
          wait_inner.style.position='absolute';
        }
    }

    ps=getPageSize()
    wait.style.height=(ps[1]+'px')
    wait.style.display='block';
}
