
// api


function getElement(el) {
	if (document.all) {
		return document.all[el];
	}
	return document.getElementById(el);
}

function getStyleObj(el) {
	if(document.layers) return el; 
	return el.style;
}



// adds leading zeros to integers
Number.padNumber = function(num, minStringLength) {
	var str = num.toString();
	for (var i = str.length; i < minStringLength; i++) {
		str = '0' + str;
	}
	return str;
}

function checkEmail(emailStr){
	var checkTLD=1; // boolean to check TLD
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;  // This the list of known TLDs that an e-mail address must end with.
	var emailPat=/^(.+)@(.+)$/; // user@domain regexp
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";  // forbidden characters
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; // joe@[123.124.233.4] is a legale-mail address. NOTE: The square brackets are required.
	var atom=validChars + '+'; // The following string represents an atom (basically a series of non-special characters.)
	var word="(" + atom + "|" + quotedUser + ")"; // The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string.
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); // The following pattern describes the structure of the user
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); // The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above.

	var matchArray=emailStr.match(emailPat); // Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze.
	if (matchArray==null){ // Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address.
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) { // Start by checking that only basic ASCII characters are in the strings (0-127).
		if (user.charCodeAt(i)>127) {
			return false;
 		  }
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			return false;
	   }
	}
	if (user.match(userPat)==null) { // See if "user" is valid 
		return false;
	}
	var IPArray=domain.match(ipDomainPat); // See if ip address is valid 
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				return false;
		   }
		}
		return true;
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			return false;
	   }
	}
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		return false;
	}
	if (len<2) {
		return false;
	}
	return true;
}

function checkCardNumWithMod10(cardNum) {
	var i;
	var cc = new Array(16);
	var checksum = 0;
	var validcc;

	// assign each digit of the card number to a space in the array 
	for (i = 0; i < cardNum.length; i++) {
		cc[i] = Math.floor(cardNum.substring(i, i+1));
	}

	// walk through every other digit doing our magic
	// if the card number is sixteen digits then start at the
	// first digit (position 0), otherwise start from the
	// second (position 1)
	for (i = (cardNum.length % 2); i < cardNum.length; i+=2) {
		var a = cc[i] * 2;
		if (a >= 10) {
			var aStr = a.toString();
			var b = aStr.substring(0,1);
			var c = aStr.substring(1,2);
			cc[i] = Math.floor(b) + Math.floor(c);
		} else {
			cc[i] = a;
		}
	}

	// add up all of the digits in the array
	for (i = 0; i < cardNum.length; i++) {
		checksum += Math.floor(cc[i]);
	}

	// if the checksum is evenly divisble by 10
	// then this is a valid card number
	validcc = ((checksum % 10) == 0);
	return validcc;
}

function cleanCardNum(cardNum) {
	var i;
	var ch;
	var newCard = "";

	// walk through the string character by character to build
	// a new string with numbers only
	i = 0;
	while (i < cardNum.length) {
		// get the current character
		ch = cardNum.substring(i, i+1);
		if ((ch >= "0") && (ch <= "9")) {
			// if the current character is a digit then add it
			// to the numbers-only string we're building
			newCard += ch;
		} else {
			// not a digit, so check if its a dash or a space
			if ((ch != " ") && (ch != "-")) {
				// not a dash or a space so fail
				return "";
			}
		}
		i++;
	}

	// we got here if we didn't fail, so return what we built
	return newCard;
}

