jQuery(document).ready(function($){
	
/* Sports Select */
	if ( $('body').is('.sports') ) {
		$('#nav-sports ul li').hoverIntent(function() {
			$(this).addClass('hover');
			$(this).children("ul").slideDown('fast');
		}, function() {
			$(this).children("ul").slideUp('fast', function(){ $(this).parent().removeClass('hover'); });
		});
	}
	
/* COLORBOX */
	if (! $('body').is('.home') ) {
		$(".node .gallery").each(function(index, obj){
			$(obj).find("a").colorbox({rel:$(obj).attr("id"), maxWidth:"100%", maxHeight:"100%", opacity:.70});
		});
	}
	/** /$('.helmet_cam a').click(function(e){
		$(this).colorbox();
		e.preventDefault();
		return false;
	});/**/
	//$('.moisture_map a').colorbox({ open:true, width: "75%", height: "85%" });
	//$('a.colorbox').colorbox();
	$('#moisture_loop a.colorbox').click(function(){
		$(this).colorbox({opacity:.70, 
			'onComplete': function(){
				if (! $('#cboxLoadedContent .overlay-logo').length ) $('#cboxLoadedContent').append( $('#moisture_loop .overlay-logo').clone() );
				$('#cboxLoadedContent .overlay-logo').show();
			},
			'onClosed':function(){
				$('.overlay-logo').hide(); 
			} 
		});
	});
	$('a.colorboxExternal').colorbox({opacity:.70, width:"100%", maxWidth:'1060px', height:"95%", iframe:true});
	$('a.colorboxInstructions').colorbox({opacity:.70, width:"50%", inline:true, href:'#colorboxFullInstructions'});
	$('a.video, .helmet_cam a').colorbox({opacity:.70});// , .moisture_map a
	
	// If moisture map hashtag on Gravity page, open moisture map
	if ( $('body').is('.gravity-lab') ) {
		if ( window.location.hash ) {
			$(window.location.hash+' a').colorbox({opacity:.70, 
				'open':true, 
				'onComplete': function(){
					if (! $('#cboxLoadedContent .overlay-logo').length ) $('#cboxLoadedContent').append( $('#moisture_loop .overlay-logo').clone() );
					$('#cboxLoadedContent .overlay-logo').show();
				},
				'onClosed':function(){ 
					$('.overlay-logo').hide(); 
				} 
			});//.siblings('.overlay-logo').show();
		}
		
	}
	
		
/* UPLOAD PHOTO/VIDEO SELECTOR */
	$('div.upload .upload-2').hide();
	$('div.upload h4 a').click(function(e){
		e.preventDefault();
		switchPhotoVideoUploader($(this));
	});
	$('div.upload form .submit').hide();
	
	// Disable form submit after submit has started to keep from double submitting
	$('div.upload form').submit(function() {
		if ( $('input#title', this).val() == "" ) {
			alert("A title is required");
			return false;
		} else {
			$('input[type=submit]', this).attr('disabled', 'disabled').css("opacity", .25).after('<p class="submitted">Sending</p>');
			return true;
		}
	});
	
	/** /
	$('div.upload h4 a').click(function(){
		//$(this).toggle();
		$('div.upload ul ul').hide();
		$(this).parent().next().show();
		$('div.upload h4').removeClass('selected');
		$(this).parent().addClass('selected');
		$(this).blur();
		return false;
	});
	/** /
	$("input[type=file]").change(function(){
		$("img.aniup").show();
	});
	
    if ($('body').is('.upload')) {
		window.onbeforeunload = askConfirm;
	}
	function askConfirm() {
		if (needToConfirm) return "Navigating away from this page will cancel the upload process.";
	};
	/**/
	
/* CONTACT FORMS, first and last name functions */
	var firstBox = $("#first_name");
	var lastBox = $("#last_name");
	var firstName = firstBox.attr("value");
	var lastName = lastBox.attr("value");
	
	//firstBox.attr("value", firstName);
	//lastBox.attr("value", lastName);
	firstBox.focus(function() {
		boxFocus($(this), firstName);
	});
	firstBox.blur(function() {
		boxBlur($(this), firstName);
	});
	lastBox.focus(function() {
		boxFocus($(this), lastName);
	});
	lastBox.blur(function() {
		boxBlur($(this), lastName);
	});
	function boxFocus(object, defaultText){
		object.addClass("active");
		if(object.attr("value") == defaultText) object.attr("value", "");
	};
	function boxBlur(object, defaultText){
		object.removeClass("active");
		if(object.attr("value") == "") object.attr("value", defaultText);
	};
	
/* LOGIN / SIGNUP FOCUS */
	var filename = get_filename();
	//document.write(filename);
	if (filename == 'upload.html') {
		if (get('do') == 'login') {
			document.login.email.focus();
		} else if (get('do') == 'signup') {
			document.signup.email.focus();
		}
		if (get('type') == 'video') {
			$('div.upload .photo ul').hide();
			$('div.upload .video ul').show();
			$('div.upload .photo h4').removeClass('selected');
			$('div.upload .video h4').addClass('selected');
		}
	}
	function get_filename() {
		//var pathname = document.location.href;
		var filename = document.location.href;//pathname.substr(pathname.lastIndexOf("/")+1,pathname.length);
		var end = (!filename.indexOf("?")) ? filename.length : filename.indexOf("?");
		return filename.substring(filename.lastIndexOf("/")+1, end);
	}
	function get(varname) {
		var url = window.location.href;
		var url_parts = url.split("?");
		
		if (url_parts.length == 0)
			return "";
		
		var query_string = url_parts[1];
		var query_vars = query_string.split("&");
		
		var value = "";
		for (i=0; i<query_vars.length; i++) {
			var parts = query_vars[i].split("=");
			if (parts[0] == varname) {
				value = parts[1];
				break;
			}
		}
		
		value = unescape(value);
		value.replace(/\+/g," ");
		return value;
	}
	
/* Home page widget */
	if ( $('body').is('.home') ) {
		var closed = false;
		$('.widget').prepend('<li class="close"><a href="#" title="Close this area">close</a></li>').children('li.close').click(grabAnchor).hover(hoverAnchorOver, hoverAnchorOut).css('cursor', 'pointer');
		$('.widget li.close a').click(function(e){
			e.preventDefault();
			if ( closed ) {
				$('.widget').removeClass('widget-closed').children('.close').children('a').text('close');
				closed = false;
			} else {
				//$('.widget').css({'display': 'none'});
				$('.widget').addClass('widget-closed').children('.close').children('a').text('open');
				closed = true;
			}
			$(this).blur();
			return false;
		});
	}
	function grabAnchor(){
		window.location = $('a', this).attr('href');
	};
	function hoverAnchorOver() {
		$('a', this).addClass('hover');
	};
	function hoverAnchorOut() {
		$('a', this).removeClass('hover');
	};

/* Home page video background */
	if ( $('body').is('.home') && ! $('body').is('.mobile') ) {
		// 400x226 1.77
		var ratio = 1.77;
		$("#video").jPlayer({
			ready: function () {
				$(this).jPlayer("setMedia", {
					m4v: homeVideoM4v,
					ogv: homeVideoOgv
				}).jPlayer("play");
				var vid_size = get_video_dimensions();
				$(this).jPlayer("option", 'size', {width: vid_size['width'] +'px', height: vid_size['height'] +'px'})
			},
			ended: function (event) {
				$(this).jPlayer("play");
			},
			swfPath: homeUrl +"/inc",
			supplied: "m4v, ogv",
			fullScreen: false,
			size: {
				height: $(window).height() +'px',
				width: ($(window).height()*ratio) +'px',
				cssClass: "jp-video"
			}
		});
		/**/
		$(window).resize(function() {
			var vid_size = get_video_dimensions();
			$("#video").jPlayer("option", 'size', {width: vid_size['width'] +'px', height: vid_size['height'] +'px'})
		});
		/**/
	}
	function get_video_dimensions() {
		var output = new Array();
		
		var width = $("#video").width();
		var height = $("#video").height();
		var curr_ratio = width / height;
		var dest_ratio = $(window).width() / $(window).height();
		if ( curr_ratio <= dest_ratio ) {
			output['width'] = $(window).width();
			output['height'] = scale_to_width($(window).width(), width, height);
		} else {
			output['width'] = scale_to_height($(window).height(), width, height);
			output['height'] = $(window).height();
		}
		return output;
	};
	function scale_to_width(newwidth, curwidth, curheight) {
		var target = (curheight / curwidth) * newwidth;
		return Math.ceil(target);
	};
	function scale_to_height(newheight, curwidth, curheight) {
		var target = (curwidth / curheight) * newheight;
		return Math.ceil(target);
	};
	
});

