/* 
	Author:  Brian Earwood
			 brian@brianearwood.com

*/



function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var myPattern = new RegExp(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/);
return pattern.test(emailAddress);
}


//-------------------------------
//   ROTATOR CLASS
//_______________________________

var Rotator = (function() {
	
	//TODO: add Rotator wait timer for slow connections.
	
	return function(images, node, animationType, name) {
		
		var _name = name || "blank";
		var _array = images;
		var _position = 0;
		
		var type = animationType;
		var slideSpeed = 800;
		var fadeSpeed = 2000;
		var isAnimating = false;
		var incomingImage = $('<img class="gallery-image" src="' + _array[_position] + '" alt="Wedding Image" />');
		
		// privileged methods
		this.next = function() {
			(!(++_position < _array.length)) && (_position = 0);
			
			incomingImage = $('<img class="gallery-image" src="' + _array[_position] + '" alt="Wedding Image" />');
			setup('');
			
			window.setTimeout(function() {
				photoContainer.removeClass('initial');
				photoContainer.addClass('final');
				
				
				// fallback to jQuery animation if no css transitions
				if(!Modernizr.csstransitions) {					
					// change opacity
					if(type === 'fade') {
						$('#photo-container.final .outgoing').css('opacity', '1').animate({opacity: 0}, fadeSpeed, function(e){onTransitionEnd();});
					}
					// change slide position
					else if(type === 'slide') {
						$('#photo-container.final .incoming').css('left', '100%').animate({left: 0}, slideSpeed, function(e){onTransitionEnd();});
						$('#photo-container.final .outgoing').css('left', '0').animate({left: '-100%'}, slideSpeed);
					}
				}
				isAnimating = true;
			}, 100);
			
			$('#container').trigger('complete');
		};
		
		this.prev = function() {
			(!(--_position > -1)) && (_position = _array.length - 1);
			
			incomingImage = $('<img class="gallery-image" src="' + _array[_position] + '" alt="Wedding Image" />');
			setup('reverse');
			
			window.setTimeout(function() {
				photoContainer.removeClass('initial reverse');
				photoContainer.addClass('final reverse');
				
				// fallback to jQuery animation if no css transitions
				if(!Modernizr.csstransitions) {					
					// change opacity
					if(type === 'fade') {
						$('#photo-container.final .outgoing').css('opacity', '1').animate({opacity: 0}, fadeSpeed, function(e){onTransitionEnd();});
					}
					// change slide position
					else if(type === 'slide') {
						$('#photo-container.final .incoming').css('left', '-100%').animate({left: 0}, slideSpeed, function(e){onTransitionEnd();});
						$('#photo-container.final .outgoing').css('left', '0').animate({left: '100%'}, slideSpeed);
					}
				}
				isAnimating = true;
			}, 100);
			
			$('#container').trigger('complete');
		};
		
		this.get_isAnimating = function() {
			return isAnimating;
		}
		this.get_images = function() {
			return _array;
		}
		this.getNext = function() {
			return incomingImage;
		}
		
		// private attributes
		var photoContainer = node || $('#photo-container');
		var outgoingImage = photoContainer.children(0);
		
		// private methods
		var onTransitionEnd = function(e) {	
			
			isAnimating = false;
			
			incomingImage.unbind('webkitTransitionEnd');
			incomingImage.unbind('transitionend');
			incomingImage.unbind('oTransitionEnd');
			
			photoContainer.removeClass('final reverse');
			
			// Remove old image
			outgoingImage.remove();
			
			// Remove temporary class name
			incomingImage.removeClass('incoming reverse');
			
			// reset outgoingImage to the loaded image
			outgoingImage = photoContainer.children(0);
		};
		
		var setup = function(direction) {
			
			incomingImage.bind('webkitTransitionEnd', onTransitionEnd);
			incomingImage.bind('transitionend', onTransitionEnd);
			incomingImage.bind('oTransitionEnd', onTransitionEnd);
			
			// Add classes for CSS transitions
			photoContainer.addClass('initial ' + direction);
			outgoingImage.addClass('outgoing');
			incomingImage.addClass('incoming');
			
			// Insert the new image into the DOM
			incomingImage.prependTo(photoContainer);			
		};
		
		var preloadImages = function(array) {
			var i = 0;
			for(var i in array) {
				var imgObj = new Image();
				
				if(i == 0) imgObj.onload = function(){
					this.className += 'gallery-image';
					$('#photo-container').append(this);
					outgoingImage = photoContainer.children(0);
				};
				
				imgObj.src = array[i];
			}
		};
		preloadImages(_array);
	};
})();


