//alert('global.js');
//=========================
// execute on page load
//=========================
jQuery(document).ready(makeLink);
jQuery(document).ready(jsExtLinks);
jQuery(document).ready(FormValid_Init);
/*
AddEvent(window, "load", makeLink);
AddEvent(window, "load", jsExtLinks);
AddEvent(window, "load", FormValid_Init);
*/



//		Form Validation
//		by Paul Novitski
//		www.juniperwebcraft.com
//		last revised July 2008


// set behaviors
//=========================
function FormValid_Init()
//=========================
{
		if (!document.getElementById) return;
		if (!document.getElementsByTagName) return;

	// look for the form
	var aForms = document.getElementsByTagName('form');

//alert(aForms.length + ' forms found');	
	
		if (aForms)
		{
			for (var iForm=0; iForm < aForms.length; iForm++)
			{
				AddEvent(aForms[iForm], "submit", FormValid_ValidateForm);
			}
		}
}


//=========================
function FormValid_ValidateForm(evt)
//=========================
{
//alert('function FormValid_ValidateForm()');
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	// default status is OK
	bStatus = true;
	
	// regular expression to collect class names
	var rClasses = /\b\w+\b/g;

	// collection of controls in this form
	var aControls = this.elements;

	//alert(aControls.length + ' controls found');	
	
	for (var iCtl = 0; iCtl < aControls.length; iCtl++)
	{
		var oControl = aControls[iCtl];
		var sClass = oControl.className;
			//alert(oControl.nodeName + ' class = ' + sClass);
		
			if (sClass && sClass > '')
			{				
				var aMatches = sClass.match(rClasses);
				
				for (var iMatch = 0; iMatch < aMatches.length; iMatch++)
				{
					//alert(sClass + '\n' + aMatches[iMatch]);
					switch (aMatches[iMatch])
					{
						case 'vReq':			[bStatus, sMsg] = FormValid_ValidateRequired(oControl);			break;
						case 'vEmail':			[bStatus, sMsg] = FormValid_ValidateEmail(oControl);			break;
						case 'vPostalCode':		[bStatus, sMsg] = FormValid_ValidatePostalCode(oControl);		break;
						case 'vPhone':			[bStatus, sMsg] = FormValid_ValidatePhone(oControl);			break;
						case 'vNums':			[bStatus, sMsg] = FormValid_ValidateNums(oControl);				break;
						case 'vCustomCaptcha':	[bStatus, sMsg] = FormValid_ValidateCustomCaptcha(oControl);	break;
					}
					
						if (!bStatus)
						{
							FormValid_DisplayErrorMessage(oControl, sMsg);
							oControl.focus();
							break;
						}
				}//for
					if (!bStatus) break;
			}//if

			if (!bStatus) break;
	}

	   // if error, cancel default behavior (form submission)
		if (!bStatus)
		{
			// W3C DOM method (hide from IE)
			if (evt.preventDefault) evt.preventDefault();
		}
		
//alert('function FormValid_ValidateForm() = ' + (bStatus) ? 'true' : 'false');
	return bStatus;
}


//=========================
function FormValid_ValidateRequired(oControl)
//=========================
{
	//alert(oControl.tagName + '.value = ' + oControl.value);

	switch (oControl.tagName)
	{
		case 'INPUT':
		case 'TEXTAREA':
			bStatus = (oControl.value > '');
			break;
	}
	return [bStatus, '@ is required'];
}



//=========================
function FormValid_ValidateEmail(oControl)
//=========================
{
	var rEmail = /^[a-z0-9._-]+@[a-z0-9._-]+(\.[a-z]+)+$/i;

		// blank?
		if (oControl.value == '') return [true, ''];

	return [rEmail.test(oControl.value), '@ is invalid'];
}


//=========================
function FormValid_ValidatePostalCode(oControl)
//=========================
{
	var rPCCA = /^[a-z][0-9][a-z] *[0-9][a-z][0-9]$/i;

		// blank?
		if (oControl.value == '') return [true, ''];

	return [rPCCA.test(oControl.value), '@ is invalid'];
}


