/**
 * @author			Kevin Thomas
 * @email			kevin.thomas@beamland.com
 * @version			1.0
 *
 * @history
 * 06.08.2010		kthomas		Initial Version
 * ...
 * 07.13.2010		kthomas		-debugged issue with clicked-based selected state sticking after a swipe-based image change
 * 								-added a check in the init for cached/already loaded images > if so, completed animation is called
 */
	
	var isColorBoxOpen = false;


	var isSmallFormat = false;
	
	var _isLoading = true;
	
	var _imageTween = 400;
	var _buttonTween = 200;
	var _swipeMin = 100;
	var _swipeMax = 200;
	var _timer;
	var _loadedHash = new Array();
	var _doLeftAnimation = false;
	var _isIPhone = (new RegExp( "iPhone", "i" )).test(
		navigator.userAgent
	);
	var _isIPad = (new RegExp( "iPad", "i" )).test(
		navigator.userAgent
	);
	
	/**
	 * initialize when everything is ready to go
	 */
	$(document).ready(function ()
	{
		updateImages();
		addGalleryListeners();
		updateLinks();
	});
	
	////////////////////////////////////////////////////////////
	// IMAGE GALLERY FUNCTIONALITY
	////////////////////////////////////////////////////////////
	
	this.addGalleryListeners = addGalleryListeners;
	function addGalleryListeners()
	{
		$('.thumbs ul li').each(function()
		{
			$(this)
			.mouseenter(function($evt)
			{
				__onImageButtonMouseOver($evt);
			})
			.click(function($evt)
			{
				__onImageButtonClick($evt);
			})
			.mouseleave(function($evt)
			{
				__onImageButtonMouseOut($evt);
			})
			.addClass('normal')
			.attr('id',__getIndexString($(this)))
			.prepend('<div class="buttonMask">')
			.children('a')
			.hide();
			$(this).children('.buttonMask')
			.click(function($evt){
				__onImageButtonClick($evt);
			})
			.mouseleave(function($evt)
			{
				__onImageButtonMouseOut($evt);
			});
		});
		
		$('.thumbs ul').each(function()
		{
			$(this).children('li:first').addClass('selected');
			var index = __getIndexString($(this).children('li:first'));
			_loadedHash[index] = $(this).children('li:first').children('a:first').attr('href');
		});
		
		$('.thumbs img').each(function(){

			$(this)
			.wrap('<div class="imageContainer">');
						
			if(_isIPad || _isIPhone)
			{
				$(this).bind('touchstart', function($evt){
					__onSwipeStart($evt);
					//return(false);
				})
			}
			
			$(this)
			.before('<div class="imageMask">')
			.load(function(){
				__onImageLoadComplete($(this));
			})
			
			if($(this)[0].complete)
			{
				__onImageLoadComplete($(this));
			}
		});
	}
	
	var __onImageLoadComplete = function($target)
	{
		$($target).css('margin-left', (_doLeftAnimation ? '-300px' : '300px'))
		.animate({marginLeft:'0px'}, _imageTween, function(){
//			$($target).unwrap('<div class="imageContainer">');
			if($($target).next('img').length > 0)
			{
				$($target).next('img').remove();
			}
			_isLoading = false;
		});
		var index = __getIndexString($($target).parent('.thumbs').children('ul li .selected:first'));
		
		if($($target).next('img').length > 0)
		{
			$($target).next('img').animate({
				'margin-left':(_doLeftAnimation ? '300px' : '-300px')
			}, _imageTween, function(){
				$(this).remove();
			})
		}
			
		if($($target).prev('.imageMask').length > 0)
		{
			$($target).prev('.imageMask')
			.animate({
				'margin-left':(_doLeftAnimation ? '300px' : '-300px')
			}, _imageTween, function(){
				$(this).remove();
			});
		}
		_doLeftAnimation = false;
	}
	
	var __onImageButtonMouseOver = function($evt)
	{
//		$($evt.target).addClass('hover');
		$($evt.target).children('.buttonMask').animate({
			'margin-top':'0px'
		}, _buttonTween);
	}
	
	var __onImageButtonClick = function($evt)
	{
		/* BUTTON SELECTION */
//		$($evt.target).removeClass('hover');
		var liTarget = ($($evt.target).hasClass('buttonMask')) ? $($evt.target).parent() : $evt.target;
		$(liTarget).children('.buttonMask').css('margin-top','20px');
		__onImageSelect(liTarget);
	}
	
	var __onImageButtonMouseOut = function($evt)
	{
//		$($evt.target).removeClass('hover');
		var liTarget = ($($evt.target).hasClass('buttonMask')) ? $($evt.target).parent() : $evt.target;
		$(liTarget).children('.buttonMask').animate({
			'margin-top':'20px'
		}, _buttonTween);
	}
	
	var __onImageSelect = function($target)
	{
		if($($target).hasClass('selected') == false && _isLoading == false)
		{
			_isLoading = true;
			$($target).siblings().each(function(){
				$(this)
				.removeClass('selected')
				.children('.buttonMask').css('margin-top','20px');
			})
			$($target).addClass('selected');
			/* IMAGE LOADING */
			var indexString = $($target).attr('id');
			if(_loadedHash[indexString] != undefined)
			{
				__displayLoadedImage($target);
			}
			else
			{
				__loadNewImage($target);
			}
		}
	}
	
	var __loadNewImage = function($target)
	{
//		_doLeftAnimation = false;
		var indexString = $($target).attr('id');
		_loadedHash[indexString] = $($target).children('a:first').attr('href');
		
		$($target).parent().parent().children('.imageContainer').children('img:first')
		.before('<div class="imageMask">')
		.prev('.imageMask:first')
		.css('margin-left',(_doLeftAnimation ? '300px' : '-300px'))
		.animate({
			'margin-left':'0px'
		}, _imageTween, function(){
			$(this).next('img').attr('src', $($target).children('a').first().attr('href'));
		});
	}
	
	var __displayLoadedImage = function($target)
	{
		var indexString = $($target).attr('id');
		var prevSrc = $($target).parent().parent().children('.imageContainer').children('img:first').attr('src');
		$($target).parent().parent().children('.imageContainer').children('img:first')
		.after('<img src="' + prevSrc + '" alt="temp">')
//		.wrap('<div class="imageContainer" style="background:url(' + prevSrc + ') no-repeat center center">')
		.css('margin-left', (_doLeftAnimation ? '-300px' : '300px'))
		.css('z-index','999')
		.attr('src', _loadedHash[indexString]);
	}
	
	////////////////////////////////////////////////////////////

	var __getIndexString = function($node)
	{
		return String($($node).parents('.work').children('h2:first').html()).replace(/\W/g, "") + '_' + $($node).children('a:first').html();
	}
	
	////////////////////////////////////////////////////////////
	// SWIPE HANDLING
	////////////////////////////////////////////////////////////
	
	var lastTouchX = 0;
	var distance = 0;
	var touchTarget;
	
	var __onSwipeStart = function($evt)
	{
		var touch = window.event.targetTouches[0];
		touchTarget = $(touch.target);
		$(touch.target).addClass('imageBorder');
		
		$(touch.target)
		.bind('touchend', function($evt){
			__onSwipeEnd();
		})
		.bind('touchmove', function($evt){
			__onSwipeMove($evt);
			//return(false);
		});
		lastTouchX = touch.pageX;
	}
	
	var __onSwipeMove = function($evt)
	{
		var touch = window.event.targetTouches[0];
		distance += Number(touch.pageX - lastTouchX);
		lastTouchX = touch.pageX;
		if(distance > _swipeMax || distance < 0-_swipeMax)
		{
			__onSwipeEnd();
		}
	}
	
	var __onSwipeEnd = function()
	{
		$(touchTarget).removeClass('imageBorder');
	
		$(touchTarget)
		.unbind('touchmove')
		.unbind('touchend');
		if(distance > _swipeMin)
		{
			// swipe right
			__prevImage(touchTarget);
		}
		else if(distance < 0-_swipeMin)
		{
			// swipe left
			__nextImage(touchTarget);
		}
		touchStartX = 0;
		distance = 0;
		touchTarget = null;
	}
	
	var __nextImage = function($target)
	{
//		logit('NEXT IMAGE');
		var current = $($target).parent().next('ul').children('li .selected');
		if($(current).next('li').length > 0)
		{
			__onImageSelect($(current).next('li'));
		}
	}

	var __prevImage = function($target)
	{
//		logit('PREV IMAGE');
		_doLeftAnimation = true;
		var current = $($target).parent().next('ul').children('li .selected');
		if($(current).prev('li').length > 0)
		{
			__onImageSelect($(current).prev('li'));
		}
	}

	////////////////////////////////////////////////////////////
	//
	// FLASH CALLBACKS
	//
	////////////////////////////////////////////////////////////
	
	
	
						
	isReady = function() 
	{
		return jsReady;
	}
					
	pageInit = function() {
		jsReady = true;
	}
	
	getBrowserLocation = function() {
		return window.location;
	}
	
	parentWidth = function() {
		return $(document).width();
	}
	
	parentHeight = function() {
		return $(document).height();
	}
	
	launchLayer = function(id) {
		isColorBoxOpen = true;
		$.fn.colorbox({href:'layer.php?id=' + id, innerWidth:"500", innerHeight:"200", iframe:true, scrolling:false, onClosed:onPopupClosed});
	}
	
	/**
	* Called when color box is closed
	*
	**/
	onPopupClosed = function(id)  {
	
		if(isColorBoxOpen)
		{
			if(getFlashMovie('flashContainer')) {
				getFlashMovie('flashContainer').onLayerCloseClicked();
			}
		}
		
		isColorBoxOpen = false;
	}
	
	/**
	* Flash calls this to close the color box
	*
	**/                    
	closeLayer = function(id) {
	
		var curOpenState = isColorBoxOpen;
		if(isColorBoxOpen) 
		{
			$.fn.colorbox.close();
		}
		isColorBoxOpen = false;  
		return curOpenState;
	} 
	
	/**
	* Grabs a reference to Flash container
	*
	**/                    
	getFlashMovie = function(movieName) 
	{
		if (navigator.appName.indexOf("Microsoft") != -1) 
		{             
			return window[movieName];         
		} 
		else 
		{             
			return document[movieName];         
		}     
	} 
		
		
	////////////////////////////////////////////////////////////
	//
	// MISCELLANEOUS
	//
	////////////////////////////////////////////////////////////
			
						
	loadedFlash = function(e) 
	{
		//alert("e.success = " + e.success +"\ne.id = "+ e.id +"\ne.ref = "+ e.ref);
		
		if(e.success == true) 
		{
			//ONLY LOAD MOUSEWHEEL JS IF WE HAVE FLASH
			$.getScript("_js/swfmacmousewheel2.js", function()
			{
				swfmacmousewheel.registerObject(attributes.id);
			});	
			
			//load JS for flash only
			$.getScript("_js/jquery.colorbox.js");
			//$.getScript("_js/jquery.swfaddress.js");
		}	
	}
		
		
	logit = function($text) 
	{
		if(window.console && window.console.firebug) 
		{
			console.log($text);
		}
	}
	
	updateLinks = function()
	{
		// Any element that has the class .clickable, watch for click and take user to first href's URL.
		$(".clickable").click(
			function () {
				$thisHref = $(this).find('a:first');
				document.location = $thisHref.attr('href');
			}
		);
	}
	
	updateImages = function()
	{
		//swap to large image if we are large
		var fadeTime = 500;
		if($(window).width() > 480)
		{
			$("#home li.clickable").each(function()
			{
				$(this).css('opacity','0');
				$(this).children('img').attr("src", $(this).children('a.large-link').attr("href"));
				$(this).animate({'opacity':'1'}, fadeTime);
				$(this).children('a.large-link').remove();
			});
		}
		else
		{
			$('#home a.large-link').remove();
		}
	}	
