// This file handles a lot of functions that get called on many pages and have a lot of general-purpose use

var t;

function pagewrite(page) // This is a general-purpose AJAX-call function for writing many of the pages out
{
	// Make a variable to hold the URL for the page load

	var url;


	// Determine which page to load, catch if not a valid page

	switch(page)
	{
		case "choose":
		url="pages/choose.php";
		$.get(url, function(data){ document.forms[0].innerHTML = data; });
		break;

		case "completed":
		url="pages/completed.php";
		$.get(url, function(data){ document.forms[0].innerHTML = data; autocompleter(); cookies(); tips(); });
		break;

		case "planned":
		url="pages/planned.php";
		$.get(url, function(data){ document.forms[0].innerHTML = data; autocompleter(); cookies(); tips(); });
		break;

		case "modify":
		url="pages/modify.php";
		$.get(url, function(data){ document.forms[0].innerHTML = data; });
		break;

		default:
		document.forms[0].innerHTML = "<p>Whoops, something went wrong!  Please hit your browser's back button or click on the link above to go back to the homepage!</p>";
	}
}


function checkpage(spans, spannum) // This function checks the page to see if it should activate the submit button and scrolls to parts that need fixing
{
	if (!$(spans[0]).hasClass("valid"))
	{
		if (!$(spans[0]).hasClass("invalid"))
		{
			invalid(spans,0);
			spans[0].innerHTML = "Please select an Event Type";
		}

		document.forms[0].submit.disabled = true;

		if (spannum > 0) $.scrollTo(spans[0], 1000);
		return;
	}

	if (!$(spans[2]).hasClass("valid"))
	{
		if (!$(spans[2]).hasClass("invalid"))
		{
			invalid(spans,2);
			spans[2].innerHTML = "Please enter a valid Event Location";
		}

		document.forms[0].submit.disabled = true;

		if (spannum > 2) $.scrollTo(spans[2], 1000);
		return;
	}

	if (!$(spans[3]).hasClass("valid"))
	{
		if (!$(spans[3]).hasClass("invalid"))
		{
			invalid(spans,3);
			spans[3].innerHTML = "Please select an Event Date";
		}

		document.forms[0].submit.disabled = true;

		if (spannum > 3) $.scrollTo(spans[3], 1000);
		return;
	}

	if (!$(spans[4]).hasClass("valid"))
	{
		if (!$(spans[4]).hasClass("invalid"))
		{
			invalid(spans,4);
			spans[4].innerHTML = "Please put in your Indirect Participants numbers";
		}

		document.forms[0].submit.disabled = true;

		if (spannum > 4) $.scrollTo(spans[4], 1000);
		return;
	}

	if (!$(spans[13]).hasClass("valid"))
	{
		if (!$(spans[13]).hasClass("invalid"))
		{
			invalid(spans,13);
			spans[13].innerHTML = "Please put in your Direct Participants numbers";
		}

		document.forms[0].submit.disabled = true;

		if (spannum > 13) $.scrollTo(spans[13], 1000);
		return;
	}

	if (!$(spans[23]).hasClass("valid"))
	{
		if (!$(spans[23]).hasClass("invalid"))
		{
			invalid(spans,23);
			spans[23].innerHTML = "Please put in your Materials numbers";
		}

		document.forms[0].submit.disabled = true;

		if (spannum > 23) $.scrollTo(spans[23], 1000);
		return;
	}

	if(spans.length > 39)
	{
		if (!$(spans[37]).hasClass("valid"))
		{
			if (!$(spans[37]).hasClass("invalid"))
			{
				invalid(spans,37);
				spans[37].innerHTML = "Please enter your Institution Name";
			}

			document.forms[0].submit.disabled = true;

			if (spannum > 37) $.scrollTo(spans[37], 1000);
			return;
		}

		if (!$(spans[38]).hasClass("valid"))
		{
			if (!$(spans[38]).hasClass("invalid"))
			{
				invalid(spans,38);
				spans[38].innerHTML = "Please enter your Contact Name";
			}

			document.forms[0].submit.disabled = true;

			if (spannum > 38) $.scrollTo(spans[38], 1000);
			return;
		}

		if (!$(spans[39]).hasClass("valid"))
		{
			if (!$(spans[39]).hasClass("invalid"))
			{
				invalid(spans,39);
				spans[39].innerHTML = "Please enter your Contact E-mail";
			}

			document.forms[0].submit.disabled = true;

			if (spannum > 39) $.scrollTo(spans[39], 1000);
			return;
		}

		if (!$(spans[40]).hasClass("valid"))
		{
			if (!$(spans[40]).hasClass("invalid"))
			{
				invalid(spans,40);
				spans[40].innerHTML = "Please enter your Contact Phone Number";
			}

			document.forms[0].submit.disabled = true;

			if (spannum > 40) $.scrollTo(spans[40], 1000);
			return;
		}

		if (!$(spans[41]).hasClass("valid"))
		{
			if (!$(spans[41]).hasClass("invalid"))
			{
				invalid(spans,41);
				spans[41].innerHTML = "Please enter a password";
			}

			document.forms[0].submit.disabled = true;

			$.scrollTo(spans[41], 1000);
			return;
		}
	}
	else if (!$(spans[37]).hasClass("valid"))
	{
		if (!$(spans[37]).hasClass("invalid"))
		{
			invalid(spans,37);
			spans[37].innerHTML = "Please enter your password";
		}

		document.forms[0].submit.disabled = true;

		if (spannum > 37) $.scrollTo(spans[37], 1000);
		return;
	}

	document.forms[0].submit.disabled = false;
}


