/*
-----------------------------------------------
CarneyPHC.com
Script: vdwUtil.js
Author: Ben Glassman
Organization: Vermont Design Works
Created: 
----------------------------------------------- */

vdwUtil = {
	init:function() {
		vdwUtil.mailtoFix('REMOVETHISBEFORESENDING');
		vdwUtil.preparePopups();
		$jq('#nav-explore').expando({
			loadCallback : function($trigger, $targets, opts) {
				var height = 0;
				$targets.each(function() {
					var pHeight = $jq(this).parent().height();
					if (pHeight > height) { height = pHeight; }
				});
				$trigger.data('targetHeight', height);
			},
			toggleCallback : function($trigger, $targets, $this, opts) {
				var targetHeight = $trigger.hasClass(opts.openClass) ? $trigger.data('targetHeight') : 'auto';
				$jq('#nav-explore-content > li').height(targetHeight);
			}
		});
		if ($jq('#btn-facebook').length && $jq('#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.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.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.href, "external", "");
					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.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() {
		$jq('.image-right, .image-left').wrapInner('<div class="image_wrapper"></div>');
		$jq('.caption').each(function() {
			$jq(this).width($jq(this).parent().find('img').width());
		});
	},
	autoPopulate:function(input_sel) {	
		$jq(input_sel).each(function() {
			var populate_text = $jq('label[for="' + $jq(this).attr('id') + '"]').text();
			if (populate_text) {
				$jq(this).val(populate_text).data('populate_text', populate_text);				
				$jq(this).focus(function() {
					if ($jq(this).val() == $jq(this).data('populate_text')) {
						$jq(this).val('');
					}
				});
				$jq(this).blur(function() {
					if ($jq(this).val() == '') {
						$jq(this).val($jq(this).data('populate_text'));
					}
				});
			}
		});
	},
	prepareServiceLandingLinks : function() {
		if ($jq('body').eq(0).hasClass('service-landing-page')) {
			$jq('#secondary-content a, #left-column a').not($jq('#secondary-navigation a')).click(function() {
				vdwUtil.popUp(this.href, "external", "");
				return false;
			});
		}
	}
}

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;
		}	
	}
};

/*
vdwDOM.addEvent(window, 'load', vdwUtil.init, false);
*/
$jq.preloadImages = function(images) {
	for(var i = 0; i < images.length; i++) {
		$jq("<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();
    });
};

(function($) {
	// Expando Plugin by Ben Glassman
	$.fn.expando = function(options) {
		var opts = $.extend({}, $.fn.expando.defaults, options);
		return this.each(function() {
			$this = $(this);
			var o = opts;
			var $targets = $('.' + o.targetClass, $this);
			var $status = $('.' + o.statusClass, $this);
			var $trigger = $('.' + o.triggerClass, $this).bind('click', function(e) {
				e.preventDefault();
				if ($trigger.hasClass(o.openClass)) {
					$status.text(o.closedStatus);
					$targets.hide();
					$trigger.removeClass(o.openClass).addClass(o.closedClass);
				} else {
					$status.text(o.openStatus);
					$targets.show();
					$trigger.removeClass(o.closedClass).addClass(o.openClass);
				}
				if (o.toggleCallback) { o.toggleCallback($trigger, $targets, $jq(this), o); }
			});
			if (o.loadCallback) { o.loadCallback($trigger, $targets, o); }
			if (o.autoClose) { $trigger.trigger('click'); }
		});
	};
	$.fn.expando.defaults = {
		triggerClass : 'trigger',
		targetClass : 'target',
		statusClass : 'status',
		openClass : 'expanded',
		closedClass : 'collapsed',
		openStatus : 'Collapse',
		closedStatus : 'Expand',
		autoClose : 1,
		loadCallback : null,
		toggleCallback : null
	};
})(jQuery);

$jq(document).ready(vdwUtil.init);


$jq(document).ready(function() {
	
	$jq('#flyup-menu > li').hover(function() {
		var offset = $jq(this).position();
		$du = $jq(this).find('ul:eq(0)');
		if (!$du.length) { return; }
		$du.css({
			'left' : 0,
			'top' : '-' + $du.outerHeight() + 'px'
		});
	}, function() {
		$du = $jq(this).find('ul:eq(0)');
		if (!$du.length) { return; }
		$du.css({
			'left' : '-999em'
		});	
	});

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

});


