/**
* Assign the view handler
*/

viewHandler = CaseStudies;

/**
* Creates a new object with methods used by the Case Studies page
*
* @author				Matt Gifford
* @copyright			2008 Timeshifting Interactive Limited
*/
function CaseStudies()
	{
	// Step 1. Define Properties

	var _instance = this;
	this.animationReferences = { count: 1 };
	this.firstCaseStudyDisplayed = false;

	this.thumbnailScrollRange = 0;
	this.thumbnailsScrolling = false;
	this.casesScrollRange = 0;
	this.casesScrolling = false;
	this.casesNextTimeout = null;

	var _MAX_THUMBNAILS_VISIBLE = 6;
	var _THUMBNAIL_WIDTH = 140;
	var _CASE_WIDTH = 942;



	// Step 2. Define Public Methods

	/**
	* Sets up the initial page state and event handlers
	*/
	this.init = function()
		{
		// Call generic page init method
		this.base.init.call(this);

		// 1. Add animation to url links
		this.initUrlLinkAnimation();
		this.initThumbnailAnimation();

		// 2. Setup the case studies content for scrolling
		document.getElementById('casesFeaturedArtboard').setAttribute('animationId', 'id' + this.animationReferences.count++);
		if (document.getElementById('casesFeaturedArtboard').style.left == '')
			{
			document.getElementById('casesFeaturedArtboard').style.left = '0px';
			}
		var casesCount = YAHOO.util.Dom.getElementsByClassName('caseItem', 'div', document.getElementById('casesFeaturedArtboard')).length;
		this.casesScrollRange = (casesCount - 1) * _CASE_WIDTH * -1;		// CSS left position offsets are negative

		// 3. Setup scrolling of the thumbnails
		var count = document.getElementById('casesThumbnailsArtboard').getElementsByTagName('div').length;
		if (_MAX_THUMBNAILS_VISIBLE < count)
			{
			this.thumbnailScrollRange = (count - _MAX_THUMBNAILS_VISIBLE) * _THUMBNAIL_WIDTH * -1;		// CSS left position offsets are negative
			}
		if (document.getElementById('casesThumbnailsArtboard').style.left == '')
			{
			document.getElementById('casesThumbnailsArtboard').style.left = '0px';
			}

		// 4. Event handlers to thumbnail links
		var anchors = document.getElementById('casesThumbnailsArtboard').getElementsByTagName('a');
		for (var x = anchors.length-1; 0 <= x; x--)
			{
			anchors[x].href = 'javascript:;';
			anchors[x].onclick = __eventHandlerSetActiveThumbnail;
			}

		// 5. Set the initial case study
		xhtml.setInitialCaseStudy();

		// 6. Start the animation of the subaru image
		if (!!document.getElementById('subaruPhoto1') == true)
			{
			setTimeout("xhtml.subaruPhotoFadeOut();", 5000);
			}
		}


	/**
	* Adds the event handlers to change the colour of url links
	*/
	this.initUrlLinkAnimation = function()
		{
		var links = document.getElementById('casesFeaturedArtboard').getElementsByTagName('a');
		for (var x = links.length-1; 0 <= x; x--)
			{
			// Check if this is an animated link
			if (links[x].className.indexOf('animate') != -1)
				{
				// Add an unique reference id to the element
				links[x].setAttribute('animationId', 'id' + this.animationReferences.count++);

				// Add event handler for mouse over
				links[x].onmouseover = function()
					{
					// Try to stop any existing animation on this object
					try { xhtml.animationReferences[this.getAttribute('animationId')].stop(false); } catch (err) {}

					// Animate the link
					xhtml.animationReferences[this.getAttribute('animationId')] = new YAHOO.util.ColorAnim(this, {color: { to: '#003366' }}, 0.3, YAHOO.util.Easing.easeBoth );
					xhtml.animationReferences[this.getAttribute('animationId')].animate();
					}

				// Add event handler for mouse out
				links[x].onmouseout = function()
					{
					// Try to stop any existing animation on this object
					try { xhtml.animationReferences[this.getAttribute('animationId')].stop(false); } catch (err) {}

					// Animate the link
					xhtml.animationReferences[this.getAttribute('animationId')] = new YAHOO.util.ColorAnim(this, {color: { to: '#336699' }}, 0.9, YAHOO.util.Easing.easeBoth );
					xhtml.animationReferences[this.getAttribute('animationId')].animate();
					}
				}
			}
		}


	/**
	* Adds event handlers to fade in/out colour thumbnail image on rollover
	*/
	this.initThumbnailAnimation = function()
		{
		var imgs = document.getElementById('casesThumbnailsArtboard').getElementsByTagName('img');

		// Process the images
		for (var x = imgs.length-1; 0 <= x; x--)
			{
			if (imgs[x].className == 'over')
				{
				// Add an unique reference id to the element
				imgs[x].setAttribute('animationId', 'id' + this.animationReferences.count++);

				// Add event handler for mouse over
				imgs[x].onmouseover = function()
					{
					// Try to stop any existing animation on this object
					try { xhtml.animationReferences[this.getAttribute('animationId')].stop(false); } catch (err) {}

					// Animate the image
					xhtml.animationReferences[this.getAttribute('animationId')] = new YAHOO.util.Anim(this, {opacity: { to: 1 }}, 0.2, YAHOO.util.Easing.easeBoth );
					xhtml.animationReferences[this.getAttribute('animationId')].animate();
					}

				// Add event handler for mouse out
				imgs[x].onmouseout = function()
					{
					// Check if this image is active, if so don't fade out
					if (this.parentNode.className.indexOf('active') == -1)
						{
						// Try to stop any existing animation on this object
						try { xhtml.animationReferences[this.getAttribute('animationId')].stop(false); } catch (err) {}

						// Animate the image
						xhtml.animationReferences[this.getAttribute('animationId')] = new YAHOO.util.Anim(this, {opacity: { to: 0.25 }}, 1.25, YAHOO.util.Easing.easeBoth );
						xhtml.animationReferences[this.getAttribute('animationId')].animate();
						}
					}
				}
			}
		}


	/**
	* Sets the display of the initial case study
	*/
	this.setInitialCaseStudy = function()
		{
		var cases = YAHOO.util.Dom.getElementsByClassName('caseItem', 'div', document.getElementById('casesFeaturedArtboard'));
		var thumbnails = document.getElementById('casesThumbnailsArtboard').getElementsByTagName('a');
		var initialCase = cases[0].className.replace('caseItem ', '');
		var hash = window.location.hash;

		// Check if we have a hash, if so check if it's a valid initial case study
		if (1 < hash.length)
			{
			// Grab the value of the hash
			hash = hash.replace('#', '');

			// Check if the value is valid
			for (x = 0; x < cases.length; x++)
				{
				if (cases[x].className.indexOf(hash) != -1)
					{
					initialCase = cases[x].className.replace('caseItem', '').replace(' ', '');
					}
				}
			}

		// Set the initial case
		for (x = 0; x < cases.length; x++)
			{
			if (cases[x].className.indexOf(initialCase) != -1)
				{
				// Move to the correct case
				document.getElementById('casesFeaturedArtboard').style.left = (x * _CASE_WIDTH * -1) + 'px';

				// Make the featured cases visible
				document.getElementById('casesFeaturedArtboard').style.visibility = 'visible';

				// Remove the loading div
				document.getElementById('casesFeatured').removeChild(document.getElementById('casesFeaturedLoading'));

				// Set the thumbnail active
				thumbnails[x].className += ' active';

				// Break out of the loop
				break;
				}
			}
		}


	/**
	* Changes the displayed case study to the one specified
	*
	* @param		name		The case study name
	*/
	this.setCaseStudy = function(name)
		{
		var cases = YAHOO.util.Dom.getElementsByClassName('caseItem', 'div', document.getElementById('casesFeaturedArtboard'));
		var thumbnails = document.getElementById('casesThumbnailsArtboard').getElementsByTagName('a');

		// Set the new case
		for (x = 0; x < cases.length; x++)
			{
			if (cases[x].className.indexOf(name) != -1)
				{
				// Set the thumbnail active
				thumbnails[x].className += ' active';

				// Move to the correct case
				var artboard = document.getElementById('casesFeaturedArtboard');
				var newLocation = (x * _CASE_WIDTH * -1);

				this.casesScrolling = true;

				// Try to stop any existing animation on this object
				try { xhtml.animationReferences[artboard.getAttribute('animationId')].stop(false); } catch (err) {}

				// Animate the image
				xhtml.animationReferences[artboard.getAttribute('animationId')] = new YAHOO.util.Anim(artboard, {left: { to: newLocation }}, 2.5, YAHOO.util.Easing.easeBoth);
				xhtml.animationReferences[artboard.getAttribute('animationId')].onComplete.subscribe(
					function()
						{
						xhtml.casesScrolling = false;
						}
					);
				xhtml.animationReferences[artboard.getAttribute('animationId')].animate();

				// Update the document hash
				window.location = '#' + name.replace(/[^a-z]/g, '');

				// Break out of the loop
				break;
				}
			}
		}

	
	/**
	* Injects the video player
	*
	* @param		url			The src url for the flash to inject
	* @param		obj			The anchor clicked on
	* @return		void
	*/
	this.injectVideo = function(url, obj)
		{
		// Delete all other video nodes
		if (!!document.getElementById('videoPlayer'))
			{
			document.getElementById('videoPlayer').parentNode.removeChild(document.getElementById('videoPlayer'));
			}
		
		// Build the video player container
		var container = document.createElement('div');
		container.id = 'videoPlayer';
		container.innerHTML = '<div id="flashContainer"><div id="flashContent"></div></div><a href="javascript:;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"><img class="closeButton" src="images/dialogs-button-close.png" width="14" height="14" alt=""/></a>';

		// Inject the video player
		var node = obj;
		while (node.parentNode)
			{
			if (node.className.indexOf('caseItem') != -1)
				{
				break;
				}
			node = node.parentNode;
			}
		node.getElementsByTagName('div')[0].appendChild(container);

		// Inject the flash
		swfobject.embedSWF(url, 'flashContent', '544', '304', '10', '', {}, {bgcolor: '#000000', menu: 'false', wmode: 'opaque', scale: 'noscale', allowscriptaccess: 'always'}, {id: 'flashcontent', name: 'nameflashcontent'});
		}


	/**
	* Scrolls to the next case study, or back to the first one if the current is the last
	*/
	this.nextCaseStudy = function()
		{
		// Queue the next action if we're in the middle of a scroll
		if (xhtml.casesScrolling == true)
			{
			clearTimeout(this.casesNextTimeout);
			this.casesNextTimeout = setTimeout("xhtml.nextCaseStudy();", 200);
			return;
			}

		// Get the current locations
		var offset = parseInt(document.getElementById('casesFeaturedArtboard').style.left);
		var caseIndex = 0;

		// Check if we're not on the last item
		if (this.casesScrollRange < offset)
			{
			caseIndex =  ((offset - _CASE_WIDTH) / _CASE_WIDTH) * -1;
			}

		// Fire the click event handler on the correct thumbnail
		var thumbnails = document.getElementById('casesThumbnailsArtboard').getElementsByTagName('a');
		thumbnails[caseIndex].onclick();
		}


	/**
	* Scrolls the thumbnail container to the left
	*/
	this.thumbnailsPrev = function()
		{
		// Delete all other video nodes
		if (!!document.getElementById('videoPlayer'))
			{
			document.getElementById('videoPlayer').parentNode.removeChild(document.getElementById('videoPlayer'));
			}

		var offset = parseInt(document.getElementById('casesThumbnailsArtboard').style.left);

		// Check if we are not already scrolling
		if (xhtml.thumbnailsScrolling == true)
			{
			return;
			}

		// Check if we can scroll
		if (offset < 0)
			{
			// Calculate the scroll destination
			offset += _THUMBNAIL_WIDTH * 3;
			if (0 < offset)
				{
				offset = 0;
				}

			// Set the thumbnails as scrolling
			xhtml.thumbnailsScrolling = true;

			// Animate the artboard
			var anim = new YAHOO.util.Anim(document.getElementById('casesThumbnailsArtboard'), {left: { to: offset }}, 0.75, YAHOO.util.Easing.easeBoth );
			anim.onComplete.subscribe(
				function()
					{
					xhtml.thumbnailsScrolling = false;
					}
				);
			anim.animate();
			}
		else
			{
			// Animate to indicate we can't scroll any further
			xhtml.thumbnailsScrolling = true;
			var anim = new YAHOO.util.Anim(document.getElementById('casesThumbnailsArtboard'), {left: { to: 25 }}, 0.15, YAHOO.util.Easing.easeIn );
			anim.onComplete.subscribe(
				function()
					{
					var anim = new YAHOO.util.Anim(document.getElementById('casesThumbnailsArtboard'), {left: { to: 0 }}, 0.35, YAHOO.util.Easing.easeOut );
					anim.onComplete.subscribe(
						function()
							{
							xhtml.thumbnailsScrolling = false;
							}
						);
					anim.animate();
					}
				);
			anim.animate();
			}
		}


	/**
	* Scrolls the thumbnail container to the right
	*/
	this.thumbnailsNext = function()
		{
		// Delete all other video nodes
		if (!!document.getElementById('videoPlayer'))
			{
			document.getElementById('videoPlayer').parentNode.removeChild(document.getElementById('videoPlayer'));
			}

		var offset = parseInt(document.getElementById('casesThumbnailsArtboard').style.left);

		// Check if we are not already scrolling
		if (xhtml.thumbnailsScrolling == true)
			{
			return;
			}

		// Check if we can scroll
		if (this.thumbnailScrollRange < offset)
			{
			// Calculate the scroll destination
			offset -= _THUMBNAIL_WIDTH * 3;
			if (offset < this.thumbnailScrollRange)
				{
				offset = this.thumbnailScrollRange;
				}

			// Set the thumbnails as scrolling
			xhtml.thumbnailsScrolling = true;

			// Animate the artboard
			var anim = new YAHOO.util.Anim(document.getElementById('casesThumbnailsArtboard'), {left: { to: offset }}, 0.75, YAHOO.util.Easing.easeBoth );
			anim.onComplete.subscribe(
				function()
					{
					xhtml.thumbnailsScrolling = false;
					}
				);
			anim.animate();
			}
		else
			{
			// Animate to indicate we can't scroll any further
			xhtml.thumbnailsScrolling = true;
			var anim = new YAHOO.util.Anim(document.getElementById('casesThumbnailsArtboard'), {left: { to: xhtml.thumbnailScrollRange - 25 }}, 0.15, YAHOO.util.Easing.easeIn );
			anim.onComplete.subscribe(
				function()
					{
					var anim = new YAHOO.util.Anim(document.getElementById('casesThumbnailsArtboard'), {left: { to: xhtml.thumbnailScrollRange }}, 0.35, YAHOO.util.Easing.easeOut );
					anim.onComplete.subscribe(
						function()
							{
							xhtml.thumbnailsScrolling = false;
							}
						);
					anim.animate();
					}
				);
			anim.animate();
			}
		}


	/**
	* Opens a popup with the Kelloggs flash game in it
	*/
	this.flashKelloggs = function()
		{
		var width = 420;
		var height = 460;

		var leftOffset = parseInt(window.screen.width) ? ((parseInt(window.screen.width)/2)-(width/2)) : 40;
		var topOffset = parseInt(window.screen.height) ? ((parseInt(window.screen.height)/2)-(height/2)) : 40;
		if (leftOffset < 0)
			{
			leftOffset = 0;
			}
		if (topOffset < 0)
			{
			topOffset = 0;
			}

		try { _flashPopupWin.close(); } catch (err) {}

		_flashPopupWin = window.open(
			'/casestudies-kelloggs.html',
			'flashPopup',
			'toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,copyhistory=no,width=' + width + ',height=' + height + ',top=' + topOffset + ',left=' + leftOffset
			);
		}

	
	/**
	* Fades out the primary subaru image
	*/
	this.subaruPhotoFadeOut = function()
		{
		anim = new YAHOO.util.Anim(document.getElementById('subaruPhoto1'), {opacity: { to: 0 }}, 2);
		anim.onComplete.subscribe(
			function()
				{
				setTimeout("xhtml.subaruPhotoFadeIn();", 5000);
				}
			);
		anim.animate();
		}


	/**
	* Fades in the primary subaru image
	*/
	this.subaruPhotoFadeIn = function()
		{
		anim = new YAHOO.util.Anim(document.getElementById('subaruPhoto1'), {opacity: { to: 1 }}, 2);
		anim.onComplete.subscribe(
			function()
				{
				setTimeout("xhtml.subaruPhotoFadeOut();", 5000);
				}
			);
		anim.animate();
		}



	// Step 3. Define Private Methods

	/**
	* Event Handler: Set active thumbnail
	*/
	function __eventHandlerSetActiveThumbnail()
		{
		// Delete all other video nodes
		if (!!document.getElementById('videoPlayer'))
			{
			document.getElementById('videoPlayer').parentNode.removeChild(document.getElementById('videoPlayer'));
			}

		// Set the active class on in this thumbnail
		this.className += ' active';

		// Find the image
		var img = this.getElementsByTagName('img')[1];

		// Try to stop any existing animation on this object
		try { xhtml.animationReferences[img.getAttribute('animationId')].stop(false); } catch (err) {}

		// Animate the image
		xhtml.animationReferences[img.getAttribute('animationId')] = new YAHOO.util.Anim(img, {opacity: { to: 1 }}, 0);
		xhtml.animationReferences[img.getAttribute('animationId')].animate();

		// Remove the active class from any other thumbnails and fade them out
		var anchors = document.getElementById('casesThumbnailsArtboard').getElementsByTagName('a');
		for (var y = anchors.length-1; 0 <= y; y--)
			{
			// Check if it's a thumbnail other than this one
			if (anchors[y].className.indexOf('active') != -1 && anchors[y] != this)
				{
				// Reset the class name
				anchors[y].className = anchors[y].className.replace(/\s?active/g, '');

				// Find the image
				var img = anchors[y].getElementsByTagName('img')[1];

				// Try to stop any existing animation on the old active object
				try { xhtml.animationReferences[img.getAttribute('animationId')].stop(false); } catch (err) {}

				// Animate the image back to transparent
				xhtml.animationReferences[img.getAttribute('animationId')] = new YAHOO.util.Anim(img, {opacity: { to: 0.25 }}, 0.3);
				xhtml.animationReferences[img.getAttribute('animationId')].animate();
				}
			}

		// Change the featured case study
		xhtml.setCaseStudy( this.className.replace(/\s?active/g, '') );
		}
	}