function autocompleter() // This function makes a list of countries for the autocompleter to use
{
	var data = ["Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","The Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burma","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Central African Republic","Chad","Chile","People's Republic of China","Colombia","Comoros","Democratic Republic of the Congo","Republic of the Congo","Costa Rica","Cote d'Ivoire","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Fiji","Finland","France","Gabon","The Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","North Korea","South Korea","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","The Netherlands","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palau","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","Spain","Sri Lanka","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Tajikistan","Tanzania","Thailand","Timor-Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States of America","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Yemen","Zambia","Zimbabwe"];

	$('#eventcountry').autocomplete(data);
}


function getcookie(c_name) // Getting a specific cookie and its data
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");

		if (c_start!=-1)
    		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);

			if (c_end==-1) c_end=document.cookie.length;

			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
	
}


function checkcookies(inputs) // This checks if a cookie exists and grabs it; it also clears the cookies if they would be used on the wrong page
{
	if (inputs[0].name == "idnum")
	{
		if (getcookie("idnum") != inputs[0].value)
		{
			clearcookies();
			return false;
		}
	}
	else if (getcookie("idnum") != null && getcookie("idnum") != "")
	{
		clearcookies();
		return false;
	}
	else if ((location.pathname.search("login") > -1 || location.pathname.search("register") > -1) && (getcookie("eventcountry") != null && getcookie("eventcountry") != ""))
	{
		clearcookies();
		return false;
	}
	else return true;
}


function cookies() // This function loops through the inputs and uses the cookies to assign them properly, then validates their fields
{
	var str;
	var spans = document.forms[0].getElementsByTagName("span");
	var inputs = document.getElementsByTagName("input");

	if(!checkcookies(inputs)) return;

	$(":input",document.forms[0]).each(function() {
		str = getcookie(this.name);
		if (str != null && str != "")
		{
			if (this.type != "checkbox") this.value = str;
			else switch(str)
			{
				case "true":
				this.checked = true;
				break;

				case "false":
				default:
				this.checked = false;
			}
			
			switch(this.name)
			{
				case "eventtype":
				checkother(str);
				break;

				case "eventother":
				othervalidate(str);
				break;

				case "eventloc":
				case "eventcountry":
				case "eventaddress":
				case "shippingaddress":
				locvalidate();
				break;

				case "year":
				yearchanged(str);
				break;

				case "month":
				monthchanged(str);
				break;

				case "day":
				daychanged(str);
				break;

				case "ik-8":
				case "i9-12":
				case "isu":
				case "itfield":
				case "itprof":
				case "iif":
				case "igyouth":
				case "igadult":
				case "dk-8":
				case "d9-12":
				case "dsu":
				case "dtfield":
				case "dtprof":
				case "dif":
				case "dgyouth":
				case "dgadult":
				case "hposter":
				case "mposter":
				case "fsmactiv":
				case "mmactiv":
				case "aoactiv":
				case "psactiv":
				case "pdactiv":
				case "hlitho":
				case "mlitho":
				case "plitho":
				case "lentd":
				case "stact":
				case "htact":
				validnum(this,str);
				break;

				case "ibexconf":
				case "ibexreq":
				ibexteamvalidate();
				break;

				case "institution":
				instvalidate(str);
				break;

				case "name":
				namevalidate(str);
				break;

				case "email":
				emailvalidate(str);
				break;

				case "phone":
				phonevalidate(str);
				break;
			}
		}
	});
}