function checkCard(cardType, cardNum){
	var validCard;
	var cardLength;
	var cardLengthOK;
	var cardStart;
	var cardStartOK;

	// clean up any spaces or dashes in the card number
	validCard = cleanCardNum(cardNum);
	if (validCard != "") {
		// check the first digit to see if it matches the card type
		cardStart = validCard.substring(0,1);
		cardStartOK = ( ((cardType == "visa") && (cardStart == "4")) ||
						((cardType == "mastercard") && (cardStart == "5")) ||
						((cardType == "american express") && (cardStart == "3")) );
		if (!(cardStartOK)) {
			// card number's first digit doesn't match card type
			return false;
		}

		// the card number is good now, so check to make sure
		// it's a the right length
		cardLength = validCard.length;          
		cardLengthOK = ( ((cardType == "visa") && ((cardLength == 13) || (cardLength == 16))) ||
						 ((cardType == "mastercard") && (cardLength == 16)) ||
						 ((cardType == "american express") && (cardLength == 15)) );
		if (!(cardLengthOK)) {
			return false;
		}

		// card number seems OK so do the Mod10
		if (checkCardNumWithMod10(validCard)) {
			return true;
		} else {
		return false;
		}
	} else {
		return false;
	}
}







/*   FORMS  */

function radioValue(radioGroup) {
	var val = 0;
	for (i = 0; i < radioGroup.length; i++) {
		if (radioGroup[i].checked) {
 			val = radioGroup[i].value; 
		}
	}
	return val;
}


function clearField(field, defaultText) {
	if (field.value == defaultText) {
		field.value = '';
	}
}

function resetField(field, defaultText) {
	if (field.value == '') {
		field.value = defaultText;
	}
}


function updateDay() {
	var monthDaysAr = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	if (document.forms[0].year[document.forms[0].year.selectedIndex].value % 4 == 0) {
		monthDaysAr[1] = 29;
	}
	var selectedDay = document.forms[0].day.selectedIndex;
	var selectedMonth = document.forms[0].month.selectedIndex;
	for (var i=this.document.forms[0].day.options.length; i>0 ;i--){
		document.forms[0].day.options[i] = null;
	}
	document.forms[0].day.options = null;
	for (var i=0; i < monthDaysAr[selectedMonth]; i++) {
		document.forms[0].day.options[i] = new Option(Number.padNumber(i+1,2), Number.padNumber(i+1,2));
	}
	if (selectedDay > document.forms[0].day.options.length - 1) {
		selectedDay = document.forms[0].day.options.length - 1;
	}
	document.forms[0].day.selectedIndex = selectedDay;
}

function nextField(formField) {
	if (formField.name == "phoneArea") {
		var limit = 3;
		var next = "phonePrefix";
	}
	if (formField.name == "phonePrefix") {
		var limit = 3;
		var next = "phoneSuffix";
	}
	if (formField.value.length >= limit) {
		document.getElementById(next).focus();
	}
}