/* Functions for external email system
--------------------------------------------------- */
function emailCheck(emailStr) {
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	if (user.match(userPat)==null) {
		alert("The username doesn't seem to be valid.");
		return false;
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
			return false;
			}
		}
		return true;
	}
	var domainArray=domain.match(domainPat);
	if (domainArray==null) {
		alert("The domain name doesn't seem to be valid.");
		return false;
	}
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if ((domArr[domArr.length-1] != "info") &&
		(domArr[domArr.length-1] != "name") &&
		(domArr[domArr.length-1] != "arpa") &&
		(domArr[domArr.length-1] != "coop") &&
		(domArr[domArr.length-1] != "aero")) {
			if (domArr[domArr.length-1].length<2 || 
				domArr[domArr.length-1].length>3) {
					alert("The address must end in a three-letter domain, or two letter country.");
					return false;
			}
	}
	if (len<2) {
	   var errStr="This address is missing a hostname!";
	   alert(errStr);
	   return false;
	}
	return true;
}
function UPTvalidateform(thisform) {
	if (thisform.val_1.value==""){	
		alert("Please enter a value for First Name");
		return(true);}if (thisform.val_2.value==""){	
		alert("Please enter a value for Last Name");
		return(true);}if (thisform.val_67974 && thisform.val_67974.value!=''){
		thisform.demographics.value += ',67974';
	}
	if (emailCheck(thisform.email.value)) {	
		alert('Thank you for signing up!');
		return false;
	} else {
		return true;
	}
}
	
