/*
-----------------------------------------------
JWHDesigns.com
Script: jwhUtil.js
Author: Ben Glassman
Organization: Vermont Design Works
Created: 01 Apr 2011
----------------------------------------------- */

(function($)
{
	// popup Plugin
	$.fn.popup = function(options)
	{
		var opts = $.extend({}, $.fn.popup.defaults, options);
		return this.each(function() {
			$this = $(this);
			if (opts.titleMessage) {
				$this.attr('title', ($this.attr('title') == '') ? opts.titleMessage : $this.attr('title') + ' ' + opts.titleMessage);
			}
			$this.click(function(e) {
				e.preventDefault();
				window.open($(this).attr('href'), opts.winName, opts.winParams);
			});
		});
	};
	$.fn.popup.defaults = {
		winName : 'popup',
		winParams : 'width=320,height=480,scrollbars=yes',
		titleMessage : '(opens in a new window)'
	};
	
	// parentButton Plugin
	$.fn.parentButton = function()
	{
		return this.each(function() {
			$this = $(this);
			$a = $this.find('a');
			if ($a.length) {
				$this.data('href', $a.eq(0).attr('href'));
				$this.click(function(e) {
					window.location.href = $(this).data('href');
				}).hover(function() {
					$(this).addClass('hover');
				}, function() {
					$(this).removeClass('hover');
				});			
			}
		});
	};
	
	// 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);
			$trigger.each(function() {
				$this = $(this);
				$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, $(this), o); }
				});	
				if (o.loadCallbackBeforeClose) { o.loadCallbackBeforeClose($trigger, $targets, o); }	
				if (o.autoClose) {
					$status.text(o.closedStatus);
					$targets.hide();
					$this.removeClass(o.openClass).addClass(o.closedClass);
				}			
				if (o.loadCallbackAfterClose) { o.loadCallbackAfterClose($trigger, $targets, o); }	
			});
		});
	};
	$.fn.expando.defaults = {
		triggerClass : 'trigger',
		targetClass : 'target',
		statusClass : 'status',
		openClass : 'expanded',
		closedClass : 'collapsed',
		openStatus : 'Collapse',
		closedStatus : 'Expand',
		autoClose : 1,
		loadCallback : null,
		toggleCallback : null
	};

	// Scrollpane Plugin by Ben Glassman
	$.fn.scrollpane = function(options)
	{
		var opts = $.extend({}, $.fn.scrollpane.defaults, options);
		return this.each(function() {
			$this = $(this).addClass('scrollpane').height(opts.height).css('overflow', 'hidden');
			function scrollIt(dir, amt, dur, pane) {
				switch (dir) {
					case 'up':
						scrollTop = ((pane.scrollTop() - amt) <= 0) ? 0 : pane.scrollTop() - amt;
						break;
					case 'down':
						scrollTop = ((pane.scrollTop() + amt) >= pane[0].scrollHeight) ? pane.scrollTop() : pane.scrollTop() + amt;
						break;
				}
				pane.scrollTop(scrollTop);
				$.data(pane, 'timeout', setTimeout(function() {
					scrollIt(dir, amt, dur, pane);
				}, dur));
			}
			(function($pane, opts) {
				$(opts.upSelector).bind('click', function(e) {
					e.preventDefault();
					clearTimeout($.data($pane, 'timeout'));
					$pane.scrollTop(0);
				});
				$(opts.downSelector).bind('mousedown', function() {
					clearTimeout($.data($pane, 'timeout'));
					scrollIt('down', opts.amount, opts.duration, $pane);
				}).bind('mouseup mouseout', function(e) {
					clearTimeout($.data($pane, 'timeout'));
				}).bind('click', function(e) {
					e.preventDefault();
				});;			
			})($this, opts);
		});
	};
	$.fn.scrollpane.defaults = {
		upSelector : '.btn-scrollpane-up',
		downSelector : '.btn-scrollpane-down',
		duration : 1,
		amount : 1,
		height : 100
	};
	
})(jQuery);