function validate(form) {
	var words = /\w/;
	if (form.name == 'quickEmail') {
		if (!checkEmail(form.email.value)) {
			alert('Please enter a valid email address.');
			form.email.focus();
			return false;
		}
		if (!parseInt(form.zip.value)) {
			alert('Please enter your zip code.');
			form.zip.focus();
			return false;
		}
	}
	if (form.name == 'signup') {
		if (!words.test(form.firstName.value)) {
			alert('Please enter your first name.');
			form.firstName.focus();
			return false;
		}
		if (!words.test(form.lastName.value)) {
			alert('Please enter your last name.');
			form.lastName.focus();
			return false;
		}
		if (!checkEmail(form.email.value)) {
			alert('Please enter a valid email address.');
			form.email.focus();
			return false;
		}
		if (!parseInt(form.zip.value)) {
			alert('Please enter your zip code.');
			form.zip.focus();
			return false;
		}
	}
	if ((form == 'contact-add') || (form == 'contact-edit')) {
		if (!checkEmail(form.email.value)) {
			alert('Please enter a valid email address.');
			form.email.focus();
			return false;
		}
	}
	if (form.name == "contribute") {
		if (!words.test(form.firstName.value)) {
			alert('Please enter your first name.');
			form.firstName.focus();
			return false;
		}
		if (!words.test(form.lastName.value)) {
			alert('Please enter your last name.');
			form.lastName.focus();
			return false;
		}
		if (!words.test(form.address1.value)) {
			alert('Please enter your address.');
			form.address1.focus();
			return false;
		}
		if (!words.test(form.city.value)) {
			alert('Please enter your city.');
			form.city.focus();
			return false;
		}
		if (form.state.options[form.state.selectedIndex].value == '') {
			alert('Please enter your state.');
			form.state.focus();
			return false;
		}
		if (!words.test(form.zip.value)) {
			alert('Please enter your zip.');
			form.zip.focus();
			return false;
		}
		if (!checkEmail(form.email.value)) {
			alert('Please enter a valid email address.');
			form.email.focus();
			return false;
		}
		if (form.country.options[form.country.selectedIndex].value == '') {
			alert('Please enter your country.');
			form.country.focus();
			return false;
		}
		if ((radioValue(form.contribAmount) >= 200) && (!words.test(form.employer.value))) {
			alert('The FEC requires that contributors who donate in excess of $200 provide employment information. If you are not employed, please enter "none".');
			form.employer.focus();
			return false;
		}
		if ((radioValue(form.contribAmount) >= 200) && (!words.test(form.occupation.value))) {
			alert('The FEC requires that contributors who donate in excess of $200 provide employment information. If you are not employed, please enter "none".');
			form.occupation.focus();
			return false;
		}
		if ((!radioValue(form.contribAmount)) || ((radioValue(form.contribAmount) == 'other') && (!parseInt(form.otherAmount.value)))) {
			alert('Please choose an amount to contribute.');
			return false;
		}
		if (!words.test(form.ccNumber.value)) {
			alert('Please enter a valid card number.');
			form.ccNumber.focus();
			return false;
		}
		if (radioValue(form.ccType) != 'discover') {
			if (!checkCard(radioValue(form.ccType), form.ccNumber.value)) {
				alert('Please enter a valid card number.');
				form.ccNumber.focus();
				return false;
			}
		}
		if (form.ccMonth.options[form.ccMonth.selectedIndex].value == '') {
			alert('Please enter your card\'s expiration date.');
			form.ccMonth.focus();
			return false;
		}
		if (form.ccYear.options[form.ccYear.selectedIndex].value == '') {
			alert('Please enter your card\'s expiration date.');
			form.ccYear.focus();
			return false;
		}
		if (!form.elig.checked) {
			alert('Please check that you comply with federal election law.');
			form.elig.focus();
			return false;
		}
	}
	return true;
}

function updateMonthly(select) {
	if (select.options[select.selectedIndex].value == "recur") {
		getElement('monthly').className = "visible";
	} else {
		getElement('monthly').className = "hidden";
	}
}

/*  / FORMS  */





/*  OTHER  */

function switchBox(num) {
	for (var i=1; i<=3; i++) {
		if (i == num) {
			getElement('box' + i).className = 'boxOn';
			getElement('tab' + i).className = 'on';
		}
		else {
			getElement('box' + i).className = 'boxOff';
			getElement('tab' + i).className = 'off';
		}
	}
}


function expandArtcle(articleNum) {
	if (getElement('p' + articleNum).className == 'hidden') {
		getElement('p' + articleNum).className = 'visible';
		getElement('more' + articleNum).className = 'moreVisible';
		document.images['arrow' + articleNum].src = "images/gr-arrow-at.gif";
	} else {
		getElement('p' + articleNum).className = 'hidden';
		getElement('more' + articleNum).className = 'moreHidden';
		document.images['arrow' + articleNum].src = "images/gr-arrow.gif";
	}
}

function popup(url) {
	if (url == 'contribute-monthly.php') {
		winName = "monthly";
		options = 'width=300, height=250, resizable=yes, scrollbars=yes';
	}
	if (url == 'contribute-mail.php') {
		winName = "mail";
		options = 'width=450, height=500, resizable=yes, scrollbars=yes';
	}
	if (url == 'contribute-code.php') {
		winName = "code";
		options = 'width=400, height=550, resizable=yes, scrollbars=yes';
	}
	newWin = window.open(url, winName, options);
	newWin.focus();
}



