/*
-----------------------------------------------
Trinity-mp.org
Script: vdwUtil.js
Author: Ben Glassman
Organization: Vermont Design Works
Created: 
----------------------------------------------- */

vdwUtil = {
	init:function() {
		vdwUtil.mailtoFix('REMOVETHISBEFORESENDING');
		vdwUtil.preparePopups();
		vdwUtil.prepareImages();
		vdwUtil.prepareExploreNav();
		vdwUtil.prepareSubmitRollover();
		if ($('#btn-facebook').length && $('#btn-twitter').length) {
			vdwPngRollover.init({ containerIds : ['btn-facebook', 'btn-twitter'], preloadImgs : ['/assets/templates/main/images/btn-facebook-on.png', '/assets/templates/main/images/btn-twitter-on.png']});
		}
		vdwUtil.autoPopulate('input.populate');
		vdwUtil.prepareServiceLandingLinks();
	},
	mailtoFix:function(stringToRemove) {
		var links = document.getElementsByTagName('a');
		var removeText = new RegExp(stringToRemove);
		for (var i = 0; i < links.length; i++) {
			if (links[i].href.indexOf('mailto:') != -1) {
				links[i].href = links[i].href.replace(removeText, '');
				links[i].firstChild.nodeValue = links[i].firstChild.nodeValue.replace(removeText, '');
				links[i].firstChild.nodeValue = links[i].firstChild.nodeValue.replace(/mailto:/, '');
			}
		}
	},
	popUp:function(winURL, name, parameters) {
		window.open(winURL, name, parameters);
	},
	preparePopups:function() {
		if (!document.getElementsByTagName) return false;
		var lnks = document.getElementsByTagName("a");
		for (var i=0; i<lnks.length; i++) {
			if (lnks[i].className == "popup") {
				lnks[i].title+= " (opens in a new window)";
				lnks[i].onclick = function() {
					vdwUtil.popUp(this.getAttribute("href"), "popup", "width=480,height=480");
					return false;
				}
			}
			else if (lnks[i].className == "video-popup") {
				lnks[i].title+= " (opens in a new window)";
				lnks[i].onclick = function() {
					vdwUtil.popUp(this.getAttribute("href"), "video_popup", "width=680,height=440");
					return false;
				}
			}
			else if (lnks[i].className == "external") {
				lnks[i].title+= " (opens in a new window)";
				lnks[i].onclick = function() {
					vdwUtil.popUp(this.getAttribute("href"), "external", "");
					return false;
				}
			}
			else if (lnks[i].className == "quiz-popup") {
				lnks[i].title+= " (opens in a new window)";
				lnks[i].onclick = function() {
					vdwUtil.popUp(this.getAttribute("href"), "quiz_popup", "width=490,height=520");
					return false;
				}
			}
			else if (lnks[i].href != null && lnks[i].href.indexOf('.pdf') != -1) {
				lnks[i].title += " (opens in a new window)";
				lnks[i].onclick = function() {
					vdwUtil.popUp(this.getAttribute("href"), "pdf", "");
					return false;
				}
			}
		}
	},
	trimString:function(str) {
		return str.replace(/^\s*\n*\r*|\s*\n*\r*$/g,'');
	},
	fadeUp:function(element, red, green, blue) {
		if (element.fade) {
			clearTimeout(element.fade);
		}
		element.style.backgroundColor = 'rgb('+red+','+green+','+blue+')';
		if (red == 255 && green == 255 && blue == 255) {
			return;
		}
		var newred = red + Math.ceil((255-red)/10);
		var newgreen = green + Math.ceil((255-green)/10);
		var newblue = blue + Math.ceil((255-blue)/10);
		var repeat = function() {
			vdwUtil.fadeUp(element, newred, newgreen, newblue);
		}
		element.fade = setTimeout(repeat, 100);
	},
	prepareImages : function() {
		$('.image-right, .image-left').wrapInner('<div class="image_wrapper"></div>');
		$('.caption').each(function() {
			$(this).width($(this).parent().find('img').width());
		});
	},
	prepareExploreNav:function() {
		$navExplore = $('#nav-explore');
		$navTrigger = $('#nav-explore-wrapper');
		$trigger = $navTrigger.find('h2').eq(0).addClass('collapsed');
		$targets = $navExplore.find('li > ul').addClass('collapsed');
		$trigger.data('targets', $targets).click(function() {
			newClass = ($(this).attr('class') == 'collapsed') ? 'expanded' : 'collapsed';
			$targets.attr('class', newClass);
			$(this).attr('class', newClass);
		});
	},
	autoPopulate:function(input_sel) {	
		$(input_sel).each(function() {
			var populate_text = $('label[for="' + $(this).attr('id') + '"]').text();
			if (populate_text) {
				$(this).val(populate_text).data('populate_text', populate_text);				
				$(this).focus(function() {
					if ($(this).val() == $(this).data('populate_text')) {
						$(this).val('');
					}
				});
				$(this).blur(function() {
					if ($(this).val() == '') {
						$(this).val($(this).data('populate_text'));
					}
				});
			}
		});
	},
	prepareServiceLandingLinks : function() {
		if ($('body').eq(0).hasClass('service-landing-page')) {
			$('#secondary-content a, #left-column a').not($('#secondary-navigation a')).click(function() {
				vdwUtil.popUp(this.href, "external", "");
				return false;
			});
		}
	},
	prepareSubmitRollover : function() {
		$('input.submit-button').hover(function() {
			$(this).attr('src', $(this).attr('src').replace(/\.png/, '-over.png'));
		}, function() {
			$(this).attr('src', $(this).attr('src').replace(/-over\.png/, '.png'));
		});
		$.preloadImages(['/assets/templates/main/images/btn-submit-over.png']);
	}
}

