/*	Author:		Daniel C. Richmond
	File:		validate.js
	Purpose:	form validation
*/

$(document).ready(
	function() {
		// on validated form submission...
		var myForm = $("form.validate");
		myForm.each(function() {
			$(this).submit(
				function submit() {
					//return false;
					// define fail counts and whether or not to validate non-required typed fields
					var fails	= 0;
					var picky	= $(this).hasClass("picky");
					//
					function matchesMatch() {
						// checks to see if all "match" classed items are identical
						// returns true/false
						var returner = true;
						var lastValue = "";
						$(this).find(".match").each(
							function () {
								if ($(this).val() != lastValue && lastValue != "") {
									returner = false;
								}
								lastValue = $(this).val();
							}
						)
						return returner;
					}
					//
					// for all items to be validated...
					$(this).find("input, textarea, select").each(
						function() {
							// define some basics
							var isSubmit	= ($(this).attr("type") == "submit");
							var match		= $(this).hasClass("match");
							var email		= $(this).hasClass("email");
							var zip			= $(this).hasClass("zip");
							var phone		= $(this).hasClass("phone");
							var req			= $(this).hasClass("req");
							var message 	= "";
							var myVal		= $(this).val();
							var warning		= false;
							//
							function makeAlert(msg, warning) {
								// creates the popup alert above the text boxes
								var _class = "alert";
								if (warning) {
									// if it's just a warning (in picky mode), also use this class
									// makes grey box rather than red
									_class += " warning";
								}
								// create html to return and inject
								var html = "";
								html += "<div class = \"" + _class + "\">";
								html += msg;
								html += "</div>";
								return html;
							}
							//
							function kill() {
								// removes element
								$(this).remove();
							}
										
							// if a user left a required field blank...
							if (req && myVal == "") {
								// create error message
								message = "This is a required field.";
							}
							
							// if the user entered something into an "email" field...
							if (email && myVal != "") {
								// this field should be an email
								// check for @ and .
								$regEx = /^.+?@.+?\./g;
								if(!myVal.match($regEx) || myVal == "you@domain.com") {
									// not a valid email address
									// if this field IS NOT required, set warning to TRUE
									req ? null : warning = true;
									// create message
									message = "Invalid email address.";
								}
							}						
							
							// if a user entered something into a "phone" field...
							if (phone && myVal != "") {
								// this field should only contain numbers, (), and -
								$regEx = /^([1]??)([-. ]??)([(]??[0-9]{3}[)]??)([-. ]??)([0-9]{3})([-. ]??)([0-9]{4})$/g;
								if(!myVal.match($regEx)) {
									// not a valid email address
									// if this field IS NOT required, set warning to TRUE
									req ? null : warning = true;
									// create message
									message = "Invalid phone number.";
								}
							}
							
							// if a user entered something into a "zip" field...
							if (zip && myVal != "") {
								// this field should only contain numbers, (), and -
								$regEx = /^\d{5}$/g;
								if(!myVal.match($regEx)) {
									// not a valid email address
									// if this field IS NOT required, set warning to TRUE
									req ? null : warning = true;
									// create message
									message = "Invalid zip code.";
								}
							}
							
							// if there are confirmation (should-be matching) fields AND the fields DO NOT match...
							if (match && !matchesMatch()) {
								// create message
								message = "Entries must match.";
							}
							
							// if message is defined...
							if (message != "" && !isSubmit) {
								// if the validator is picky or the field is required, increment main fail counter
								
								(picky || req) ? fails++ : null;
								// if an alert DIV exists...
								// console.log($(this));
								// console.log($(this).hasClass("mark"));
								if ($(this).hasClass("mark")) {
									$(this)
										.removeClass("valid")
										.addClass("mark-invalid");
									$(this).focus(function () {
										$(this)
											.removeClass("mark-invalid")
											.removeClass("valid");
									});
								} else {
									if ($(this).parent().find("div.alert").length) {
										// ... set its message to the new error message
										$(this).parent().find("div.alert").html(message);
									} else {
										// ... if not, create an alert DIV and make it slide into view
										$(this).parent().prepend(makeAlert(message, warning));
										$(this).parent().find("div.alert").slideDown(250);
									}
								}
							} else if (!isSubmit) {
								// ... if not, slide it out of view and remove it
								if($(this).hasClass("mark")) {
									$(this)
										.removeClass("mark-invalid")
										.addClass("valid");
								}
								$(this)
									.removeClass("mark-invalid")
									.parent().find("div.alert").slideUp(250, kill);
								
							}
						}
					)
					//return false;
					// if errors have been reported...
					if (fails) {
						// ... deny default form submission functionality
						return false;
					}
					// if we arrive here, all is well -- submit form
					return true;
				}
			)
		});
	}
);




/**
 * @author Cody
 * @author Brendan
 */