function switchPhotoVideoUploader($object) {
	//$(this).toggle();
	var $parent = $object.parent();
	var $container = $parent.parent();
	var hide;
	var show;
	
	if (! $parent.is('.disabled') ) {
		$parent.addClass('selected');
		$parent.siblings('h4').removeClass('selected');
		$container.find('p.file-upload label span').text($object.text());
		
		if ( $parent.is('.video') ) {
			hide = '.upload-1';
			show = '.upload-2';
			$('input[name=categoryId]').attr('value', 7);
		} else {
			show = '.upload-1';
			hide = '.upload-2';
			$('input[name=helmetCam]').attr('checked', false);
			$('input[name=categoryId]').attr('value', 6);
		}
		$container.find(hide).hide();
		$container.find(show).show();
		
		$object.blur();
	}
	/** /
	if (! $parent.is('.disabled') ) {
		$parent.addClass('selected');
		$parent.siblings('h4').removeClass('selected');
		$container.find('p.file-upload label span').text($object.text());
		
		if ( $container.find('.upload-1').is(":visible") ) {
			hide = '.upload-1';
			show = '.upload-2';
			$('input[name=categoryId]').attr('value', 7);
		} else {
			show = '.upload-1';
			hide = '.upload-2';
			$('input[name=helmetCam]').attr('checked', false);
			$('input[name=categoryId]').attr('value', 6);
		}
		$container.find(hide).hide();
		$container.find(show).show();
		
		$object.blur();
	}
	/**/
};

function disablePhotoVideoUploader($object) {
	var $parent = $object.parent();
	$parent.addClass('disabled');
};