vdwDOM = {
	addEvent:function(elm, evType, fn, useCapture){
		if (elm.addEventListener){
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		} else {
			elm['on' + evType] = fn;
		}
	},
	getTarget:function(e){
		var target = window.event ? window.event.srcElement : e ? e.target : null;
		if (!target){return false;}
		while(target.nodeType!=1 && target.nodeName.toLowerCase()!='body'){
			target=target.parentNode;
		}
		return target;
	},
	cancelClick:function(e){
		if (window.event){
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault){
			e.stopPropagation();
			e.preventDefault();
		}
	},
    safariClickFix:function(){
      return false;
    },
	addClass:function(element, value) {
		if (!element.className) {
			element.className = value;
		} else {
			newClassName = element.className;
			newClassName+= " ";
			newClassName+= value;
			element.className = newClassName;
		}
	},
	removeClass:function(element, value) {
		var rep = element.className.match(' '+value)?' '+value:value;
		element.className = element.className.replace(rep,'');
	},
	importNode:function(node, allChildren) {
		/* find the node type to import */
		switch (node.nodeType) {
			case document.ELEMENT_NODE:
				/* create a new element */
				var newNode = document.createElement(node.nodeName);
				/* does the node have any attributes to add? */
				if (node.attributes && node.attributes.length > 0)
					/* add all of the attributes */
					for (var i = 0, il = node.attributes.length; i < il;)
						newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
				/* are we going after children too, and does the node have any? */
				if (allChildren && node.childNodes && node.childNodes.length > 0)
					/* recursively get all of the child nodes */
					for (var i = 0, il = node.childNodes.length; i < il;)
						newNode.appendChild(vdwDOM.importNode(node.childNodes[i++], allChildren));
				return newNode;
				break;
			case document.TEXT_NODE:
			case document.CDATA_SECTION_NODE:
			case document.COMMENT_NODE:
				return document.createTextNode(node.nodeValue);
				break;
		}
	},
	firstChild:function(parent, nodeType) {
		var child = parent.firstChild;
		while (child.nodeType != nodeType) {
			child = child.nextSibling;
		}
		return child;		
	},
	/*
    getElementsByClassName
    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com
	*/
	getElementsByClassName:function(oElm, strTagName, oClassNames){
		var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
		var arrReturnElements = new Array();
		var arrRegExpClassNames = new Array();
		if(typeof oClassNames == "object"){
			for(var i=0; i<oClassNames.length; i++){
				arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
			}
		}
		else{
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
		}
		var oElement;
		var bMatchesAll;
		for(var j=0; j<arrElements.length; j++){
			oElement = arrElements[j];
			bMatchesAll = true;
			for(var k=0; k<arrRegExpClassNames.length; k++){
				if(!arrRegExpClassNames[k].test(oElement.className)){
					bMatchesAll = false;
					break;
				}
			}
			if(bMatchesAll){
				arrReturnElements.push(oElement);
			}
		}
		return (arrReturnElements)
	},
	fixNodeTypes:function() {
		/* Make sure that all the necessary node types for vdwDOM.importNode are defined */
		if (!document.ELEMENT_NODE) {
			document.ELEMENT_NODE = 1;
			document.ATTRIBUTE_NODE = 2;
			document.TEXT_NODE = 3;
			document.CDATA_SECTION_NODE = 4;
			document.ENTITY_REFERENCE_NODE = 5;
			document.ENTITY_NODE = 6;
			document.PROCESSING_INSTRUCTION_NODE = 7;
			document.COMMENT_NODE = 8;
			document.DOCUMENT_NODE = 9;
			document.DOCUMENT_TYPE_NODE = 10;
			document.DOCUMENT_FRAGMENT_NODE = 11;
			document.NOTATION_NODE = 12;
		}	
	}
}