function dimInputs(inputs){
	/*
		inputs should be a multidimensional array, formatted like:
		inputs(	{id:"an_id", text:"some text"},
				{id:"another_id", text:"more text"});
		//
		this will loop through that array and assign blur and focus handlers to each specified input
	*/
	for(i in inputs){
		// if it exists on this page...
		if($(inputs[i].id).length > 0){
			$(inputs[i].id).val(inputs[i].text);
			// ... add the "active" class to the input box
			$(inputs[i].id).addClass("inactive");
			// assign the following focus event:
			$(inputs[i].id).focus(function() {
				// if the input's value upon focus matches the corresponding text then...
				if($(this).val() == inputs[i].text){
					// ... clear the text out and...
					$(this).val("");
					// ... remove the "inactive" class from the input
					$(this).removeClass("inactive");
				}
			});
			// assign the following blur event:
			$(inputs[i].id).blur(function() {
				// if the input's value upon blur is "" then...
				if($(this).val() == ""){
					// ... assign the corresponding text as the input box's value...
					$(this).val(inputs[i].text);
					// ... add the "active" class to the input boFx
					$(this).addClass("inactive");
				}
			});
		}
	}
}

function homepageTrailer(){
	$("#innerFlash")
		.fadeOut(1000, function() {
			$(this).remove();
			$("#flash")
				.animate(
					{
						height: "573px"
					},
					1000,
					"swing",
					embedTrailer
				);
		} );
}
function embedTrailer() {
	flashembed(
		"flash",
		{
			src: "flash/flowplayer-3.1.5.swf",
			wmode: "transparent"
		},
		{
		config: { 
			clip: {
				url: ( /*'/files/videos/trailer.f4v'*/'/files/videos/trailer.f4v' ),
				bufferLength:10
			},
			canvas: {backgroundColor: "#787878"},

			plugins: {
			   controls: {
			      progressGradient: 'medium',
			      durationColor: '#999999',
			      sliderGradient: 'none',
			      progressColor: '#000000',
			      bufferGradient: 'none',
			      sliderColor: '#949494',
			      tooltipTextColor: '#ffffff',
			      volumeSliderGradient: 'none',
			      tooltipColor: '#5F747C',
			      volumeSliderColor: '#000000',
			      buttonOverColor: '#ababab',
			      timeColor: '#ffffff',
			      buttonColor: '#737373',
			      timeBgColor: '#555555',
			      backgroundGradient: 'low',
			      borderRadius: '0px',
			      backgroundColor: '#000000',
			      bufferColor: '#787878',
			      height: 20,
			      opacity: 1.0
			   }
			} 
		}
	}); 
}

function initQuotes() {
	/*
	 * This function controls the homepage quote rotator.
	 * 
	 * Quote rotation speed adjusts according to quote length based on
	 * a somewhat handicapped average reading speed of 200 wpm
	 * (Wikipedia gives 250-300 wpm as the average range)
	 * delay = ( words / wpm * 60 * 1000 )
	 * 
	 * Requires #homepage-quotes.
	 */
	
	var wpm 			= 200;
	var quoteIndex 		= 0;
	var container 		= $( "#homepage-quotes" );
	var quotes;
	var curQuote;
	var timer;
	var delay;
	var toggleQuote		= function( opacity, onComplete ) {
		var show = opacity > 0; 
		
		if( show ) {
			curQuote
				.css( "left", "auto" );
		}
		
		curQuote.animate( {
			opacity: opacity
		}, show ? 500 : 1000, function() {
			if( !show ) {
				curQuote
					.css( "left", container.width() + "px" );
			}
			onComplete ? onComplete() : null;
		} );
	}
	var resetTimer		= function() {
		delay			= curQuote.text().split( " " ).length / wpm * 60 * 1000; 
		timer			= setTimeout( changeQuotes, delay )
	}
	var changeQuotes	= function() {
		toggleQuote( 0, revealQuote );
		curQuote		= quotes.eq( ++quoteIndex >= quotes.length ? quoteIndex = 0 : quoteIndex );
	}
	var revealQuote		 = function() {
		container
			.animate( {
				height: curQuote.height() + 3 + "px",	// 3px added to allow descenders
				opacity: 1
			}, 500, function() {
				toggleQuote( 1, resetTimer )
			} );
	}
	
	if( container.length ) {		// quote container verified... proceed
		// hide the container right off the bat so we don't see unstyledness
		quotes 			= $( "#homepage-quotes .homepage-quote" );	// define quotes
		curQuote 		= quotes.eq( quoteIndex );

		container
			.css( "height", "0px" )
			.animate( {
				opacity: 0
			}, 0 );
		
		quotes
			.css( "opacity", 0 )
			.css( "position", "absolute" )
			.css( "width", ( container.innerWidth() - parseInt( container.css( "padding-left" ) ) - parseInt( container.css( "padding-right") ) ) + "px" )
			.css( "left", container.width() + "px" );
		
		revealQuote();
	}
	
}

