// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


/*  OBJECT EXTENSIONS  */

String.prototype.trimLeft = function() { return this.replace(/^\s+/,'') }
String.prototype.trimRight = function() { return this.replace(/\s+$/,'') }
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,'') }
String.prototype.insert = function(idx,value) { return this.slice(0,idx) + value + this.slice(idx) }

//  PROTOTYPE.JS EXTENSIONS

Object.extend(Element, {
	toggleClassName: function(element,className1, className2) {
		if (Element.hasClassName(element, className1)) {
			Element.removeClassName(element, className1);
			if (className2) {
				Element.addClassName(element, className2);
			}
		}
		else {
			Element.addClassName(element, className1);
			if (className2) {
				Element.removeClassName(element, className2);
			}
		}
	}
})


//  SCRIPTACULOUS EXTENSIONS

//  add markdown syntax links to edit in place text areas
Object.extend(Ajax.InPlaceEditor.prototype, {
	createForm: function() {
	  this.form = document.createElement("form");
	  this.form.id = this.options.formId;
	  Element.addClassName(this.form, this.options.formClassName);
	  this.form.onsubmit = this.onSubmit.bind(this);

	  this.createEditField();

	  if (this.options.textarea) {
	    var br = document.createElement("br");
	    this.form.appendChild(br);
	  }

	  if (this.options.instructions) { // mods: add documentation links
	    documentation = document.createElement("div");
	    documentation.className = "documentation";
	    documentation.appendChild(document.createElement("span").appendChild(document.createTextNode("This field uses Markdown for formatting. ")));
	    cheatLink = document.createElement("a");
	    cheatLink.appendChild(document.createTextNode("cheat sheet"));
	    cheatLink.href = "javascript:popup('/content/markdown_help');";
//	    cheatLink.setAttribute("onclick", "popup('/content/markdown_help');return false;");
	    documentation.appendChild(cheatLink);
	    documentation.appendChild(document.createElement("span").appendChild(document.createTextNode(" | ")));
	    fullLink = document.createElement("a");
	    fullLink.appendChild(document.createTextNode("documentation"));
	    fullLink.href = "http://daringfireball.net/projects/markdown/syntax";
	    fullLink.target = "_blank";
	    documentation.appendChild(fullLink);
	    this.form.appendChild(documentation);
	  }
	  if (this.options.okButton) {
	    okButton = document.createElement("input");
	    okButton.type = "submit";
	    okButton.value = this.options.okText;
	    okButton.className = 'editor_ok_button';
	    this.form.appendChild(okButton);
	  }

	  if (this.options.cancelLink) {
	    cancelLink = document.createElement("a");
	    cancelLink.href = "#";
	    cancelLink.appendChild(document.createTextNode(this.options.cancelText));
	    cancelLink.onclick = this.onclickCancel.bind(this);
	    cancelLink.className = 'editor_cancel';      
	    this.form.appendChild(cancelLink);
	  }
	}
})


/*  / OBJECT EXTENSIONS  */




/*  SUB NAV  */

toggle_subnav = function(a) { //  function to show/hide subnav - walks dom to find proper ul, then either shows or hides it
	for (var i=0; i < a.parentNode.childNodes.length; i++) {
			if (a.parentNode.childNodes[i].tagName == 'UL') {
			var ul = a.parentNode.childNodes[i];
		}
	}
	if (ul.style.display == 'none') {
		new Effect.BlindDown(ul, {duration:0.25, beforeStart: toggle_subnav_arrow});
	}
	else {
		new Effect.BlindUp(ul, {duration:0.25, beforeStart: toggle_subnav_arrow});
	}
}

toggle_subnav_arrow = function(obj) { //  callback utilized by toggle_subnav to change the class of the turndown arrow - walks dom to find proper a, then changes class
	var ul = obj['element'];
	for (var i=0; i < ul.parentNode.childNodes.length; i++) {
		if (ul.parentNode.childNodes[i].tagName == 'A') {
				var a = ul.parentNode.childNodes[i];
				break;
		}
	}
	if (Element.hasClassName(a, "sub_arrow")) {
		Element.addClassName(a, "sub_arrow_down");
		Element.removeClassName(a,"sub_arrow");
	} else if (Element.hasClassName(a, "sub_arrow_down")) {
		Element.addClassName(a, "sub_arrow");
		Element.removeClassName(a,"sub_arrow_down");
	}
}

/*  / SUBNAV  */





/*  MISC SCRIPTS  */

//  popup markdown cheat sheet
//  edited by Will Lanni (WL), will@redcardstudios.com, 8/23/2008. Added Centered property, and an if/else statement. see comments inline
popup = function(path, width, height, centered) {
	if (path == undefined)   alert('no path specified to popup');
	if (width == undefined)  width = 450;
	if (height == undefined) height = 400;
//WL: added centered property, evaluate if it is defined for backwards compatibility
	if (centered == undefined) centered = false;
	day = new Date();
	id = day.getTime();
//WL: added if statement, assuming that old uses of popup are false. the eval("page"... code was the original popup code
	if (centered == false){
		eval("page" + id + " = window.open('" + path + "', '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=" + width + ",height=" + height + "');");
//WL: I added this code in primarily to launch the Anniversary site popup. Basically it just gets the screen width and height, divides by two, and places the popup left and top at the new numbers
	} else if (centered == true) {
		var winl = (screen.width-width)/2;
		var wint = (screen.height-height)/2;
		eval("page" + id + " = window.open('" + path + "', '" + id + "', 'menubar=0,toolbar=0,location=1,directories=0,status=1,scrollbars=0,resizable=0,copyhistory=0,width=" + width + ",height=" + height + ",top="+wint+",left="+winl+"');");
	}
}