// ---
// Array support for the push method in IE 5
if(typeof Array.prototype.push != "function"){
	Array.prototype.push = ArrayPush;
	function ArrayPush(value){
		this[this.length] = value;
	}
}

$(document).ready(function() {

	if ($('#slideshow-widget').cycle) {
		$('#slideshow-widget').cycle({ fx : 'fade'});
	}

	if ($("#content-tabs").tabs) {
		$("#content-tabs").tabs();
		window.scrollTo(0,0);
	}

    if ($('.gcal-dialog').dialog) {
	
		$('.gcal-dialog').each( function() {
			var $h3 = $(this).children('h3.gcal-title');
			var title = $h3.html();
			$(this).dialog({ autoOpen: false, title: title });
			$h3.remove();
		});

		$('a.gcal-popup').click(function(event) {
			event.preventDefault();
			id = $(this).attr('id').slice(10);
			$('#gcal-dialog-'+id).dialog('open');
		});
		
	}
	
	// format ordered lists
	$('#content ol').each(function() {
		if (!$(this).hasClass('commentlist')) {
			$(this).addClass('olstyle');
			i = 1;
			$(this).children('li').each(function() {
				$(this).prepend('<span class="number">'+i+'</span>');
				i++;
			});
		}
	});
	
	// format Q & A on FAQ page
	$('#faq #content p').each(function() {
		html = $(this).html();
		if (html.substr(0,2) == 'A.') {
			$(this).html(html.substr(2));
			$(this).prepend('<span class="a">A.</span>');
			$(this).addClass('a-text');
		} else if (html.substr(0,6) == '<em>Q.') {
			$(this).html('<em>' + html.substr(6));
			$(this).prepend('<span class="q">Q.</span>');
			$(this).addClass('q-text');
		}
	});

	 $("#newsletter-signup-form").submit(function() {
		   if ($("#newsletter_email").val() == "Email Address:" || $("#newsletter_email").val() == "") {
				 alert('Please enter your email address.');
				 return false;
		   };
	 });

});


vdwDOM.addEvent(window, 'load', vdwUtil.init, false);

$.preloadImages = function(images) {
	for(var i = 0; i < images.length; i++) {
		$("<img>").attr("src", images[i]);
	}
}

/*
jQuery Form Validation Error Container Plugin */

jQuery.fn.prepareFormVal = function() {
    return this.each(function(){
        jQuery('<div id="error-container"><h2>The following errors occured</h2><ul></ul></div>').prependTo(jQuery(this)).hide();
    });
};

