// tmLib 1.0.0--theMechanism's general code library
// Copyright 2008 Jeffrey Barke (themechanism.com)
// Dual licensed under the MIT (MIT-LICENSE.txt)
//	and GPL (GPL-LICENSE.txt) licenses.

// Dependencies:
	// Prototype 1.6.0
	// Scriptaculous 1.8.0: Builder

// theMechanism general library object
// ----------------------------------------------
var tmLib = {

	// public methods
	// ----------------------------------------------

	// string methods
	charNum2NumArr: function(str) {
		return str.match(/\d+\.?\d*/g);
	},


	// external links

	lnkExternalLaunch: function(strHref) {
		objNewWin = window.open(strHref, 'newwin');
		objNewWin.focus();
	},

	lnkPopupLaunch: function(href) {
		objNewWin = window.open(href, 'newwin', 'height=600,width=550,location=false,menubar=false');
		objNewWin.focus();
	},

	lnkExternalPrep: function() {
		if (!document.getElementsByTagName) { return false; }
		$$('a[rel="external"]', 'a.link-external').each(function(obj) {
			obj.onclick = function() {
				tmLib.lnkExternalLaunch(this.getAttribute('href'));
				return false;
			}
		} );
		$$('a[rel="nonWebFile"]', 'a.nonWebFile').each(function(obj) {
			obj.onclick = function() {
				tmLib.lnkExternalLaunch(this.getAttribute('href'));
				return false;
			}
		} );
		$$('a[rel="popup"]', 'a.popup').each(function(obj) {
			obj.onclick = function() {
				tmLib.lnkPopupLaunch(this.getAttribute('href'));
				return false;
			}
		} );
	},

	lnkJumpNav: function(strHref) { window.location.href = strHref; },


	// form helpers

	frmAddHelpers: function() {
		$$('input[type=image]').each(function(obj) {
			obj.onclick = function() {
				if (this.disabled) {
					return false;
				} else {
//					this.disabled = true;
					$(this).addClassName('input-disabled');
					return true;
				}
			}
		 } );
		// retrieve all form elements with class text
		$$('.input').each(function(obj) { 
			Event.observe(obj, 'focus', tmLib._frmFocus, false);
			Event.observe(obj, 'blur', tmLib._frmBlur, false);
		});
	},

	// form validation

	checkForm: function(objForm) {
		// local variables
		var blnError = false;										// indicates if error occurred
		var objFirst = null;										// first input for which error occurred
		// retrieve all labels
		var arrLabels = objForm.getElementsByTagName('label');
		for (var i = 0; i < arrLabels.length; i++) {
			// test for required class
			if (Element.hasClassName(arrLabels[i], 'required')) {
				if (arrLabels[i].htmlFor) {
					var objInput = $(arrLabels[i].htmlFor);
				} else {
					var objInput = Element.down(arrLabels[i], 'input');
				}
				var strErrorText = null;
				if (objInput != null) {
					// validation logic
					strErrorText = tmLib.frmValidate(objInput, arrLabels[i]);
					if (strErrorText != null) {
						if (objFirst == null) { objFirst = objInput; }
						blnError = true;
						// write correction with label object and error text
						tmLib._writeCorrection(arrLabels[i], strErrorText);
						// live autocorrect
						tmLib._addLiveCorrect(objInput);
					} else {
						tmLib._writeCorrection(arrLabels[i]);
					}
				}
			}
		}
		if (blnError) {
			objFirst.focus();
			return false;
		} else {
			return true;
		}
	},

	checkValidity: function(e) {
		var objInput = $(Event.element(e));
		var strErrorText = null;
		var arrLabels = document.getElementsByTagName('label');
		var intLen = arrLabels.length;
		for (var i = 0; i < intLen; i++) {
			if (arrLabels[i].htmlFor == objInput.id) {
				var objLabel = $(arrLabels[i]);
				break;
			} else if (arrLabels[i] == objInput.parentNode) {
				var objLabel = $(arrLabels[i]);
			}
		}
		strErrorText = tmLib.frmValidate(this, objLabel);
		if (strErrorText != null) {
			tmLib._writeCorrection(objLabel, strErrorText);
		} else {
			tmLib._writeCorrection(objLabel);
		}
	},

	frmValidate: function(objInput, objLabel) {
		if (objInput.value.strip() == '') {
			//return 'Please enter your ' + objLabel.innerHTML.toLowerCase().replace(/:/, '').replace(/\*/, '').stripTags() + '.';
			return 'Please enter your ' + objLabel.firstChild.data.toLowerCase().strip().replace(/:/, '').replace(/\*/, '').stripTags() + '.';
		} else if (Element.hasClassName(objLabel, 'requiredEmail') && !tmLib.validEmail(objInput.value)) {
			return 'Please supply a valid email address';
		}
	},

	validEmail: function(strEmail) {
		if (strEmail.match(/^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/)) {
			return true;
		}
		return false;
	},

	// private methods
	// ----------------------------------------------

	// form helpers

	_frmBlur: function(e) {
		Event.element(e).removeClassName('active');
	},

	_frmFocus: function(e) {
		obj = $(Event.element(e));
		obj.addClassName('active');
		if (obj.nodeName == 'TEXTAREA' || obj.type == 'text') { obj.select(); }
	},

	// form validation

	_addLiveCorrect: function(objInput) {
		// text and password inputs
		// objInput.getAttribute('type') == 'password'
		if (objInput.nodeName.toLowerCase() == 'input' && (objInput.getAttribute('type') == 'text')) {
			Event.observe(objInput, 'keyup', tmLib.checkValidity, false);
		// textareas
		} else if (objInput.nodeName.toLowerCase() == 'textarea') {
			Event.observe(objInput, 'keyup', tmLib.checkValidity, false);
		// selects
		} else if (objInput.nodeName.toLowerCase() == 'select') {
			Event.observe(objInput, 'change', tmLib.checkValidity, false);
		// files
		} else if (objInput.nodeName.toLowerCase() == 'input' && (objInput.getAttribute('type') == 'file')) {
			Event.observe(objInput, 'change', tmLib.checkValidity, false);
		}
	},

	_removeError: function(objLabel) {
		if (objLabel.htmlFor) {
			var objInput = $(objLabel.htmlFor);
		} else {
			var objInput = Element.down(objLabel, 'input');
		}
		var objPar = $(objInput.parentNode);
		var arrErr = objPar.select('.errorNotice');
		if (arrErr.length > 0) {
			objPar.removeChild(arrErr[0]);
		};	
	},

	_writeCorrection: function(objLabel, strText, blnCorrect) {
		if (objLabel.htmlFor) {
			var objInput = $(objLabel.htmlFor);
		} else {
			var objInput = Element.down(objLabel, 'input');
		}
		var objImage = objLabel.parentNode.getElementsByTagName('img')[0];
		// no error, remove existing error
		if (!strText) {
			if (objImage != null) { }
			Element.removeClassName(objInput, 'correctionText');
			tmLib._removeError(objLabel);
		} else {
			// error
			if (objImage == null) {
				var objImg = Builder.node('img', { className:'correctionIcon' } );
			}
			// remove existing error notice
			tmLib._removeError(objLabel);
			// add new error notice
			var objP = Builder.node('p', { className:'errorNotice' }, strText);
			objInput.parentNode.appendChild(objP);
			Element.addClassName(objInput, 'correctionText');
		}
		return true;
	}

}

// event listeners
// ----------------------------------------------
Event.observe(window, 'load', tmLib.lnkExternalPrep.bindAsEventListener(tmLib), false);
Event.observe(window, 'load', tmLib.frmAddHelpers.bindAsEventListener(tmLib), false);