// open links to external sites in a _blank window
// must be called onload

links_in_new_window = function() {
	server_name = window.location.host
	anchors = document.getElementsByTagName("A");
	for (var i=0; i < anchors.length; i++) {
		if ((anchors[i].href.indexOf(server_name) == -1) && (anchors[i].href.indexOf("mailto") == -1) && (anchors[i].href.length > 0)) {
			anchors[i].target = "_blank";
		}
	}
}


/*  / MISC SCRIPTS  */





/*  FORM VALIDATION  */

validate = function(form) {
	if (form.name == 'loi_form') {  // LETTER OF INQUIRY FORM
		if ($F('grantee_name').trim() == '') {
			alert('Please enter your organization\'s name');
			$('grantee_name').focus();
			return false;
		}
		if ($F('grantee_address1').trim() == '') {
			alert('Please enter your organization\'s address');
			$('grantee_address1').focus();
			return false;
		}
		if ($F('grantee_city').trim() == '') {
			alert('Please enter your organization\'s city');
			$('grantee_city').focus();
			return false;
		}
		if ($F('grantee_state').trim() == '') {
			alert('Please enter your organization\'s state');
			$('grantee_state').focus();
			return false;
		}
		if (!check_zip($F('grantee_zip').trim())) {
			alert('Please enter your organization\'s zip code');
			$('grantee_zip').focus();
			return false;
		}
		if (!check_phone_number($F('grantee_phone'))) {
			alert('Please enter your organization\'s phone number, including the area code');
			$('grantee_phone').focus();
			return false;
		}
		if ($F('contact_firstname').trim() == '') {
			alert('Please enter your primary contact\'s first name');
			$('contact_firstname').focus();
			return false;
		}
		if ($F('contact_lastname').trim() == '') {
			alert('Please enter your primary contact\'s last name');
			$('contact_lastname').focus();
			return false;
		}
		if ($F('contact_title').trim() == '') {
			alert('Please enter your primary contact\'s title');
			$('contact_title').focus();
			return false;
		}
		if (!check_phone_number($F('contact_phone_phone_number'))) {
			alert('Please enter your primary contact\'s phone number, with area code');
			$('contact_phone_phone_number').focus();
			return false;
		}
		if (!check_email($F('contact_email_email_address'))) {
			alert('Please enter your primary contact\'s email address');
			$('contact_email_email_address').focus();
			return false;
		}
		if ($F('letter_of_inquiry_area_of_interest') == 'Please Choose...') {
			alert('Please choose the area of interest under which you will be applying');
			$('letter_of_inquiry_area_of_interest').focus();
			return false;
		}
		if (($F('letter_of_inquiry_previous_letter') != 0) && ($F('previous_letter_month') == 'Month')) {
			alert('Please choose the approximate month when you sent your last letter of inquiry');
			$('previous_letter_month').focus();
			return false;
		}
		if (($F('letter_of_inquiry_previous_letter') != 0) && ($F('previous_letter_year') == 'Year')) {
			alert('Please choose the year when you sent your last letter of inquiry');
			$('previous_letter_year').focus();
			return false;
		}
		if (($F('letter_of_inquiry_previous_grant') != 0) && ($F('previous_grant_month') == 'Month')) {
			alert('Please choose the approximate month when you received your grant');
			$('previous_grant_month').focus();
			return false;
		}
		if (($F('letter_of_inquiry_previous_grant') != 0) && ($F('previous_grant_year') == 'Year')) {
			alert('Please choose the year when you received your grant');
			$('previous_grant_year').focus();
			return false;
		}
		if ($F('letter_of_inquiry_letter').trim() == '') {
			alert('Please include your letter of inquiry');
			$('letter_of_inquiry_letter').focus();
			return false;
		}
		
		
		
	}
	else {
		alert("invalid form: " + form.name);
		return false;
	}
	return true;
}

/*  / FORM VALIDATION  */




/*  FORM VALIDATION HELPERS  */

function check_email(emailStr){
	var checkTLD=0; // 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 legal e-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;
}

check_phone_number = function(str) {
	str = str.replace(/\D/g, '');
	var phone_pat = /^1?\d{10}$/;
	if (str.match(phone_pat) == null) {
		return false;
	} else {
		return true;
	}
}

check_zip = function(str) {
	var zip_pat = /\d{5,}/;
	if (str.match(zip_pat) == null) {
		return false;
	} else {
		return true;
	}
}

check_password = function(str) {
	if ((str.length >= 4) && (str.match(/^[a-zA-Z0-9]*$/)))
		return true;
	else 
		return false;
}

confirm_password = function(str1, str2) {
	if ((check_password(str1)) && (check_password(str2)) && (str1 == str2))
		return true;
	else
		return false;
}

limit_chars = function(form_element, length) {
	if ($(form_element).value.length > length) {
		$(form_element).value = $(form_element).value.substr(0, length);
		alert("Sorry, you have exceeded the limit of " + length + " characters");
	}
}


/*  / FORM VALIDATION HELPERS  */
