/* RUN THESE EVENTS WHEN THE PAGE IS READY FOR IT */
/* ********************************************** */

window.addEvent('domready', function(){
	
	
	/* GLOBAL VARIABLES */
	
	var scroller; 						// stores interval for scroller
	var imagePrefix = 'http://d2z57atfnbxql8.cloudfront.net/www/static/_img/home/';  // prefix for all image URLs
	var slider_fullWidth = 3547;		// full width of all the images
	var inAction = false;				// prevents multiple firings of move
	
	var scrl_winSize = window.getSize().x;
	var scrl_ipadAnchor = $('bounding').getSize().x/2 - 190;
	
	// setting transition duration for all images
	$$('img').set('tween', { duration: 1000 });
	
	/* LOADS IN THE IMAGES */
	
	var images = [
		{src: imagePrefix + '01.jpg', loaded: false },
		{src: imagePrefix + '03.jpg', loaded: false },
		{src: imagePrefix + '02.jpg', loaded: false },
		{src: imagePrefix + '04.jpg', loaded: false }
	];
	
	images.each(function(item) {
		var image = new Element('img', { 
			src: item.src, 
			events: {
				'load': function(){
					item.loaded = true;
					item.imageObject = image;
					setUpImage(image);
				}
			}
		});
	});
	
	/* SETS UP THE INITIAL IMAGE LOADS */
	/* ******************************************* */

	function setUpImage(image){
		
		var doneLoading = true;
		for (var i = 0, c = images.length; i < c; i++)
			if (!images[i].loaded)
				doneLoading = false;

		if (!doneLoading) return;

		var currentOffset = 0;

		images.each(function(item, index){
			item.imageObject.style.left = currentOffset + 'px';
			currentOffset += item.imageObject.width;
			
			//AX:Hide these images from screen readers/VoiceOver
			item.imageObject.setAttribute("role","presentation");
			
			$('shift-frame').adopt(item.imageObject);
		});
	}


	// This catch-all helper method for scroll only runs if the parameters
	// are not the same as the last mouse action (to prevent multiple firings
	// within the same hotspots). It takes in the direction you want the image
	// to move, the interval between refreshes, and how far it should travel
	// with each refresh. This method simply sets up intervals, that's all.
	
	function defaultScroll( direction ) {
		
		clearInterval(scroller);
		if ( direction == 'left' )
			scroller = setInterval(function(){ goLeft(1) }, 15);
		else if ( direction == 'right' )
			scroller = setInterval(function(){ goRight(1) }, 15);
		
	} defaultScroll('right');
	
	
	
	// This function is intended for use when you know your final destination.
	// It calculates all the necessary positioning and intervals by taking in
	// how long you want the animation to take place, which direction you want
	// it to travel, and knowing where your final destination is.
	
	function targetedScroll( direction, items, distance, duration ) {
		
		var interval = []
		
		clearInterval(scroller);
		var start = (new Date).getTime(), 
			finish = start + duration;
		
		items.each(function(item, i){
			item.startPosition = parseInt(item.style.left);
			interval[i] = setInterval(function(){
				var time = (new Date).getTime(),
					pos = easeInCirc( direction, time-start, item.startPosition, distance, duration);
				item.style.left = pos + 'px';
				positionMonitor(item, direction);
				if ( time > finish-1300 ) {
					// -1300 accounts for jitteryness at end of scroll
					inAction = false;
					if ( direction == 'left') defaultScroll('left');
						else defaultScroll('right');
					clearInterval(interval[i]);
				}
			}, 10);
		});
	}
	
	// This helper method moves images back and forth when they cross the fold of
	// the page, by monitoring its position. Happens EVERY 10ms.
	// TAKES IN: AN OBJECT and A DIRECTION (STRING)
	// RETURNS: NOTHING
	
	function positionMonitor(item, direction){
		
		/* TRAVELING RIGHT */
		if (parseInt(item.style.left) < -item.width - 500 && direction == 'right') {
			var farthest = farthestItem(),
				newPosition = parseInt(farthest.style.left) + farthest.width;
			item.style.left = newPosition + 'px';
			item.startPosition += slider_fullWidth; //width of all images
		}
		
		/* TRAVELING LEFT */
		
		if ( direction == 'left' ){
			var frontmost = frontmostPosition();
			var farthest = farthestItem();
			if (parseInt(item.style.left) > scrl_winSize && item == farthest){
				item.style.left = parseInt(frontmost.style.left) - farthestItem.width + 'px';
				item.startPosition -= slider_fullWidth;
			}
		}

	}
	

	// EQUATIONS FOR EASING THE ANIMATION
	// direction (dir), time (t), begin (b), distance (c), duration (d)
	
	function easeInOutQuintic(dir, t, b, c, d){
		var result;
		if ((t/=d/2) < 1) result = c/2*t*t*t*t*t + b;
		result = c/2*((t-=2)*t*t*t*t + 2) + b;
		result = (dir == 'right') ? -result : result;
		return result;
	}
	function easeInCirc(dir, t, b, c, d){
		var result
		if ( dir == 'right' ) c = -c;
		result = c*((t=t/d-1)*t*t*t*t + 1) + b;
		return result;
	}
	
	
	/* MAKES THE FRAME.. GO RIGHT. */
	// This method first moves all the images together, but also checks
	// that once an image has fully left the screen (indicated by when its
	// left position value is the same as its negative width) it calculates an end
	// position and throws it to the end of the set of images.
	
	// IMPORTANT TO NOTE: NEITHER GOLEFT() NOR GORIGHT() ARE ACTUALLY CHANGING THE DOM
	// ORDERS OF THE IMAGES. They are simply changing the CSS Left position of the
	// elements, so you CANNOT simply do a "getFirst()" or "getLast()" to get the items
	// in the lead. You will need to calculate the fronmost and farthest elements to
	// select them. A pain, yes, but it was harder to scroll the DIV infinitely.
	
	function goRight(distance) {
		
		$$('#shift-frame img').each(function(item){
			
			/* SIMPLE MOVEMENT */
			item.style.left = parseInt(item.style.left) - distance + 'px';
			if (parseInt(item.style.left) < -item.width) {
				var farthest = farthestItem(),
					newPosition = parseInt(farthest.style.left) + farthest.width;
				item.style.left = newPosition + 'px';
			}
			
			/* MONITORING FOR IPAD CROSS-SECTION */
			var itemStart = parseInt(item.style.left),
				itemEnd = itemStart + item.width;
			if ( scrl_ipadAnchor > itemStart && scrl_ipadAnchor < itemEnd ){
				checkpointer( item, 'right', [20, 320, 620] );
			}
			
		});
	}
	
	/* HANDLES THE FRAME GOING LEFT */
	// Starts by calculating the frontmost element via the frontmostPosition() helper method.
	// Then moves all the elements in unison to scroll. If the left position is the FARTHEST
	// recorded position so far, log it as the FARTHEST item, and record its width as well.
	// These are used in the second part:

	// Run a THIRD iteration through the images to see if the element has rolled off the page.
	// If it HAS and it's the furthest item out, then set its leftmost position to the 
	// position of the frontmost element MINUS the width of the farthest element.
	
	// IMPORTANT: THIS FUNCTION IS NOT IN USE BECAUSE THERE IS NO NEED RIGHT NOW FOR A DEFAULT
	// LEFT SCROLL. IT'S LEFT IN THE CODE FOR IN CASE WE EVER DECIDE TO USE IT.
	
	function goLeft(distance){
		
		var frontmost = parseInt(frontmostPosition().style.left),
			farthestItem,
			width = 0, farthest = 0;
		
		$$('#shift-frame img').each(function(item){
			// next line just simply moves the images first.
			item.style.left = parseInt(item.style.left) + distance + 'px'
			if ( parseInt(item.style.left) > farthest ){
				farthest = parseInt(item.style.left);
				farthestItem = item;
				width = item.width;
			}
			
			/* MONITORING FOR IPAD CROSS-SECTION */
			var itemStart = parseInt(item.style.left),
				itemEnd = itemStart + item.width;
			if ( scrl_ipadAnchor > itemStart && scrl_ipadAnchor < itemEnd ){
				checkpointer( item, 'left', [240, 480, 810] );
			}
		})
		
		$$('#shift-frame img').each(function(item){
			if( parseInt(item.style.left) > scrl_winSize && item == farthestItem )
				item.style.left = frontmost - width + 'px'
		})
	
	}

	
	
	
	/* POSITION TRACKING & ELEMENT HUNTING */
	/* ******************************************* */
	
	// This method figures out if an image is being intersected by the browser window.
	// It first calculates the position of the iPad, and sets a temporary variable that
	// stores the shortest distance between the left position of an image and the iPad.
	// IF the left position of an image is greater than the iPad anchor, then this is a
	// good target (this is only used for right scroll). If the distance between the
	// image's left position and the iPad is shorter than the one stored in 
	// "shortestDistance", then this is our target! RETURNS: AN OBJECT
	
	function intersects(items, position){
		
		var ipadAnchor = scrl_winSize/2 - 180;
		var shortestDistance = 6000;
		var nextItem;
		
		for ( i=0; i < items.length; i++ ) {
			var item = items[i];
			if (parseInt(item.style.left) > scrl_ipadAnchor){
				var distance = parseInt(item.style.left)-scrl_ipadAnchor;
				if ( distance < shortestDistance ){
					shortestDistance = distance;
					nextItem = item;
				}
			}
		}
		return nextItem;
	}
	
	// This is a more generalized version of intersects, that monitors for checkpoints within
	// an individual image, not necessarily just the browser edge.
	
	function checkpointer( image, direction, checkpoints ){
		var ipadAnchor = scrl_winSize/2 - 180,
			currentCheckpt;
		
		for ( i=0; i < checkpoints.length; i++ ){
			var truePosition = parseInt(image.style.left) + checkpoints[i];
			if ( ipadAnchor > truePosition-15 && ipadAnchor < truePosition+15 &&
					image.lastCheck != checkpoints[i] ){
						
				image.lastCheck = checkpoints[i];
				var imageUrl = imagePrefix + 'x' + getName(image.src) + i + '.jpg',
					textUrl = imagePrefix + 'subhead' + getName(image.src) + '.jpg';
				
				var nextImage = $$('#bounding #ipad img:not(.active)')[0],
					currentImage = $$('#bounding #ipad img.active')[0],
					nextText = $$('#bounding #slider_text img:not(.active)')[0],
					currentText = $$('#bounding #slider_text img.active')[0];
				
				// if the name of the upcoming image is NOT the same as the name of the
				// image that's already in place, then execute this fade. this is in place
				// to avoid transitioning an image that's already been transitioned.
				
				if( getName(imageUrl) != getName(currentImage.src) ){
					nextImage.src = imageUrl;
					currentImage.tween('opacity', 0);
					nextImage.tween('opacity', 1);
					currentImage.removeClass('active');
					nextImage.addClass('active');
				}
				
				if( i == 0 && ( getName(textUrl) != getName(currentText.src) ) && direction == 'right' ){
					nextText.src = textUrl;
					currentText.tween('opacity', 0);
					nextText.tween('opacity', 1);
					currentText.removeClass('active');
					nextText.addClass('active');
				}
				
				if( i == 2 && ( getName(textUrl) != getName(currentText.src) ) && direction == 'left' ){
					nextText.src = textUrl;
					currentText.tween('opacity', 0);
					nextText.tween('opacity', 1);
					currentText.removeClass('active');
					nextText.addClass('active');
				}
			}
		}
	}
	
	// TAKES IN: ITEM BEING TRANSITIONED TO. RETURNS: NOTHING
	// Just changes the source of the images.
	
	function transitioner( item ){
		var nextImage = $$('#bounding #ipad img:not(.active)')[0],
			currentImage = $$('#bounding #ipad img.active')[0],
			nextText = $$('#bounding #slider_text img:not(.active)')[0],
			currentText = $$('#bounding #slider_text img.active')[0];
		
		// make this a global variable with a URL and reference it here
		nextImage.src = imagePrefix + 'x' + getName(item.src) + '0.jpg';
		nextText.src = imagePrefix + 'str' + getName(item.src) + '.jpg';
		
		currentImage.tween('opacity', 0);
		nextImage.tween('opacity', 1);
		currentImage.removeClass('active');
		nextImage.addClass('active');
		
		currentText.tween('opacity', 0);
		nextText.tween('opacity', 1);
		currentText.removeClass('active');
		nextText.addClass('active');
	}
	
	/* HELPER FUNCTION. GETS: A STRING. RETURNS: A STRING. */
	// This helper function takes in a long source URL and tokenizes it so that it
	// just gets the file name without the extension.
	
	function getName(s){
		var d = s.lastIndexOf('.');
		return s.substring(s.lastIndexOf('/') + 1, d < 0 ? s.length : d);
	}
		
	// These helper function quickly determines what is the frontmost (or
	// farthest) image. RETURNS: AN OBJECT

	function frontmostPosition(){
		var frontmost = 8000, frntItem;
		$$('#shift-frame img').each(function(item){
			if ( parseInt(item.style.left) < frontmost ){
				frontmost = parseInt(item.style.left);
				frntItem = item;
			}
		});
		return frntItem;
	}
	
	function previousItem(items){
		for ( i=0; i < items.length; i++ )
			if (parseInt(items[i].style.left) < 0 && parseInt(items[i].style.left) > -900)
				return items[i];
	}
	
	function farthestItem(){
		var farthest = 0, farItem;
		$$('#shift-frame img').each(function(item){
			if (parseInt(item.style.left) > farthest ){
				farthest = parseInt(item.style.left);
				farItem = item;
			}
		})
		return farItem;
	}
	
	
	
	
	/* EVENT HANDLER FOR BUTTONS */
	/* ******************************************* */
	
	// This event is fired when the left button is clicked. It gets the
	// position of the front most element, starts a scroll, and monitors the front
	// position of the element to make sure it stops at the proper locations.
	
	if ( $('scrll-leftbtn') ){
		$('scrll-leftbtn').addEvents({
			click: function(e){

				if ( inAction ) return;
				var prev = previousItem( $$('#shift-frame img') ),
					distance = -(parseInt(prev.style.left) - scrl_ipadAnchor - 120);

				inAction = true;
				transitioner(prev);
				targetedScroll( 'left', $$('#shift-frame img'), distance, 2200 );
			}
		});
	}

	$('scrll-rghtbtn').addEvents({
		click:function(e){
			
			if ( inAction ) return;
			var farthest = intersects( $$('#shift-frame img'), scrl_winSize ),
				distance = parseInt(farthest.style.left) - scrl_ipadAnchor + 80;
			// get the left of the next element, and find distance between it and iPad.
			
			inAction = true;
			transitioner(farthest);
			targetedScroll( 'right', $$('#shift-frame img'), distance, 2200 );
		}
	})
	
});