//-------------------------------
//   INFO BOX CLASS
//_______________________________

var RotatorInfoBox = (function() {
	
	
	return function(element) {
		
		// priviledged attr
		var _$element = element;
		var _infoBoxIn = false;
		var _position = 0;
		var _$venue = $('#infoBox > div:first-child > p');
		var _$photoLink = $('#infoBox > div:last-child a');
		
		var _venues, _links;
		
		// priviledged func
		this.hide = function() {
			_$element.animate({bottom : '-60px'}, 'fast');
			_infoBoxIn = false;
		}
		
		this.show = function() {
			if (!_infoBoxIn) {
				_$element.animate({bottom : '0px'}, 'fast');
				_infoBoxIn = true;
			}
		}
		
		this.setVenues = function(venues) {
			_position = 0;
			_venues = venues;
		}
		this.setLinks = function(links) {
			_position = 0;
			_links = links;
		}
		
		this.showFirst = function() {
			$('#infoBox > div:last-child a').replaceWith(_links[0]);
			$('#infoBox > div:first-child > p').replaceWith(_venues[0]);
		}
		
		this.next = function() {
			(!(++_position < _venues.length)) && (_position = 0);
			$('#infoBox > div:last-child a').replaceWith(_links[_position]);
			$('#infoBox > div:first-child > p').replaceWith(_venues[_position]);
		}
		
		this.prev = function() {
			(!(--_position > -1)) && (_position = _venues.length - 1);
			$('#infoBox > div:last-child a').replaceWith(_links[_position]);
			$('#infoBox > div:first-child > p').replaceWith(_venues[_position]);
		}
		
		this.resetView = function() {}}
	
})();


//-------------------------------
//   BUTTON CLASS
//_______________________________

var RotatorButton = (function() {
	
	return function(element, isForward) {
		
		var _$element = element;
		var _isForward = isForward;
		var _buttonIn = false;
		var _infoBox, _rotator;
		
		
		// gallery navigation button listeners get added:
		if (_$element && !_isForward) {
			_$element.click(function(e) {
				if(_rotator && _rotator.get_isAnimating() == false) {
					// previous image
					_rotator.prev();
					// previous infoBox
					_infoBox.prev();
				}
			});
		} else if (_$element && _isForward) {
			_$element.click(function(e) {
				if(_rotator && _rotator.get_isAnimating() == false) {
					// advance image
					_rotator.next();
					// advance infoBox
					_infoBox.next();
				}
			});
		}
			
		this.hide = function() {
			if (!_isForward) {
				_$element.animate({left : '-80px'}, 'fast');
				_buttonIn = false;
			} else if (_isForward) {
				_$element.animate({right : '-80px'}, 'fast');
				_buttonIn = false;
			}
		}
		
		this.show = function() {
			if (!_isForward && !_buttonIn) {
				_$element.animate({'left' : '10px'}, 'fast');
				_buttonIn = true;
			} else if (_isForward && !_buttonIn) {
				_$element.animate({'right' : '10px'}, 'fast');
				_buttonIn = true;
			}
		}
		
		this.setRotator = function(newRotator) {
			_rotator = newRotator;
		}
		this.setInfoBox = function(box) {
			_infoBox = box;
		}
	}
})();



//*******************************
//   GALLERY CONTROLLER
//
//*******************************