//=========================
function FormValid_ValidatePhone(oControl)
//=========================
{
	var rPhone = /^[+-. 0-9()]+$/;

		// blank?
		if (oControl.value == '') return [true, ''];

	return [rPhone.test(oControl.value), '@ is invalid'];
}


//=========================
function FormValid_ValidateNums(oControl)
//=========================
{
	var rNums = /^[- 0-9]+$/;

		// blank?
		if (oControl.value == '') return [true, ''];

	return [rNums.test(oControl.value), '@ is invalid'];
}


//=========================
function FormValid_ValidateCustomCaptcha(oControl)
//=========================
{
	// look up question
	var sQuestionId = oControl.id + '-q';
	var oQuestion = document.getElementById(sQuestionId);
		// not found?
		if (!oQuestion) return;

	var sCorrectAnswer = oQuestion.options[oQuestion.selectedIndex].value;
	
	return [(oControl.value == sCorrectAnswer), '@ has the wrong answer'];	// + '\n' + oControl.value + ' should be ' + sCorrectAnswer];
}


//=========================
function FormValid_DisplayErrorMessage(oControl, sMsgTemplate)
//=========================
{
	//alert('function FormValid_DisplayErrorMessage(' + oControl.nodeName + ', ' + sMsgTemplate + ')');

	// default value = control id
	var sId = oControl.id.replace(/_/, ' ');

	var sFormValid_FormId = oControl.form.id;
	//alert('sFormValid_FormId = ' + sFormValid_FormId);
	
	var oForm = document.getElementById(sFormValid_FormId);

	var aLabels = oForm.getElementsByTagName('LABEL');
		//alert('aLabels.length = ' + aLabels.length);
	
	for (var iLabel=0; iLabel < aLabels.length; iLabel++)
	{
		var sFor = aLabels[iLabel].getAttribute('for');
		
			if (sFor && sFor == oControl.id)
			{
				sId = aLabels[iLabel].textContent;
	//alert('sId = ' + sId);
				var iEnd = sId.indexOf(':');
					if (iEnd > 0) sId = sId.substr(0,iEnd);
				sId = sId.replace('* ', '');
				sId = sId.replace(' (required)', '');
				//sId = sId.replace(':', '');
				break;
			}
	}

	var sMsg = sMsgTemplate.replace('@', sId);
	alert(sMsg);
}



/*		externallinks.js
		by Paul Novitski - www.juniperwebcraft.com
		February 2007

This script converts all absolute URL hyperlinks to open in a new window.
19 April 2007 - also any link with the class "external"
*/

//=========================
function jsExtLinks()
//=========================
{
	//alert("function jsExtLinks()");

		// check for DOM-awareness
		if (!document.getElementById) return;
		if (!document.getElementsByTagName) return;

	var sPrompt = "(Opens in a new window)";

	var aLinks = document.getElementsByTagName("A");
	
	//alert("aLinks.length = " + aLinks.length);
	
	for (var iLink = 0; iLink < aLinks.length; iLink++)
	{
		var bExternal = false;
		var bPopup = false;
		
		var sClass = aLinks[iLink].className;		
		//var sClass = aLinks[iLink].getAttribute("class");
			if (sClass && sClass == 'popup')
			{
				bPopup = true;
			}
			else if (sClass && sClass == 'external')
			{
				bExternal = true;
			}
			else
			{		
				var sHref = aLinks[iLink].getAttribute("href");
				//alert(iLink + ": " + sHref);
				
					if (!sHref) continue;
					if (sHref == "") continue;

					if (sHref.substring(0, 4) == "http") bExternal = true;
					
					// don't open new window for any page in this website family
					if (sHref.indexOf("jw.com") >= 0 || sHref.indexOf("juniperwebcraft.com") >= 0)
					{
						bExternal = false;
					}
			}
		
			if (!bExternal && !bPopup) continue;
		
			if (bExternal)
			{
				var sClickFunction = jsExtLinksClick;
			}
			else if (bPopup)
			{
				var sClickFunction = jsPopupLinksClick;
			}
			else
			{
				continue;
			}
		
		//AddEvent(aLinks[iLink], "click", sClickFunction);
		aLinks[iLink].onclick = sClickFunction;

		var sTitle = aLinks[iLink].getAttribute("title");
		
			if (!sTitle) sTitle = '';
			if (sTitle.indexOf("new window") >= 0) continue;

			if (sTitle == "")
			{
				sTitle = sPrompt;
			}
			else
			{
				sTitle = sTitle + " " + sPrompt;
			}
		
		aLinks[iLink].setAttribute("title", sTitle);
		//alert("title: " + iLink + ": " + sTitle);
	}
}