function clearcookies() // This function kills cookies by setting their expiration date to a long, long time ago
{
	var inputs = ["idnum","eventtype","eventother","eventloc","eventcountry","eventaddress","shippingaddress","year","month","day","ik-8","i9-12","isu","itfield","itprof","iif","igyouth","igadult","dk-8","d9-12","dsu","dtfield","dtprof","dif","dgyouth","dgadult","ibexconf","ibexreq","hposter","mposter","fsmactiv","mmactiv","aoactiv","psactiv","pdactiv","hlitho","mlitho","plitho","lentd","stact","htact","fsmactivc","mmactivc","aoactivc","psactivc","pdactivc","pptdem","webdem","gamesdem","institution","name","email","phone","submit"];

	for (var i = 0;i < inputs.length;i++)
	{
		document.cookie = inputs[i] + "=; expires=Wed, 25 May 1977 00:00:01 UTC; path=/";
	}
}


function valid(spans, spannum) // Setting a validation span to valid and adding some default text
{
	// Validate the span specified by spannum: I used this code way too much so I made it a function
	$(spans[spannum]).removeClass("invalid");
	$(spans[spannum]).addClass("valid");
	spans[spannum].innerHTML = "Valid!";

	checkpage(spans, spannum);
}


function invalid(spans, spannum) // Setting a validation span to invalid and adding some default text
{
	// Generic invalidation function; I can add more descriptive innerHTMLs if necessary, but this should make the code a bit less mind-boggling
	$(spans[spannum]).removeClass("valid");
	$(spans[spannum]).addClass("invalid");
	spans[spannum].innerHTML = "Invalid!";

	checkpage(spans, spannum);
}


function wordvalidate(str) // Validating a word/phrase/any string, really
{
	// If it's empty, we don't want it
	if (str == "") return false;

	// Create a regular expression to exclude bad characters
	var pattern = new RegExp('[!-&(-+/:-?]');

	// Send back the result!
	return pattern.test(str);
}


function isemail(str) // Specifically checks for email formatting on a string
{
	// This is going to just really quickly check if the formatting is right on an email; it does not check if it is *really* an email, though
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return (filter.test(str));
}


function ibexteamvalidate() // Special validation for IBEX team members (no sense writing this exact code in both planned- and happenedfunctions.js)
{
	// This goes through the IBEX Confirmed Team Members (and requested ones, on the planned page) and validates them
	var spans = document.forms[0].getElementsByTagName("span");

	var ibexconf = document.forms[0].ibexconf.value;

	if  (ibexconf == "") ibexconf =  "a";

	if(wordvalidate(ibexconf))
	{
		
		invalid(spans,22);
		spans[22].innerHTML = "Invalid! Please use only alphanumeric characters!";
	}
	else
	{
		var ibexreq = document.forms[0].ibexreq.value;

		if (ibexreq.length > 0)
		{
			var ibexreq = document.forms[0].ibexreq.value;
			
			if  (ibexreq == "") ibexreq =  "a";

			if (wordvalidate(ibexreq))
			{
				invalid(spans,22);
				spans[22].innerHTML = "Invalid! Please use only alphanumeric characters!";
			}
			else valid(spans,22);
		}
		else valid(spans,22);
	}
}


function tips() // Adds the informational tooltips to their relevant pages
{
	var tipsections = $(".toolclick");

	$(tipsections[0]).simpletip({ fixed: true, position: 'right', content: 'e.g.<br />\n					<em>Adler Planetarium<br />\n					United States of America<br />\n					Adler Planetarium, 1300 South Lake Shore Drive, Chicago, IL 60605</em>' });


	$(tipsections[1]).simpletip({ fixed: true, position: 'right', content: 'Indirect Participants are anonymous. If you know specific information about participants, such as name and address, please count them in the Direct Participants section!' });

	$(tipsections[2]).simpletip({ fixed: true, position: 'right', content: 'Direct Participants are ones you have specific information about, such as name and address. If you do not have this information, please place them in the Indirect Participants section!' });

	$(tipsections[3]).simpletip({ fixed: true, position: 'right', content: 'e.g. <em>Dave McComas, Lindsay Bartolone, Nathan Schwadron</em>' });

	$(tipsections[4]).simpletip({ fixed: true, position: 'right', content: 'These materials can be found and detailed on the <a href="http://ibex.swri.edu/planetaria/" title="IBEX: Interstellar Boundary Explorer Planetaria Resources" target="_blank">IBEX Planetaria Resources</a> page.' });
}

function pwdvalidate(str) // This just makes sure the password is the right length
{
	clearTimeout(t);
	t = setTimeout('var spans = document.forms[0].getElementsByTagName("span"); var pwdspan = 37; if (spans.length > 38) pwdspan = 41; var str = document.forms[0].pwd.value; if (str.length >= 8 && str.length <= 16)	{ valid(spans,pwdspan);	} else { invalid(spans,pwdspan); spans[pwdspan].innerHTML = "Invalid! Please input an alphanumeric password between 8 and 16 characters long!";	}',800);
}