var GalleryControl = (function() {
	
	// return the constructor
	return function(element) {
		
		var _rotator;	
		var _timer;
		var _index = 0;
		
		// left nav node list
		var _$nav = element;
		var _onButton = false;
		var _onPhoto = false;
		var _onInfoBox = false;
		var _imageUrls;
		var _photoElements;
		
		var _photos, _venues, _links;
		
		//var $imageContainer;
		var _$infoContainer = $("<div class='info-container'></div>");
		var _$imageContainer = $("<div class='gallery-images'></div>");
		var $photoContainer = $('#photo-container');
		var $rotForward = $('#rotator .forward');
		var $rotBack = $('#rotator .back');
		var $infoBox = $('#infoBox');
		
		var $loaderImage = $('<img id="loader-image" src="/_images/gui/loader.gif" />');
		
		// create gallery buttons
		var _forwardBtn = new RotatorButton($rotForward, true);
		var _backBtn = new RotatorButton($rotBack, false);
		var _infoBox = new RotatorInfoBox($infoBox);// **** TODO: add info for info box here
		
		
		// init left nav click listener
		_$nav.click(function(e) {
			if(_rotator) {
				_rotator = null;
				_$infoContainer.remove();
			}
			
			_photos = [];
			_venues = [];
			_links = [];
			
			_imageUrls = [];
			_photoElements = [];
			$photoContainer.children().remove();
			
			$photoContainer.append($loaderImage);
			
			var _urlTitle = String(e.target.getAttribute('rel'));
			
			_$infoContainer.load("http://amymillerweddings.com/embeds/gallery-images ." + _urlTitle, function(e){
				_$infoContainer.find('.galleryPhoto').each(function(){_photos.push(this.src)});
				_$infoContainer.find('.galleryVenue').each(function(){_venues.push(this)});
				_$infoContainer.find('.galleryLink').each(function(){_links.push(this)});	
				
				_rotator = new Rotator(_photos, $photoContainer, 'slide', "first");
				
				_forwardBtn.setRotator(_rotator);
				_forwardBtn.setInfoBox(_infoBox);
				
				_backBtn.setRotator(_rotator);
				_backBtn.setInfoBox(_infoBox);
				
				_infoBox.resetView();
				_infoBox.setVenues(_venues);
				_infoBox.setLinks(_links);
				_infoBox.showFirst();	
			});
			
			$(this).addClass('active').siblings().removeClass('active');
			
			$('body').mousemove(function(e){				
				if(_onPhoto || _onInfoBox) {
					window.clearTimeout(_timer);
					
					if(_forwardBtn) _forwardBtn.show();
					if(_backBtn) _backBtn.show();
					if(_infoBox) _infoBox.show();
					
					_timer = window.setTimeout( function(){
						_forwardBtn.hide();
						_backBtn.hide();
						_infoBox.hide();
					}, 1000);
				}
				
				else if(_onButton) {
					window.clearTimeout(_timer);
					
					if(_forwardBtn) _forwardBtn.show();
					if(_backBtn) _backBtn.show();
					
					_timer = window.setTimeout( function(){_infoBox.hide();}, 1000);
				}
			});
			
			$('.button').mouseover(function(e){
				_onButton = true;
			});
			$('.button').mouseout(function(e){
				_onButton = false;
			});
			
			$('#photo-container').mouseover(function(e){
				_onPhoto = true;
			});
			$('#photo-container').mouseout(function(e){
				_onPhoto = false;
			});
			
			$('#infoBox').mouseover(function(e){
				_onInfoBox = true;
			});
			$('#infoBox').mouseout(function(e){
				_onInfoBox = false;
			});
		});
		
		this.getRotator = function() {
			return _rotator;
		}
		// constructor initialization code:
		_$nav.eq(0).trigger('click');		
	};
})();