$(document).ready(function() {
	// initialize quote rotator
	initQuotes();
	
	// unfocus clicked links
	$("#content a").click(
		function(){
			this.blur();
		}
	)
	
	// open in new window
	$(".new_window").attr({ target: "_blank" });
	
	// setup nav
	function navigation(){
		$("#nav li").each(function(){
			$(this).hover(function(){
				$(this).addClass("hover");
			}, function(){
				$(this).removeClass("hover");
			})
		});
	}
	navigation();
	
	dimInputs([
		{id:"#email_signup input.email", text:"you@domain.com"}
	]);
	
    //AJAX SETUP
    $.ajaxSetup({
		global: false,
		type: "POST",
		dataType: "json"
	});	
    
    /* HOMEPAGE FLASH BANNER */
	if ($("#banner #flash").length >= 1) {
		$("#flash").html("<div id = \"innerFlash\">&nbsp;</div>");
		flashembed(
			"innerFlash", 
			{
				src: "flash/gallery.swf",
				version: [9],
				wmode: "transparent",
				width: 860,
				height: 247,
				onFail: function(){
					$("#innerFlash").remove();
				}
			}
		);
	}
	
	/* TWITTER LOADING ON SIDEBAR */
	function tzOffset() {
		var d = new Date();
		return d.getTimezoneOffset();
	}
	tzOffset();
	$.ajax({
		url: "ajax/getTwitters.php",
		data: "method=getPublicTimeline&tzoffset=" + tzOffset(),
		beforeSend: function(){
			$(".twitter-feed .loading").show();
		},
		success: function(json){
			var toAppend = "";
			if(json[0]['error']) {
				toAppend = "<p>" + json[0]['error'] + "</p>";
			} else {
				for(var i=0; i < json.length; i++){
					toAppend += "<p>" + json[i]['text'] + "<br class = \"hide\"/><span>" + json[i]['created_at'] + "</span></p>";
				}
			}
			$(".twitter-feed .loading").fadeOut(
				500,
				function(){
					$(this).remove();
				}
			);
			$("#tweet_jail")
				.html(toAppend)
				.slideDown(1000);
		}
	});	
	
	/* PHOTO GALLERY */
	if ($("#photo_gallery.thumbs").length >= 1) {
		$("#photo_gallery.thumbs a").overlay({
			target: '#gallery',
			expose: '#000000',
			onClose: function(){
				if($("#gallery #img").length > 0){
					$("#gallery #img").remove();
					$("#gallery").attr("style", '');
				}
			}			
		}).gallery({
			speed: 800
		});
	}
	
	
	
	/* VIDEO PORTION OF THE SITE */
	if($(".player").length >= 1){
		$("a.popup_video").overlay({
			expose: {
				color: '#000000',
				opacity: 0.5,
				closeSpeed: 1000
			},
			onLoad: function() {
				var _container = this.getOverlay().find("a.player");
				_container.flowplayer(0).load();
				if( _container.attr( "large" ) || _container.attr( "mobile" ) ) {
					_container
						.after( "<div class = \"download_container\" />" )
						.parent()
						.find( ".download_container" )
							.append( ( _container.attr( "large" ) ) ? ( "<a class = \"download_large\" href = \"download/" + _container.attr( "large" ) + "\"><span class = \"hide\">Download Large</span></a>" ) : "" )
							.append( ( _container.attr( "mobile" ) ) ? ( "<a class = \"download_mobile\" href = \"download/" + _container.attr( "mobile" ) + "\"><span class = \"hide\">Download Mobile</span></a>" ) : "" )
							.css( "visibility", "visible" )
							.end()
						.animate( { paddingBottom: _container.parent().find( ".download_container" ).css( "height" ) }, "slow" );
				}
			},
			onClose: function() {
				var _container = this.getOverlay();;
				_container.css( "padding-bottom", "0px" ).find( ".download_container" ).remove();
				$f().unload();
			}
		});
		$("a.player").flowplayer("flash/flowplayer-3.1.5.swf", {
			canvas: {backgroundColor: "#787878"},

			plugins: {
			   controls: {
				  progressGradient: 'medium',
				  durationColor: '#999999',
				  sliderGradient: 'none',
				  progressColor: '#000000',
				  bufferGradient: 'none',
				  sliderColor: '#949494',
				  tooltipTextColor: '#ffffff',
				  volumeSliderGradient: 'none',
				  tooltipColor: '#5F747C',
				  volumeSliderColor: '#000000',
				  buttonOverColor: '#ababab',
				  timeColor: '#ffffff',
				  buttonColor: '#737373',
				  timeBgColor: '#555555',
				  backgroundGradient: 'low',
				  borderRadius: '0px',
				  backgroundColor: '#000000',
				  bufferColor: '#787878',
				  height: 20,
				  opacity: 1.0
			   }
			}
		} ); 		
	}
});
