$(document).ready(function() {
	
	var domainAddress = 'http://www.barnescatmur.com';
	var content = $('#content');
	var pageContent = content.find('#pageContent');
	var overlay = $('#overlay');
	var pageIsShowing = false;
	var flatEntry = false;
	
	Shadowbox.init({
		skipSetup: true,
		overlayOpacity: 11
	});

	content.css({'top' : $(window).height(), 'display' : 'block' });
	
	$(window).resize(function() {
		if(content.hasClass('hide')) {
	  		content.css({'top' : $(window).height(), 'display' : 'block' });
		}
	});

	var currentURL = $(location).attr('href');
	if(currentURL.toString().indexOf(domainAddress+'/#') < 0 && currentURL != domainAddress+'/') {
		var navAttempt = currentURL.replace(domainAddress+'/','');
		if(navAttempt.length > 0) {
			flatEntry = true;
			window.location.href = domainAddress+'/#/'+navAttempt;
			flatEntry = false;
		}
	} else {
	
		$.address.change(function(address) {
			var url = domainAddress+address.path;
			if(address.path != '/') {
				if(content.hasClass('hide')) {
					loadContent(url, showPage());
				} else {
					updateContent(url);
				}
			} else if(content.hasClass('show')) {
				hidePage();
			}
		});
		
	}
	
	$('a').live('click', function(e) {
		var updateLink = true;
		var target = $(this).attr('target').toString();
		if(target == "_blank" || target == "_parent") {
			return true;
		} else if($(this).attr('rel').indexOf('shadowbox') >= 0) {
		} else if ($(this).hasClass('clearDefault')) {
			e.preventDefault();
		} else {
			var deepLink = $(this).attr('href').replace(domainAddress+'/','');
			$.address.value(deepLink);
		}
		return false;

	});
	
	$('#overlay').click(function(e) {
		hidePage();
		return false;
	});
	
	 var showPage = function() {
		overlay.fadeIn();
		var YPos = 15;
		var WPos = ($(window).height()/2)-(content.outerHeight()/2);
		if (WPos > 15) YPos = WPos; 
		content.animate({'top': YPos}, 1000, 'easeOutBack', function() {
			content.removeClass('hide');
			content.addClass('show');
			pageIsShowing = true;
			pageContent.fadeIn();
		});
		
		return false;
	}
	
	 var hidePage =  function() {
		
		var YPos = content.outerHeight()*-1;
		content.animate({'top' : YPos}, 1000, 'easeInBack', function() {
			content.css('top', $(window).height());
			content.removeClass('show');
			content.addClass('hide');
			pageIsShowing = false;
			overlay.fadeOut();
			pageContent.hide();
			pageContent.html('');
			$('.galleryContent').remove();
			
		});
		
		return false;
	}
	
	var loadContent = function(url, func) {
		pageContent.load(url + ' .copy', function() {
			if(func) func.call();
			checkForImages();
			checkForPlayer();
		}).error(function() {
			$.address.value('/');
		});
	}
	
	var updateContent = function(url) {
		//Fade in new content
		pageContent.fadeOut(200,function() { pageContent.html('');});
		pageContent.load(url + ' .copy', function() { 
			pageContent.fadeIn();
			checkForImages();
			checkForPlayer();
		}).error(function() {
			$.address.value('/');
		});
	}

	
	/* Mouse Wheel Variables */
	
	var wheelRate = 100; //How many pixels per wheel click?
	var wheelSpeed = 500; //Wheel Rate Velocity.
	var scrollHitCountUp = 0;
	var scrollHitCountDown = 0;
	
	/* Gallery Virtical Scroll */
	
	var vScrollSpeed = 25; //How many pixels per second?
	
	$('.up').live('mouseover mouseout', function(e) {
		var listView = $(this).parent().find('.pageScroll');
		if(e.type == 'mouseover') {
			handleArrows($(this).parent(), 'show');
			scroller(listView, 'd');
		} else {
			listView.stop(true, false);
			handleArrows($(this).parent(), 'hide');
		}
	});
	
	$('.down').live('mouseover mouseout', function(e) {
		var listView = $(this).parent().find('.pageScroll');
		if(e.type == 'mouseover') {
			handleArrows($(this).parent(), 'show');
			scroller(listView, 'u');
		} else {
			listView.stop(true, false);
			handleArrows($(this).parent(), 'hide');
		}
	});
	
	$('.pageScroll').live('mouseover mouseout', function(e) {
		if(e.type == 'mouseover') {
			$(this).bind('mousewheel', function(event, delta) {
				var holder = $(this).parent();
				if(delta > 0) gMouseWheelUp(holder, $(this));
				else gMouseWheelDown(holder, $(this));
			});
		} else {
			$(this).unbind('mousewheel');
		}
	});
	
	var gMouseWheelUp = function(holder, obj) {
		scrollHitCountUp +=1;
		scrollHitCountDown = 0;
		handleArrows(holder, 'show');
		gScroll(obj, 'd');
			
	}
	
	var gMouseWheelDown = function(holder, obj) {
		scrollHitCountDown +=1;
		scrollHitCountUp = 0;
		handleArrows(holder, 'show');
		gScroll(obj, 'u');		
	}
	
	var scroller = function(obj, dir) {
	
		var offset = obj.css('top');
		offset = parseInt(offset.substring(0, offset.length - 2));
		var cap = obj.outerHeight(true)-obj.parent().height();
		var duration = (cap/vScrollSpeed)*100;
		var upwardRatio = (cap+offset)/cap;
		var downwardRatio = (-1*offset)/cap;		
	
		if(dir == 'u') {
			var time = duration*upwardRatio;
			
			obj.animate({ top:"-"+cap+"px"}, time, "linear", function() {
			});
		} else {
			var time = duration*downwardRatio;
			obj.animate({ top:"0px"}, time, "linear", function() {
			});	
		}
		
	}
	
	var gScroll = function(obj, dir) {
	
		var offset = obj.css('top');
		offset = parseInt(offset.substring(0, offset.length - 2));
		var cap = obj.outerHeight(true)-obj.parent().height();
	
		if(dir == 'u') {
			var distance = wheelRate*scrollHitCountDown;
			if((offset*-1)+distance>cap) distance = cap;
			else distance = (offset*-1)+distance;
			obj.stop(true, false);
			obj.animate({ top:"-"+distance+"px"}, wheelSpeed, "linear", function() {
				scrollHitCountDown = 0;
				handleArrows(obj.parent(), 'hide');
			});
		} else {
			var distance = wheelRate*scrollHitCountUp;
			if((offset*-1)-distance<0) distance = 0;
			else distance = (offset*-1)-distance;
			obj.stop(true, false);
			obj.animate({ top:"-"+distance+"px"}, wheelSpeed, "linear", function() {
				scrollHitCountUp = 0;
				handleArrows(obj.parent(), 'hide');
			});	
		}
	}
	
	var handleArrows = function(parentObj, setting) {
		var up = parentObj.find('.up');
		var down = parentObj.find('.down');
		
		if(setting == 'hide') {
			up.fadeTo(100, .01);
			down.fadeTo(100, .01);
		} else {
			up.fadeTo(100, 1);
			down.fadeTo(100, 1);
		}
	}
	
	/* How We Do it Scrolling Nav */
	
	var hwdiScrollSpeed = 25; //How many pixels per second?
	
	$('.lefthand').live('mouseover mouseout', function(e) {
		var holder = $(this).parent().find('ul.t');
		checkWhoNamesWidth(holder);
		if(e.type == 'mouseover') {
			handlehands($(this).parent(), 'show');
			hScroll(holder, 'r');
		} else {
			holder.stop(true, false);
			handlehands($(this).parent(), 'hide');
		}
	});
	
	$('.righthand').live('mouseover mouseout', function(e) {
		var holder = $(this).parent().find('ul.t');
		checkWhoNamesWidth(holder);
		if(e.type == 'mouseover') {
			handlehands($(this).parent(), 'show');
			hScroll(holder, 'l');
		} else {
			holder.stop(true, false);
			handlehands($(this).parent(), 'hide');			
		}
	});
	
	
	$('ul.t').live('mouseover mouseout', function(e) {
		if(e.type == 'mouseover') {
			
			checkWhoNamesWidth($(this));
			$(this).bind('mousewheel', function(event, delta) {
				var holder = $(this).parent();
				if(delta > 0) mouseWheelUp(holder, $(this));
				else mouseWheelDown(holder, $(this));
			});
		} else {
			$(this).unbind('mousewheel');
		}
	});
	
	var mouseWheelUp = function(holder, obj) {
		scrollHitCountUp +=1;
		scrollHitCountDown = 0;
		handlehands(holder, 'show');
		wScroll(obj, 'r');
			
	}
	
	var mouseWheelDown = function(holder, obj) {
		scrollHitCountDown +=1;
		scrollHitCountUp = 0;
		handlehands(holder, 'show');
		wScroll(obj, 'l');		
	}
	
	var hScroll = function(obj, dir) {
	
		var offset = obj.css('left');
		offset = parseInt(offset.substring(0, offset.length - 2));
		var cap = obj.outerWidth()-obj.parent().width();
		var duration = (cap/hwdiScrollSpeed)*100;
		var LeftRatio = (cap+offset)/cap;
		var RightRatio = (-1*offset)/cap;		
	
		if(dir == 'l') {
			var time = duration*LeftRatio;
			obj.animate({ left:"-"+cap+"px"}, time, "linear", function() {
			});
		} else {
			var time = duration*RightRatio;
			obj.animate({ left:"0px"}, time, "linear", function() {
			});	
		}
	}
	
	var wScroll = function(obj, dir) {
	
		var offset = obj.css('left');
		offset = parseInt(offset.substring(0, offset.length - 2));
		var cap = obj.outerWidth()-obj.parent().width();
	
		if(dir == 'l') {
			var distance = wheelRate*scrollHitCountDown;
			if((offset*-1)+distance>cap) distance = cap;
			else distance = (offset*-1)+distance;
			obj.stop(true, false);
			obj.animate({ left:"-"+distance+"px"}, wheelSpeed, "linear", function() {
				scrollHitCountDown = 0;
				handlehands(obj.parent(), 'hide');
			});
		} else {
			var distance = wheelRate*scrollHitCountUp;
			if((offset*-1)-distance<0) distance = 0;
			else distance = (offset*-1)-distance;
			obj.stop(true, false);
			obj.animate({ left:"-"+distance+"px"}, wheelSpeed, "linear", function() {
				scrollHitCountUp = 0;
				handlehands(obj.parent(), 'hide');
			});	
		}
	}
	
	var handlehands = function(parentObj, setting) {
		var left = parentObj.find('.lefthand');
		var right = parentObj.find('.righthand');
		
		if(setting == 'hide') {
			left.fadeTo(200, .01);
			right.fadeTo(200, .01);
		} else {
			left.fadeTo(200, 1);
			right.fadeTo(200, 1);
		}
	}
	
	var checkWhoNamesWidth = function(holder) {
		if(holder.width() >= 4000) {
			var contents = 	holder.find('li');
			var totalWidth = 0;
			$.each(contents, function() {
				totalWidth+=$(this).outerWidth(true);
			});
			holder.width(totalWidth);
		}
	}
	
	/* Gallery Carosel Nav */
	
	var hScrollSpeed = 25; //How many pixels per second?
	
	$('.pLeft').live('mouseover mouseout', function(e) {
		var holder = $(this).parent().find('ul');
		checkHolderWidth(holder);
		if(e.type == 'mouseover') {
			carosel(holder, 'r');
		} else {
			holder.stop(true, false);
		}
	});
	
	$('.pRight').live('mouseover mouseout', function(e) {
		var holder = $(this).parent().find('ul');
		checkHolderWidth(holder);
		if(e.type == 'mouseover') {
			carosel(holder, 'l');
		} else {
			holder.stop(true, false);			
		}
	});
	
	var carosel = function(obj, dir) {
	
		var offset = obj.css('left');
		offset = parseInt(offset.substring(0, offset.length - 2));
		var cap = obj.outerWidth()-obj.parent().width();
		var duration = (cap/hScrollSpeed)*100;
		var LeftRatio = (cap+offset)/cap;
		var RightRatio = (-1*offset)/cap;		
	
		if(dir == 'l') {
			var time = duration*LeftRatio;
			
			obj.animate({ left:"-"+cap+"px"}, time, "linear", function() {
			});
		} else {
			var time = duration*RightRatio;
			obj.animate({ left:"0px"}, time, "linear", function() {
			});	
		}
		
	}
	
	var checkHolderWidth = function(holder) {
		if(holder.width() >= 4000) {
			var contents = 	$('.printholder .printimages ul').find('li');
			var totalWidth = 0;
			$.each(contents, function() {
				totalWidth+=$(this).outerWidth(true);
			});
			holder.width(totalWidth);
		}
	}
	
	$('.printimages li a').live('click', function() {
		return false;
	});
	
	/* Animated Hand */
	
	$('.hwdi-list ul li a').live('mouseover mouseout', function(e) {
		var handDiv = $('.hwdi-list ul');
		if(e.type == 'mouseover') {
			var vPos = $(this).position();
			// vPos = parseInt(vPos.top-222)+"px";
			vPos = parseInt(vPos.top-212)+"px";
			
			//handDiv.css({backgroundPosition: '52px '+vPos});
			handDiv.stop(true, false);
			handDiv.animate({backgroundPosition: '52px '+vPos}, 200);
		} else {
			//handDiv.css({backgroundPosition: '32px 24px'});
			handDiv.animate({backgroundPosition: '32px 78px'}, 1000);
		}
	});
	
	/* Gallery Display */
	
	var a = new Array();
	var i;
	var l;
	
	function checkForImages() {
	
		var images = new Array();
	
		$.each($('a'), function() {
			if($(this).attr('rel').indexOf('shadowbox') >= 0) {
				images.push($(this).attr('href'));
				$(this).click(function() {
					i = $.inArray($(this).attr('href'), images);
					showGallery();
				});
			}
		});
		
		a = images;
		l = a.length;
		
	}
	
	function showGallery() {
		var top = $('#container #content').css('top');
		$('#container #content').append('<div class="galleryContent"><a class="mainback" href="http://barnescatmur.com/new/"></a><p style="text-decoration: underline; cursor: pointer" class="leaveGallery">Back to Campaign</p><div class="dynamicGallery"><div class="previous clearDefault"></div><div class="galleryImage"></div><div class="next clearDefault"></div></div>');
		$('.galleryContent').fadeIn();
		manageGalleryHands();
		setupImage(a[i]);
				
	}
	
	function manageGalleryHands() {
		if(i>0) {
			$('.galleryContent .previous').fadeIn();	
		} else {
			$('.galleryContent .previous').fadeOut();
		}
		
		if(i<l-1) {
			$('.galleryContent .next').fadeIn();	
		} else {
			$('.galleryContent .next').fadeOut();
		}
	}
	
	function setupImage(src) {
		if($('.galleryContent .galleryImage img').length > 0) {
			$('.galleryContent .galleryImage img').fadeOut(function() {
					loadImage(src);
			});
		}  else {
			loadImage(src);
		}
	}
	
	function loadImage(src) {
		var img = new Image();
		$(img).load(function() {
			$(this).hide();
			$('.galleryContent .galleryImage').html(this);
			imgEl = $('.galleryContent .galleryImage img');
			var imageTop = ($('.galleryContent').outerHeight()-imgEl.outerHeight())/2;
			var imageLeft = ($('.galleryContent').outerWidth()-imgEl.outerWidth())/2;
			$('.galleryContent .galleryImage').css({'top':imageTop+'px', 'left':imageLeft+'px'});
			$(this).fadeIn();
		}).error(function() {
			alert('image failed to load');
		}).attr('src', src);
		
	}
	
	$('.galleryContent .previous').live('click', function(e) {
			e.preventDefault;
			if(i>0) {
				i = i-1;
				manageGalleryHands();
				setupImage(a[i]);
			}
		});
	
	$('.galleryContent .next').live('click', function(e) {
		e.preventDefault;
		if(i<l-1) {
			i = i+1;
			manageGalleryHands();
			setupImage(a[i]);
		}
	});
	
	$('.galleryContent .leaveGallery').live('click', function(e) {
		e.preventDefault;
		$('.galleryContent').fadeOut(function() {  	
			$('.galleryContent').remove();
		});	
	});
	
	/**  JW Player
	 * Setup up JW player if needed on page, #mediaplayer.
	 * 
	 * Preview image filenames must be the same presuffix - e.g. file1.mp4 requires file1.jpg.
	 * Images are loaded in to WP - see the Gallery 'Video Frames'
	 * 
	 */
	
	function checkForPlayer() {
		if($('#mediaplayer').length >0) {
			var file = $('.vidnav a.playlist:eq(0)').attr('href').replace(domainAddress+'/','');
			var preview_image = domainAddress+'/wp-content/gallery/videoframes/'+file+'.jpg';
			jwplayer('mediaplayer').setup({
				flashplayer: domainAddress+'/jwplayer/player.swf',
				id: 'playerID',
				width: '372',
				height: '207',
				// controlbar: 'none',
				wmode: 'opaque',
				image: preview_image,
				file: domainAddress+'/videos/'+file+'.mp4',
			 })
		}
	}
	
	$('a.playlist').live('click', function() {
		var file = $(this).attr('href').replace(domainAddress+'/','');
		var preview_image = domainAddress+'/wp-content/gallery/videoframes/'+file+'.jpg';
		jwplayer('mediaplayer').setup({
				flashplayer: domainAddress+'/jwplayer/player.swf',
				id: 'playerID',
				width: '372',
				height: '207',
				// controlbar: 'none',
				wmode: 'opaque',
				image: preview_image,
				file: domainAddress+'/videos/'+file+'.mp4',
			 })
	});
	
	
	/* contact map jiggle */
	
	var hovering = false;
	
	$('.details').live('mouseover mouseout', function(e) {
		if(e.type == 'mouseover') {
			hovering = true;
			moveMapPointersIn();
		} else {
			hovering = false;
		}
	});
	
	function moveMapPointersIn() {
		if(hovering) {
			$('.lochand').animate({'top': '280px', 'left': '437px'}, 100, 'linear', function() {
				moreMapPointersOut();
			});
			$('.fphand').animate({'top': '400px', 'left': '670px'}, 100, 'linear');
		}
	}
	
	function moreMapPointersOut() {
			$('.lochand').animate({'top': '270px', 'left': '427px'}, 100, 'linear', function() {
				moveMapPointersIn();
			});
			$('.fphand').animate({'top': '406px', 'left': '675px'}, 100, 'linear');
	}
	
	/* Random Lights */
		
	setTimeout('flickALight()', 1000);

	
});

//Outside of the document.ready() - Random Lights cont.

function flickALight() {
	var rand_num = Math.floor(Math.random()*$('#menu-main-menu li a').size());
	var room = $('#menu-main-menu li a').eq(rand_num);
	room.addClass('hover');
	var flick = Math.floor(Math.random()*2000);
	setTimeout('clearHover()', flick);
	resetTimer();
}

function clearHover() {
	$('#menu-main-menu li a.hover').removeClass('hover');
}

function resetTimer() {
	var time = Math.floor(Math.random()*10000);
	setTimeout('flickALight()', time);
}

