/**
* Assign the view handler
*/

viewHandler = CityMediaPage;

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

	var _instance = this;
	var _tooltips = [];

	// Vars used by the thumbnails
	var _thumbnailWindow = 5;
	var _thumbnailSize = 89;
	var _currentMedia = {
		videos: 0,
		photos: 0
		}
	var _totalMedia = {
		videos: 0,
		photos: 0
		}
	this.scrollingInProgress = false;




	// 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);

		// Default to no media modules
		var hasMediaModules = false;

		// Initialize the videos module, if present
		if (document.getElementById('videosContent'))
			{
			this.initVideosModule();
			hasMediaModules = true;
			}

		// Initialize the photos module, if present
		if (document.getElementById('photosContent'))
			{
			this.initPhotosModule();
			hasMediaModules = true;
			}

		// Check if there's media specified on url, and update the page
		if (hasMediaModules == true && window.location.href.indexOf('#') != -1)
			{
			this.loadDefaultMedia();
			}

		// Add author photo for niel
		var paragraphs = YAHOO.util.Dom.getElementsByClassName("authorFeineman", "p", document.getElementById('cityContent'));
		if (paragraphs.length)
			{
			paragraphs[0].setAttribute('rel', 'author-neil.jpg');
			paragraphs[0].onmouseover = __eventHandlerBlogAuthorOver;
			paragraphs[0].onmouseout = __eventHandlerBlogAuthorOut;
			}
		}



	/**
	* Initializes the videos media module
	*/
	this.initVideosModule = function()
		{
		if (!document.getElementById('videosThumbnailsContainer'))
			{
			return;
			}

		// Calculate the number of thumbnails
		_totalMedia.videos = document.getElementById('videosThumbnailsContainer').getElementsByTagName('a').length;

		// Set the initial location
		document.getElementById('videosThumbnailsContainer').style.left = '0px';

		// Add tooltips to thumbnails
		var anchors = document.getElementById('videosThumbnailsContainer').getElementsByTagName('a');
		for (var x = 0; x < anchors.length; x++)
			{
			var content = '<div class="tooltipGeneric"><div class="tooltipGenericInner">' + anchors[x].title + '<img src="/images/global-elements-tooltip-arrow-black-fs8.png" alt=""/></div></div>';
			_tooltips[_tooltips.length] =  new YAHOO.widget.Tooltip("videoAnchorTooltip" + x, { context: anchors[x], text: content, preventoverlap: false });
			}
		}


	/**
	* Initializes the photos media module
	*/
	this.initPhotosModule = function()
		{
		if (!document.getElementById('photosThumbnailsContainer'))
			{
			return;
			}

		// Calculate the number of thumbnails
		_totalMedia.photos = document.getElementById('photosThumbnailsContainer').getElementsByTagName('a').length;

		// Set the initial location
		document.getElementById('photosThumbnailsContainer').style.left = '0px';

		// Add tooltips to thumbnails
		var anchors = document.getElementById('photosThumbnailsContainer').getElementsByTagName('a');
		for (var x = 0; x < anchors.length; x++)
			{
			var content = '<div class="tooltipGeneric"><div class="tooltipGenericInner">' + anchors[x].title + '<img src="/images/global-elements-tooltip-arrow-black-fs8.png" alt=""/></div></div>';
			_tooltips[_tooltips.length] =  new YAHOO.widget.Tooltip("photoAnchorTooltip" + x, { context: anchors[x], text: content, preventoverlap: false });
			}
		}


	/**
	* Loads the default media into the document
	*/
	this.loadDefaultMedia = function()
		{
		// Try to retrieve the photo and video ids
		try
			{
			var video = parseInt(window.location.hash.split('|')[0].replace(/\D/g, ''));
			var photo = parseInt(window.location.hash.split('|')[1].replace(/\D/g, ''));
			}
		catch (err)
			{
			return;
			}

		// Clear the current captions and credits
		if (document.getElementById('videosText'))
			{
			document.getElementById('videosText').innerHTML = '';
			}
		if (document.getElementById('photosText'))
			{
			document.getElementById('photosText').innerHTML = '';
			}

		// Load the media
		if (isNaN(video) == false && video != 0)
			{
			// Display the media
			this.playVideo(video);

			// Scroll the thumbnails
			var thumbnails = document.getElementById('photosThumbnailsContainer').getElementsByTagName('a');
			var index = -1;
			for (var x = 0; x < thumbnails.length; x++)
				{
				if (thumbnails[x].getAttribute('rel') == video)
					{
					_currentMedia.videos = x;
					break;
					}
				}
			document.getElementById('videosThumbnailsContainer').style.left = (_currentMedia.videos * _thumbnailSize * -1) + 'px';
			}

		if (isNaN(photo) == false && photo != 0)
			{
			// Display the media
			this.displayPhoto(photo);

			// Scroll the thumbnails
			var thumbnails = document.getElementById('photosThumbnailsContainer').getElementsByTagName('a');
			var index = -1;
			for (var x = 0; x < thumbnails.length; x++)
				{
				if (thumbnails[x].getAttribute('rel') == photo)
					{
					_currentMedia.photos = x;
					break;
					}
				}
			document.getElementById('photosThumbnailsContainer').style.left = (_currentMedia.photos * _thumbnailSize * -1) + 'px';
			}
		}


	/**
	* Plays the specified video
	*
	* @param		param		The thumbnail obj clicked on || the video number to display
	*/
	this.playVideo = function(param)
		{
		// Check if the video module exists
		if (!document.getElementById('videosContent'))
			{
			return;
			}

		// Retrieve the id
		if (typeof(param) == 'number')
			{
			var id = param;
			}
		else
			{
			var id = param.getAttribute('rel');
			}

		// Map id to filename TODO
		var filename = '../videostore/' + id + '.flv';

		// Delete the existing flash container
		var parent = document.getElementById('flashContainer').parentNode
		parent.removeChild( document.getElementById('flashContainer') );

		// Add the new container
		var div = document.createElement('div');
		div.id = 'flashContainer';
		parent.appendChild(div);

		// Insert the movie into the container
		var so = new SWFObject("/videoplayer/fullvideo.swf", "mediaVideo", "418", "313", "8", "#000000");
		so.addParam("wmode", "opaque");
		so.addParam("allowScriptAccess", "sameDomain");
		so.addParam("allowFullScreen", "true");
		so.addVariable("videoPath", filename);
		so.write('flashContainer');

		// Update the current video id
		document.getElementById('ajaxVideo').value = id;
		this.updateUrlHash();

		// Dim the old video text
		document.getElementById('videosText').className = 'loading';

		// Clear the current captions and credits
		document.getElementById('videosText').innerHTML = '';

		// Send the ajax request to retrieve the new text
		YAHOO.util.Connect.asyncRequest("GET", 'media-description.ajax.php?id=' + id, { success: __callbackVideoText } );

		// Update embed video code
		if (document.getElementById('videoEmbedCode'))
			{
			var template = '<object width="418" height="313"><param name="movie" value="http://www.30daysontheroad.com/videoplayer/fullvideo.swf"></param><param name="wmode" value="transparent"></param><param flashvars="videoPath=%filename%"></param><embed src="http://www.30daysontheroad.com/videoplayer/fullvideo.swf" type="application/x-shockwave-flash" wmode="transparent" flashvars="videoPath=%filename%" width="418" height="313"></embed></object>';
			template = template.replace(/%filename%/g, filename);
			document.getElementById('videoEmbedCode').value = template;
			}
		}


	/**
	* Displays the specified photo
	*
	* @param		param		The thumbnail obj clicked on || the photo number to display
	*/
	this.displayPhoto = function(param)
		{
		// Check if the photo module exists
		if (!document.getElementById('photosContent'))
			{
			return;
			}

		// Retrieve the id
		if (typeof(param) == 'number')
			{
			var id = param;
			}
		else
			{
			var id = param.getAttribute('rel');
			}

		// Delete the existing photo
		var imgs = document.getElementById('photosContent').getElementsByTagName('img');
		for (var x = imgs.length - 1; 0 <= x; x--)
			{
			document.getElementById('photosContent').removeChild( imgs[x] );
			}

		// Insert the photo into the container
		var img = document.createElement('img');
		img.src = '/image.html?view=large&imageId=' + id;
		document.getElementById('photosContent').appendChild( img );

		// Update the current photo id
		document.getElementById('ajaxPhoto').value = id;
		this.updateUrlHash();

		// Dim the old video text
		document.getElementById('photosText').className = 'loading';

		// Clear the current captions and credits
		document.getElementById('photosText').innerHTML = '';

		// Send the ajax request to retrieve the new text
		YAHOO.util.Connect.asyncRequest("GET", 'media-description.ajax.php?id=' + id, { success: __callbackPhotoText } );
		}


	/**
	* Scrolls the thumbails left
	*
	* @param		type			The media box to scroll
	*/
	this.thumbnailsPrev = function(type)
		{
		// Check if only one page
		if (_totalMedia[type] < 6)
			{
			return;
			}

		// Scroll left
		_currentMedia[type] -= 5;

		// Range check
		if (_currentMedia[type] < 0)
			{
			_currentMedia[type] = 0;
			}

		// Update UI
		this.thumbnailsUpdate(type);
		}


	/**
	* Scrolls the thumbails right
	*
	* @param		type			The media box to scroll
	*/
	this.thumbnailsNext = function(type)
		{
		// Check if only one page
		if (_totalMedia[type] < 6)
			{
			return;
			}

		// Scroll right
		_currentMedia[type] += 5;

		// Range check
		if ((_totalMedia[type] - _thumbnailWindow) < _currentMedia[type])
			{
			_currentMedia[type] = (_totalMedia[type] - _thumbnailWindow);
			}

		// Update UI
		this.thumbnailsUpdate(type);
		}


	/**
	* Updates the thumbnails UI
	*
	* @param		type			The media box to scroll
	*/
	this.thumbnailsUpdate = function(type)
		{
		// If the UI is currently updating, return
		if (this.scrollingInProgress == true)
			{
			return;
			}

		// Queue the scroll
		switch (type)
			{
			case 'videos':
				this.thumbnailsScroll('videosThumbnailsContainer', (_currentMedia[type] * _thumbnailSize * -1) );
				break;

			case 'photos':
				this.thumbnailsScroll('photosThumbnailsContainer', (_currentMedia[type] * _thumbnailSize * -1) );
				break;
			}
		}


	/**
	* Scrolls the specified thumbnail container to the specified location
	*
	* @param		id				The container Id
	* @param		finish		The location to scroll to
	*/
	this.thumbnailsScroll = function(id, finish)
		{
		xhtml.scrollingInProgress = true;

		// Calculate the new location
		var current = parseInt(document.getElementById(id).style.left);

		// Calculate new location
		if (finish < current)
			{
			// we're scrolling right
			current += -20;

			// Range check
			if (current < finish)
				{
				current = finish;
				}
			}
		else
			{
			// we're scrolling left
			current += 20;

			// Range check
			if (finish < current)
				{
				current = finish;
				}
			}

		// Update the container location
		document.getElementById(id).style.left = current + 'px';

		// Check if we need to recurse
		if (current != finish)
			{
			setTimeout('xhtml.thumbnailsScroll("' + id + '", ' + finish + ');', 15);
			}
		else
			{
			xhtml.scrollingInProgress = false;
			}
		}


	/**
	* Updates the URL hash so bookmarking and share this works
	*/
	this.updateUrlHash = function()
		{
		window.location.href = '#video' + document.getElementById('ajaxVideo').value + '|photo' + document.getElementById('ajaxPhoto').value;
		}


	/**
	* Toggles the display of a city page module
	*
	* @param		obj			The button clicked
	*/
	this.toggleModule = function(obj)
		{
		// Find the module div
		var module = obj.parentNode.parentNode;

		// Toggle the state
		if (module.className.indexOf('expanded') != -1)
			{
			module.className = module.className.replace(/\s?expanded/g, '') + ' collapsed';
			var body = module.getElementsByTagName('div')[1];
			body.className += ' hidden';
			}
		else
			{
			module.className = module.className.replace(/\s?collapsed/g, '') + ' expanded';
			var body = module.getElementsByTagName('div')[1];
			body.className = body.className.replace(/\s?hidden/g, '');
			}
		}


	/**
	* Expands the interview item
	*
	* @param		obj		The button clicked on
	*/
	this.expandInterview = function(obj)
		{
		// Hide the read more link
		xhtml.findParent(obj, 'p').className = 'hidden';

		// Display the additional content
		xhtml.findParent(obj, 'div').getElementsByTagName('div')[0].className = '';
		}


	/**
	* Expands the story item
	*
	* @param		obj		The button clicked on
	*/
	this.expandStory = function(obj)
		{
		// Hide the read more link
		xhtml.findParent(obj, 'p').className = 'hidden';

		// Display the additional content
		xhtml.findParent(obj, 'div').getElementsByTagName('div')[0].className = '';
		}



	// 3. Define Private Methods

	/**
	* Event Handler: Mouse over blog image popup author
	*
	* @param		event		The browser event object
	*/
	function __eventHandlerBlogAuthorOver(event)
		{
		// 1. Create the image rollover
		var div = document.createElement('div');
		div.id = 'blogImagePopup';

		var html = '<div><img src="/images/blog/%filename%" alt=""/><img class="arrow" src="/images/global-elements-tooltip-arrow-beige-fs8.png" alt=""/></div>';
		html = html.replace('%filename%', this.getAttribute('rel'));

		div.innerHTML = html;


		// 2. Position the image rollover

		// Get the event object if necessary
		event = !!event ? event : window.event;

		// Get the mouse location
		if(xhtml.isTrident == true)
			{
			var mouseX = window.event.clientX;
			var mouseY = window.event.clientY;
			}
		else
			{
			var mouseX = event.pageX;
			var mouseY = event.pageY;
			}

		div.style.left = mouseX - 40 + 'px';
		div.style.top = mouseY - 20 + 'px';

		// 3. Remove any existing rollover
		__eventHandlerBlogAuthorOut();

		// 4. Insert into document
		document.body.appendChild( div );
		}


	/**
	* Event Handler: Mouse out blog image popup author
	*
	* @param		event		The browser event object
	*/
	function __eventHandlerBlogAuthorOut()
		{
		if (document.getElementById('blogImagePopup'))
			{
			document.body.removeChild(document.getElementById('blogImagePopup'));
			}
		}


	/**
	* Callback: Updates the video's caption, description and credits
	*
	* @param		callbackObj			The ajax callback object
	*/
	function __callbackVideoText(callbackObj)
		{
		// Check if we got content back
		if (callbackObj.responseText && 0 < callbackObj.responseText.length)
			{
			var content = callbackObj.responseText;
			}
		else
			{
			var content = '<h4 class="item0">untitled</h4>';
			}

		// Create a container node
		var container = document.createElement('div');
		container.innerHTML = callbackObj.responseText;

		// Try to retrieve the id
		try
			{
			var id = container.getElementsByTagName('h4')[0].className.replace(/\D/g, '');
			}
		catch (err)
			{
			return;
			}

		// Check if this detail is for the currently displayed video, if not return
		if (id != document.getElementById('ajaxVideo').value)
			{
			return;
			}

		// Update the video's text content and remove loading class
		document.getElementById('videosText').innerHTML = callbackObj.responseText;
		document.getElementById('videosText').className = '';
		}


	/**
	* Callback: Updates the photo's caption, description and credits
	*
	* @param		callbackObj			The ajax callback object
	*/
	function __callbackPhotoText(callbackObj)
		{
		// Check if we got content back
		if (callbackObj.responseText && 0 < callbackObj.responseText.length)
			{
			var content = callbackObj.responseText;
			}
		else
			{
			var content = '<h4 class="item0">untitled</h4>';
			}

		// Create a container node
		var container = document.createElement('div');
		container.innerHTML = callbackObj.responseText;

		// Try to retrieve the id
		try
			{
			var id = container.getElementsByTagName('h4')[0].className.replace(/\D/g, '');
			}
		catch (err)
			{
			return;
			}

		// Check if this detail is for the currently displayed video, if not return
		if (id != document.getElementById('ajaxPhoto').value)
			{
			return;
			}

		// Update the video's text content and remove loading class
		document.getElementById('photosText').innerHTML = callbackObj.responseText;
		document.getElementById('photosText').className = '';
		}
	}
