﻿	// This event handler is called if the browser supports onorientationchange
	// event on the body tag.
	function orient()
	{
		var stylesheetHRef = 'css/iphone_portrait.css'
		
		if (isiphone() == true)
		{
			// iphone.
			
			switch(window.orientation)
			{  
				case 0:
				//portrait
				stylesheetHRef = 'css/iphone_portrait.css';
				break;
				case -90:
				stylesheetHRef = 'css/iphone_landscape.css';
				break;
				case 90:
				//landscape
				stylesheetHRef = 'css/iphone_landscape.css';
				break;
						
			}
			
		}
		else
		{
			// Not an iphone.
			stylesheetHRef= 'css/desktop.css';

		}
		
		// Set the stylesheet.
		var userAgentStyleSheetEl = document.getElementById('uagentCss');
		userAgentStyleSheetEl.href = stylesheetHRef;

		

	}

	function isHtml5Supported(videoElementId)
	{
		var videoEl = document.getElementById(videoElementId);
		
		// If we can access the source attribute then it means we
		// have a valid object, otherwise it will throw an exception.
		try
		{
			var src = videoEl.src;
			
			if (src == undefined)
			{
				return false;
			}

			return true;
		}
		catch(ex)
		{
			return false;
		}
	}
	
	
	function getiPhoneOSMajorVersion()
	{
		var value = -1;
		
		if (isiphone() == true)
		{
			// Default to version 1 for older iphone user Agents.
			value = 1;
			var useragent = navigator.userAgent.toLowerCase();
			var location = useragent.indexOf('iphone os')

			if (location > -1)
			{
				value = useragent.substring(location + 10, location + 11);
			}			
			
		}
		
		return value;
	}
	
	function isiphone()
	{
		
		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
		{
			return true;
		}
	
		return false;
	}
	
	function showElement(elementId)
	{
		var element = document.getElementById(elementId);
		element.style.visibility = 'visible';
		element.style.display = 'block';
	}

	function hideElement(elementId)
	{
		var element = document.getElementById(elementId);
		element.style.visibility = 'hidden';
		element.style.display = 'none';
	}
	
	function playVideo(videoUri)
	{
		var videoElem = document.getElementById("videoelem");
		videoElem.pause();
		videoElem.src = videoUri;
		videoElem.load();
		videoElem.play();
		startedPlaying();
	}


	function setAndPauseVideo(videoElementId, videoUri)
	{
		var videoElem = document.getElementById(videoElementId);
		videoElem.src = videoUri;
		videoElem.pause();
	}
	

	function setVideoVisibilityByChannel()
	{
		// Go through the videos and show/hide
		// depending on the channel.
		var v=1;

		var iphoneChannelSelectEl = document.getElementById("iphoneChannelSelect");
		var selectedChannel = iphoneChannelSelectEl.options[iphoneChannelSelectEl.selectedIndex].value;
		
		// Initialize the iphone videos.
		for (v=1;v<=iphoneVideoAssetCount;v++)
		{
			var videoId = 'iVideo' + v;
			var videoChannel = getVideoToutAsset('assetChannel', videoId);
			
			if (selectedChannel == '' || videoChannel == selectedChannel)
			{
				// Display the item.
				showElement(videoId + "Wrapper");
			}
			else
			{
				// Hide the item.
				hideElement(videoId + "Wrapper");
			}

		}
		
	}

	function showDebugInfo()
	{
		showElement('debugLabel');
		var message = debugHtml + '<br /><br />Currently Playing=' + document.getElementById('videoelem').src;
		document.getElementById('debugLabel').innerHTML = message;
	}
	
	// This is Play() triggered.
	function startedPlaying()
	{
		hideElement('videoFeaturePlayButton');
		showElement('videoFeaturePauseButton');
		
	}
	
	function updateVideoTimeInfo(videoElId, timeElement)
	{
		var video = document.getElementById(videoElId);
		
		var durationString = '';

		if (isNaN(video.duration) == true)
		{
			durationString = '--:--';
		}
		else if (isFinite(video.duration) == false)
		{
			durationString = 'Live';
		}
		else
		{

			var minutes = Math.floor(video.duration/60);    // The minutes
			var seconds = Math.floor(video.duration % 60);  // The balance of seconds

			var minutesDisplay = minutes;
			
			if (minutes < 10)
			{
				minutesDisplay = '0' + minutes;
			}			
			
			var secondsDisplay = seconds;
			
			if (seconds < 10)
			{
				secondsDisplay = '0' + seconds;
			}
			
			durationString = minutesDisplay + ":" + secondsDisplay;
		}
		
		timeElement.innerHTML =  durationString;	
	}
	
	// This is when the video event playing is triggered.
	function videoPlaying()
	{
		updateVideoTimeInfo(videoFeature.id, document.getElementById('videoFeatureInfoTimer'));
	}
	
	function stoppedPlaying()
	{
		showElement('videoFeaturePlayButton');
		hideElement('videoFeaturePauseButton');
	}
	
	function videoFeatureEnded()
	{
		// When the video ends, we need to reset to the poster frame
		// This can only be accomplished by replacing the video element
		// with a new one that has not had the source set yet.
		var videoElem = document.getElementById('videoelem');
		var newVideoElem = createAndReplaceVideoFeatureElement(videoElem);
	}
	
	function createAndReplaceVideoFeatureElement(originalVideoElement)
	{
		var videoParent = originalVideoElement.parentNode;
		var newVideoElem = document.createElement('video');
		newVideoElem.id = originalVideoElement.id;
		newVideoElem.poster = originalVideoElement.poster;
		newVideoElem.controls = originalVideoElement.controls;
		newVideoElem.innerHTML = originalVideoElement.innerHTML;
		videoParent.appendChild(newVideoElem);
		videoParent.removeChild(originalVideoElement);
		videoFeature = newVideoElem;
		// Add the event listeners to the new video.
		addEventListenersToControls()
		originalVideoElement.poster = 'images/sp.gif';
		return newVideoElem;
	}
	
	// Adds event listeners to controls including the video Feature
	function addEventListenersToControls()
	{
	
		var playButton = document.getElementById('videoFeaturePlayButton');
		var pauseButton = document.getElementById('videoFeaturePauseButton');

		videoFeature.addEventListener("play", startedPlaying);
		videoFeature.addEventListener("playing", function() { videoPlaying(); } );
		videoFeature.addEventListener("pause", stoppedPlaying);
		videoFeature.addEventListener("ended", function () {
			if (!videoFeature.paused)
				videoFeature.pause();
				stoppedPlaying();
				videoFeatureEnded();
	    
			});
		videoFeature.addEventListener("canplaythrough", function () {
			 videoFeature.play();
		});
		
		videoFeature.addEventListener("error", function() {
			alert('An error occurred. ' + videoFeature.error.code);
		});
		
		// Add click events to the play and pause buttons.
		// Do not-readd them again later.
		if (buttonEventsInitialized == false)
		{
			buttonEventsInitialized = true;
			playButton.addEventListener("click", function() { playButtonClicked(); } );
			pauseButton.addEventListener("click", function() {pauseButtonClicked(); } );
		}

	}
	
	function pauseButtonClicked()
	{
		videoFeature.pause();
	}
	
	function playButtonClicked()
	{
		//alert('play');
		
		if (videoFeature.paused)
		{
			// Already paused.
			if (!videoFeature.src)
			{
				// Set the source to the selected video.
				videoFeature.src = getVideoToutAsset('assetDesktopVideoUri',selectedVideoToutIdSuffix);
			}
			
			if (loadRequired())
			{
					videoFeature.load();
			}
			
			if (canPlayThrough())
			{
				videoFeature.play();
			}
			
			
		}
		else
		{
			// Pause the video.
			videoFeature.pause();		
		}
	}
	
	
	function waiting (ev)
	{
		// Do nothing.
		//		 if (!showProgress) {
		//			 showProgress = true;
		//			 playButton.innerHTML = "Loading...";
		//			 playButton.className = "videobutton videoloading";
		//		 }
	}
	
	function loadRequired()
	{
		var videoElem = document.getElementById('videoelem');
		if ("DATA_UNAVAILABLE" in HTMLMediaElement)
			return videoElem.readyState == HTMLMediaElement.DATA_UNAVAILABLE;
		if ("HAVE_NOTHING" in HTMLMediaElement)
			return videoElem.readyState == HTMLMediaElement.HAVE_NOTHING;
		return false
	}
	
	function canPlayThrough()
	{
		var videoElem = document.getElementById('videoelem');
		if ("CAN_PLAY_THROUGH" in HTMLMediaElement)
			return videoElem.readyState == HTMLMediaElement.CAN_PLAY_THROUGH;
		if ("HAVE_ENOUGH_DATA" in HTMLMediaElement)
			return videoElem.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA;
		return false
	}
	
	function updateProgress(ev)
	{
		return;
		//		if (!showProgress)
		//		   return;
		//		if (ev.total)
		//			playButton.innerHTML = "Loading " + (100*ev.loaded/ev.total).toFixed(0) + "%";
		//		else
		//			playButton.innerHTML = "Loading...";
		//		playButton.className = "videobutton videoloading";
	}
	function videoToutOnMouseover(toutIdSuffix)
	{
		showElement('videoToutPlayButton' + toutIdSuffix);

	}

	function videoToutOnMouseout(toutIdSuffix)
	{
		hideElement('videoToutPlayButton' + toutIdSuffix);
	}
	
	
	function getVideoDuration(videoElement)
	{
		return videoElement.duration;
	}
	
	
	function updateVideoToutInfo()
	{
		var title = getVideoToutAsset("assetVideoTitle", selectedVideoToutIdSuffix);
		var desc = getVideoToutAsset("assetVideoDescription", selectedVideoToutIdSuffix);
		// note we'll use the iphone logo image.
		var logo = getVideoToutAsset("assetIphoneLogoImage", selectedVideoToutIdSuffix);
		
		document.getElementById('videoFeatureInfoTitle').innerHTML = title;
		document.getElementById('videoFeatureInfoDescription').innerHTML = desc;
		document.getElementById('videoFeatureInfoLogoImage').src = logo;
		
	}
	
	function playVideoTout(toutIdSuffix)
	{
		
		
		// First reset any previously selected videoTout
		if (selectedVideoToutIdSuffix.length > 0)
		{
			resetVideoToutToReadyToPlay(selectedVideoToutIdSuffix);
		}

		// Mark this video Tout as selected.
		selectedVideoToutIdSuffix = toutIdSuffix;

		// id is formated like videoToutSelectedT1 (1st video)
		showElement('videoToutSelected' + toutIdSuffix);
		hideElement('videoToutPlayButton' + toutIdSuffix);
		
		var videoToPlay = getVideoToutAsset('assetDesktopVideoUri',toutIdSuffix);
		//alert('trying to play: ' + videoToPlay);

		if (html5IsSupported == false)
		{
		
			swapQTMovie(videoToPlay);
			document.movie1.Play();
			
		}
		else
		{
			// We use the HTML 5 elements.
			videoFeature.poster = getVideoToutAsset('assetDesktopPoster',toutIdSuffix);
			playVideo(videoToPlay);
		}
		
		// Update the tout info.
		updateVideoToutInfo();
		
		return false;
	}
	
	function resetVideoToutToReadyToPlay(toutIdSuffix)
	{
		// id is formated like videoToutSelectedT1 (1st video)
		hideElement('videoToutSelected' + toutIdSuffix);
		showElement('videoToutPlayButton' + toutIdSuffix);
	}

function swapQTMovie(movieUri)
{
	document.movie1.Stop();
	document.movie1.SetURL(movieUri);
	document.movie1.Stop();
}

function myAddListener(obj, evt, handler, captures)
{

        if ( document.addEventListener )
        {
            obj.addEventListener(evt, handler, captures);
        }
        else
        {
            // IE
            obj.attachEvent('on' + evt, handler);
		}
}

function registerListener(eventName, objID, embedID, listenerFcn)
{
    var obj = document.getElementById(objID);

    if ( !obj )
        obj = document.getElementById(embedID);
    if ( obj )
        myAddListener(obj, eventName, listenerFcn, false);
}

function quicktimeEnded()
{
	// do nothing.
	//alert('qt ended');
}
	