//=========================
function jsExtLinksClick(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	var sHref = this.getAttribute("href");

	window.open (sHref, "_blank");	

	return false;
}



//=========================
function jsPopupLinksClick(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;
	
	// see if it's an image
	var rCheckImage = /\.(jpg|jpeg|gif|png)$/i;
	var rGetDims = /-(\d+)x(\d+)\.(jpg|jpeg|gif|png)$/i;
	
	var sPopupHref = 'popupImage.php?img=';
	
	var sHref = this.getAttribute("href");

	var bIsImage = rCheckImage.test(sHref);
	
	//alert((bIsImage) ? 'An image' : 'Not an image');

		if (bIsImage)
		{
			var aMatches = rGetDims.exec(sHref);
			//alert(aMatches.join('\n'));
			sHref = sPopupHref + encodeURIComponent(sHref);
			var sWindowName = "Image Pop-up";
			var sFeatures = "menubar=no,toolbar=no,directories=no,personalbar=no,scrollbars=no";
				if (aMatches) sFeatures += ",width=" + aMatches[1] + ",height=" + aMatches[2];
		}
		else
		{
			var sWindowName = "New Window";
			var sFeatures = '';
		}

	window.open(sHref, sWindowName, sFeatures);

	return false;
}


//=========================
function AddEvent(oElement, sEventName, fnFunction)
//=========================
{
	if (oElement)
	{
		if (oElement.attachEvent)
		{
			oElement.attachEvent("on" + sEventName, fnFunction);
		}
		else
		{
			oElement.addEventListener(sEventName, fnFunction, true);
		}
	}
}


// Free Mailto Spam Protection by www.phpcaptcha.org
// modified by Paul Novitski May 2010 to use class instead of id in order to process multiple links per page

var e1b2d4 = '%63%6f%6e&#116;a%63';
var m2d40a93dd = 'm%61i%6c&#116;o:';
var vd40a93dd = 'w&#101;%62&#99;r%61f';
var q881b2d4 = 't&#64;&#106;%75nip%65&#114;';
var f065193 = '&#116;%2e&#99;&#111;&#109;';
var sMTLinkClass = 'mt';

//=========================
function makeLink()
//=========================
{
	if (document.getElementsByTagName)
	{
		var aLinks = document.getElementsByTagName('a');
		
		for (var i=0; i<aLinks.length; i++)
		{
			var sClass = aLinks[i].className;
				if (sClass && sClass == sMTLinkClass)
				{
					aLinks[i].setAttribute('href', decode(m2d40a93dd + e1b2d4 + q881b2d4 + vd40a93dd + f065193));

						if (aLinks[i].firstChild.nodeName != 'IMG')
						{
							aLinks[i].innerHTML = decode(e1b2d4 + q881b2d4 + vd40a93dd + f065193);
						}
				}
		}
	}
}

function decode(s)
{
	var l = s.length, n = '', d = '';

	for (var i = 0; i < l; ++i)
	{
		if (s.charAt(i) == '') { continue; }

		if (s.charAt(i) == '%')
		{
			n = s.charAt(++i) + '' + s.charAt(++i);
			d += String.fromCharCode(parseInt(n, 16));
			continue;
		}
		else if (s.charAt(i) == '&')
		{
			i+=2;
			n = '';
			while (s.charAt(i) != ';' && i < l) {
				n += '' + s.charAt(i); i++;
			}
			d += String.fromCharCode(parseInt(n));
			continue;
		}
		else
		{
			d += s.charAt(i);
		}
	}

	return d;
}