jQuery.validator.setDefaults({
	onfocusout : false,
	onkeyup : false,
	onclick : false,
	showErrors: function(errorMap, errorList) {
		if (jQuery(this.currentForm).find('.errors').length == 0) {
			jQuery('<div id="error-container" class="errors"><h2>The following errors occured</h2><ul></ul></div>').prependTo(jQuery(this.currentForm)).hide();
		}
		var errors = this.numberOfInvalids();
		if (errors) {
			var error_list_html = '';
			for (var i in errorList) {
				this.settings.highlight.call(this, errorList[i].element, this.settings.errorClass, this.settings.validClass);
				error_list_html += $.format('<li>{0}</li>', errorList[i].message);
			}
			$('.errors ul').html(error_list_html).parent().slideDown('fast');
			window.location.hash = '#error-container';
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call(this, elements[i], this.settings.errorClass, this.settings.validClass);
				}
			}
		}
	}
});
jQuery.validator.addMethod("noUrl", function(value, element) {
	return (value == '') ? true : !/https?:\/\//i.test(value);
}, "Value cannot contain urls");


//var jwh = {};
jwhUtil = {
	init:function() {
		jwhUtil.mailtoFix('REMOVETHISBEFORESENDING');
		jwhUtil.preparePopups();
		$('#nav-explore').expando({
			loadCallbackBeforeClose : function($trigger, $targets, opts) {
				if (!$targets.length) {
					$trigger.hide();
					return false;
				}
				var height = 0;
				$targets.each(function() {
					var pHeight = $(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';
				$('#nav-explore-content > li').height(targetHeight);
			}
		});	
		$('ul.file-alerts li a').click(function() {
			$(this).parent().hide();
		});
	/*	$('.movie-trigger').click(function() {
			$('#movie-image').hide();
		}); */
		if (document.getElementsByTagName('body')[0].id === 'index') {
			//jwhUtil.videoLoaded = false;
			$('#jwh-video-home a').bind('click', function(e) {
				e.preventDefault();
				/*if (!jwhUtil.videoLoaded) { */
					jwhUtil.videoDialog = $('#jwh-video-dialog').dialog({
						width : 600,
						height : 390,
						dialogClass : 'ui-dialog-large',
						resizable : false,
						draggable : false,
						/*
						open : function(event, ui) {
							if (jwhUtil.videoLoaded) {
								setTimeout(function() {
									jwhUtil.videoPlayer.seekTo(0);
									jwhUtil.videoPlayer.playVideo();								
								}, 1000);
							}
						},
						*/
						close : function(event, ui) {
							$('#yt_iframe').remove();
							$('#jwh-video-dialog').append('<iframe id="yt_iframe" name="yt_iframe" width="560" height="345" src="http://www.youtube.com/embed/0DU_NYwxdtI" frameborder="0" allowfullscreen="true"></iframe>');
//							jwhUtil.videoPlayer.stopVideo();
						}
					});	
				//	var tag = document.createElement('script');
				//	tag.src = "http://www.youtube.com/player_api";
				//	var firstScriptTag = document.getElementsByTagName('script')[0];
				//	firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
				/*} else {
					jwhUtil.videoDialog.dialog('open');
				}*/
			});
		}
	},
	initFAQ : function() {
		var count = 1;
		$('#content h2').each(function() {
			$this = $(this);
			$this.wrapInner('<a href="'+window.location.href+'#jwh-faq-'+count+'" class="trigger expanded">');
			$this.nextUntil('h2').not('script').wrapAll('<div class="target" id="jwh-faq-'+count+'" />');
			$faq = $this.add($this.next());
			$faq.wrapAll('<div class="jwh-faq" />');
			count++;
		});
		$('.jwh-faq').expando();
	},
	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:/, '');
			}
		}
	},
	preparePopups:function() {
		$('a.external').popup({ 'winName' : 'external', 'winParams' : '' });
	},
	createCookie : function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},	
	readCookie : function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	eraseCookie : function(name) {
		this.createCookie(name,"",-1);
	}
};

/*
function onYouTubePlayerAPIReady() {
	jwhUtil.videoPlayer = new YT.Player('jwh-video-dialog', {
		height: '345',
		width: '560',
		videoId: '0DU_NYwxdtI',
		events: {
			'onReady': onPlayerReady
		}
	});
}

function onPlayerReady(event) {
	jwhUtil.videoLoaded = true;
	jwhUtil.videoPlayer.playVideo();
}
*/
$(document).ready(function() {
	if ($('#faqs').length) { 
		jwhUtil.initFAQ();	
	}
	jwhUtil.init();
});