$(document).ready(function(){
	
	//
	// Init for Comment Form
	//
	if(location.pathname.match(/\/blog\/entry\//)) {
		$('#name').focus(function(){$('label[for=name]').animate({'opacity':0}, 500);
		}).blur(function(){
			if($(this).val() == 0) {$('label[for=name]').animate({'opacity':1}, 500);
			}
		});
		$('#comment').focus(function(){$('label[for=comment]').animate({'opacity':0}, 500);
		}).blur(function(){
			if($(this).val() == 0) {$('label[for=comment]').animate({'opacity':1}, 500);
			}
		});
	}
	
	
	//
	// Contact form checkbox overlay
	//
	if($('body').hasClass('event')) {
		$('.event #content ul').masonry({ singleMode: true });
	}
	
	$('.contact form > div:last-child fieldset div').click(function(e){
		if($(this).children('span').hasClass('clicked')) {
			$(this).children('span').removeClass('clicked');
			$(this).children('input').removeAttr("checked");
			
		} else {
			$(this).children('span').addClass('clicked');
			$(this).children('input').attr({"checked":"checked"});
		}
	});
	
	$('.contact form > div:last-child fieldset div > label').click(function(e){e.preventDefault();});
	
	
	//
	// Homepage and Event page rotators init
	//
	if(location.pathname === "/dev/" || location.pathname === "/") {
		var _$container = $('<div></div>');
		var _$photoContainer = $('#photo-container');
		var _imageSrcs = [];
		_$container.load("http://amymillerweddings.com/embeds/rotator-home .homepagePhoto", function(){
			_$container.children().each(function(e){_imageSrcs.push(this.src);});
			var _rot = new Rotator(_imageSrcs, _$photoContainer, 'fade');
			window.setInterval(function(){_rot.next();}, 4000);
		});
	}
	else if(location.pathname === "/dev/main/weddings" || location.pathname === "/main/weddings") {
		var _$container = $('<div></div>');
		var _$photoContainer = $('#photo-container');
		var _imageSrcs = [];
		_$container.load("http://amymillerweddings.com/embeds/rotator-weddings .weddingsPhoto", function(){
			_$container.children().each(function(e){_imageSrcs.push(this.src);});
			var _rot = new Rotator(_imageSrcs, _$photoContainer, 'fade');
			window.setInterval(function(){_rot.next();}, 4000);
		});
	}
	else if(location.pathname === "/dev/main/corporate" || location.pathname === "/main/corporate") {
		var _$container = $('<div></div>');
		var _$photoContainer = $('#photo-container');
		var _imageSrcs = [];
		_$container.load("http://amymillerweddings.com/embeds/rotator-corporate .corporatePhoto", function(){
			_$container.children().each(function(e){_imageSrcs.push(this.src);});
			var _rot = new Rotator(_imageSrcs, _$photoContainer, 'fade');
			window.setInterval(function(){_rot.next();}, 4000);
		});
	}
	else if(location.pathname === "/dev/main/social" || location.pathname === "/main/social") {
		var _$container = $('<div></div>');
		var _$photoContainer = $('#photo-container');
		var _imageSrcs = [];
		_$container.load("http://amymillerweddings.com/embeds/rotator-social .socialPhoto", function(){
			_$container.children().each(function(e){_imageSrcs.push(this.src);});
			var _rot = new Rotator(_imageSrcs, _$photoContainer, 'fade');
			window.setInterval(function(){_rot.next();}, 4000);
		});
	}
	
	
	//
	// Call Gallery Navigation init
	//
	if(location.pathname === '/dev/main/gallery' || location.pathname === '/main/gallery') {
		var gallery;
		var $navItems = $('section[role=widget] li')
		gallery = new GalleryControl($navItems);
		
		$('#container').bind('complete', function(){
			console.log('event caught');
			$('#loader-image').remove();
		});
	};
	
	
	
	
	//
	// Contact Page init
	//
	if(location.pathname === '/dev/main/contact' || location.pathname === '/main/contact') {
		
		var validated = false;
		
		$("#confirmEmail").keyup(function(){
			var email = $("#email").val();
			var confirmEmail = $("#confirmEmail").val();
			
			if(email != 0)
			{
				if(isValidEmailAddress(email) && confirmEmail == email)
				{
			 		$(".validation-icon").removeClass('yes no');
					$(".validation-icon").addClass('yes');
					validated = true;
				} 
				else
				{
			 		$(".validation-icon").removeClass('yes no');
					$(".validation-icon").addClass('no');
					validate = false;
				}
			} 
			else
			{
				$(".validation-icon").removeClass('yes no');
				validated = false;
			}
		});
		
		$('.contact input[type=submit]').click(function(e){
			e.preventDefault();
			
			var _message = "Whoopsie, don't forget to complete the required fields!"
			var _message2 = "Whoopsie, check to see if your Email is entered correctly."
			var _$warning = $('#warning-message');
			
			var _$name = $('#theName').val();
			var _$email = $("#email").val();
			var _$confirmEmail = $("#confirmEmail").val();
			
			if(_$email == 0 || _$confirmEmail == 0 || _$name == 0) {
				_$warning.text(_message);
				_$warning.css('display', 'inline-block');
				window.setTimeout(function(){_$warning.css('display','none');}, 3000);
			}
			else if (isValidEmailAddress(_$email) && _$confirmEmail == _$email) {
				$(this).unbind('click');
				$(this).trigger('click');
			}
			else {
				_$warning.text(_message2);
				_$warning.css('display', 'inline-block');
				window.setTimeout(function(){_$warning.css('display','none');}, 3000);
			}
		});
	};
});










