var numAudioItems = 28;
var numVideoItems = 18;
var numSoundItems = 2;

var mediaPlayer;            // toggles between audio and video
var audioPlayer = null;
var videoPlayer = null;
var imagePlayer = null;
var flashMediaPlayer = null;
var updateProgress = true;
var playingElement = null;
var isStarted = false;
var isUsingFlash = false;
var flashDuration = -1;
var flashSeek = -1;
var currentFilename = null;
var isAudio = true;
var videoInfoTimeout = null;
var currentDuration = 0;
var mediaChecker;
var flashInstalled = false;
var randomButtonDisabled = false;
var nextItemId = "";

function gratuitousRandomization()
{
	if (!randomButtonDisabled)
	{
		$('#randomButton').attr('src', 'images/randombuttondown.png');
		var tabChoice = Math.random();
		if (tabChoice < 0.7)
		{
			var anum = '#audioitem' + Math.floor(Math.random() * numAudioItems + 1);
			if (playingElement != null)
				while (anum == playingElement.id) anum = '#audioitem' + Math.floor(Math.random() * numAudioItems + 1);
			$('a.musictab').click();
			nextItemId = anum;
		}
		else if (tabChoice < 0.9)
		{
			var vnum = '#videoitem' + Math.floor(Math.random() * numVideoItems + 1);
			if (playingElement != null)
				while (vnum == playingElement.id) vnum = '#videoitem' + Math.floor(Math.random() * numVideoItems + 1);
			$('a.videotab').click();
			nextItemId = vnum;
		}
		else
		{
			var snum = '#sounditem' + Math.floor(Math.random() * numSoundItems + 1);
			$('a.soundtab').click();
			nextItemId = snum;
		}
		setTimeout("delayedItemClick()", 600);
		if (navigator.userAgent.indexOf('MSIE') == -1)
		{
			var clickAudio = $("#randomClickAudio").get(0);
			if (clickAudio) clickAudio.play();
		}
	}
}

function delayedItemClick()
{
	$(nextItemId).click();
	restoreRandomButton();
}

function restoreRandomButton()
{
	if (!randomButtonDisabled)
	{
		randomButtonDisabled = true;
		setTimeout("restoreRandomButton()", 500);
	}
	else
	{
		$('#randomButton').attr('src', 'images/randombuttonwait.png');
		setTimeout("enableRandomButton()", 5000);
	}
}

function enableRandomButton()
{
	$('#randomButton').attr('src', 'images/randombuttonup.png');
	randomButtonDisabled = false;
}

function playMedia(fileName, imageLoc, description, isAudioFile, container)
{
    // prevent spurrious playlist selections
    if (currentFilename == fileName) 
    {
        // but if the playlist item was selected again, ensure that it is playing
        if ($('#play').button().text() == 'play')
        {
            $('#play').button().click();
        }
        return;
    }
    
	if (mediaChecker != null) clearInterval(mediaChecker);

    currentFilename = fileName;
    
    // avoid closing the info panel if it was previously on a timer
    if (videoInfoTimeout != null)
    {
        clearTimeout(videoInfoTimeout);
    }
    
    // change background of previous and current playlist selections
    if (playingElement != null)
    {
        playingElement.style.backgroundColor = "";
    }
    playingElement = container;
    playingElement.style.backgroundColor = "#333333";
    
    // put controls in visual state to play
    if ($('#play').button().text() == "pause")
    {
        $('#play').button().click();
    }
    
    // if HTML5 video, make sure it is not playing
    if (navigator.userAgent.indexOf('MSIE') == -1 && videoPlayer != null) 
    {
        videoPlayer.pause();
    }
    
    // if Flash, make sure it is stopped
    if (isUsingFlash)
    {
        if (flashMediaPlayer.getConfig().state != "IDLE")
        {
            flashMediaPlayer.sendEvent('STOP');
        }
        flashDuration = -1;
    }
    
    // remember whether we're playing audio or video
    isAudio = isAudioFile;
    
    // show the info for the current selection
    if ( ! $('#infoContainer').is(':hidden') )
    {
        $('#infoContainer').slideToggle(200);
    }
    if (description != null)
    {
        $('#infoHolder').html(description);
        $('#infoContainer').slideToggle(200);
        $('#infoContainer').css('visibility', '');
        if (!isAudio)
        {
            // for video, timeout the info panel
            videoInfoTimeout = setTimeout(function() { $('#infoContainer').slideToggle(200); }, 5000);
        }
    }
    else
    {
    	$('#infoHolder').html('');
    	$('#infoContainer').css('visibility', 'hidden');
    }
    
    // put the player in a visual loading state
    isStarted = false;
    isUsingFlash = flashInstalled;	// always use Flash if it is available
    if (mediaPlayer != null && mediaPlayer.currentTime > 0) mediaPlayer.currentTime = 0;
    $("#progressbar").slider("option", "value", 0);
    $('#playBigBtn').button("option", "label", "Loading...");
    $('#playBigBtn').button("option", "disabled", true);
    
    // play the media content
    if (isAudio)
    {
        fileName = fileName.substring(0, fileName.length - 4);  // prepare for mp3 or ogg
        mediaPlayer = audioPlayer;
        playAudio(fileName, imageLoc);
    }
    else
    {
        mediaPlayer = videoPlayer;
        playVideo(fileName, imageLoc);
    }
    
    mediaChecker = setInterval("checkPlayState()", 3000);
}

function playAudio(fileName, imageLoc)
{
    if (!isUsingFlash && audioPlayer != null && audioPlayer.canPlayType) 
    {
        var canPlayOgg = audioPlayer.canPlayType("audio/ogg") != "no" && audioPlayer.canPlayType("audio/ogg") != "";
        var canPlayMP3 = audioPlayer.canPlayType("audio/mpeg") != "no" && audioPlayer.canPlayType("audio/mpeg") != "";
        if (canPlayMP3)
        {
            audioPlayer.src = fileName + ".mp3";
            $('#play').button().click();
        }
        // uncomment this when/if I transcode the audio to ogg as well as mp3
        /*else if (canPlayOgg)
        {
            audioPlayer.src = fileName + ".ogg";
            $('#play').button().click();
        }*/
        else
        {
            // web browser cannot play MP3 or OGG files using HTML5
            isUsingFlash = true;
        }
    }
    else
    {
        // web browser cannot support any sort of HTML5 audio tag
        isUsingFlash = true;
    }
    if (isUsingFlash)
    {
         if (!flashInstalled)
         {
   			alert("Your browser does not support HTML5 audio and video, and you do not have the free Flash player, either." +
   				" Sorry, this file cannot be played.");
         }
        flashDuration = -1;
        flashMediaPlayer.sendEvent('LOAD', {file:fileName + '.mp3'});
        $('#play').button().click();
    }
    
    if (imageLoc != null)
    {
        imagePlayer.src = imageLoc;
    }
    imagePlayer.style.display = "";
    videoPlayer.style.display = "none";
    if (flashInstalled) showFlashPlayer(false);
}

function playVideo(fileName, imageLoc)
{
    if (imageLoc == null)
    {
        imageLoc = "images/posterframe.png";
    }
    
    isUsingFlash = navigator.userAgent.indexOf('MSIE') != -1;	// force flash video on IE
    var isYouTube = fileName.indexOf("youtube.com") != -1;
    var canPlayH264 = false;
    if (!isUsingFlash && videoPlayer != null && videoPlayer.canPlayType && !isYouTube) 
    {
        canPlayH264 = videoPlayer.canPlayType("video/mp4") != "no" && videoPlayer.canPlayType("video/mp4") != "";
        if (canPlayH264)
        {
            if (flashInstalled) showFlashPlayer(false);
            imagePlayer.style.display = "none";
            videoPlayer.style.display = "";
            videoPlayer.poster = imageLoc;
            videoPlayer.src = fileName;
            $('#play').button().click();
        }
    }
    if (!canPlayH264 || isYouTube)
    {
   	    if (!flashInstalled)
        {
              alert("Your browser does not support HTML5 audio and video, and you do not have the free Flash player, either." +
    		" Sorry, this file cannot be played.");
        }
        isUsingFlash = true;
        imagePlayer.style.display = "none";
        showFlashPlayer(true);
        flashDuration = -1;
        if (isYouTube)
        {
            flashMediaPlayer.sendEvent('LOAD', {'file':fileName, 'image':imageLoc, 'provider':'youtube'});
        }
        else
        {
            flashMediaPlayer.sendEvent('LOAD', {'file':fileName, 'image':imageLoc, 'provider':'video'});
        }
        setTimeout("$('#play').button().click()", 500);
    }
}

function isFlashNeeded()
{
    var canPlayVideo = false;
    if (videoPlayer != null && videoPlayer.canPlayType) 
    {
        canPlayVideo = audioPlayer.canPlayType("video/mp4") != "no" && audioPlayer.canPlayType("video/mp4") != "";
    }
    
    var canPlayAudio = false;
    if (audioPlayer != null && audioPlayer.canPlayType) 
    {
        canPlayAudio = audioPlayer.canPlayType("audio/mpeg") != "no" && audioPlayer.canPlayType("audio/mpeg") != "";
    }
    
    return !canPlayVideo && !canPlayAudio;
}

function showFlashPlayer(doShowIt)
{
    var playerDiv = $('#flashMediaPlayer').get(0);
    if (doShowIt)
    {
        playerDiv.style.width = '480px';
        playerDiv.style.height = '320px';
        flashMediaPlayer.width = 480;
        flashMediaPlayer.height = 320;
    }
    else
    {
        playerDiv.style.width = '1px';
        playerDiv.style.height = '1px';
        flashMediaPlayer.width = 1;
        flashMediaPlayer.height = 1;
    }
}
      
function playerReady(obj) 
{
    flashMediaPlayer = getFlashPlayer(obj.id);
    flashMediaPlayer.addModelListener("time", "onFlashPlayProgress");
    flashMediaPlayer.addModelListener("state", "onFlashStateChange");
}

function getFlashPlayer(gid) 
{
    if(navigator.appName.indexOf("Microsoft") != -1) return window[gid];
    else return window.document[gid];
}

function onPlayProgress()
{
    if (updateProgress)
    {
    	currentDuration = mediaPlayer.duration;
        if (mediaPlayer.currentTime > 0 && !isStarted)
        {
            // hide loading visual
            togglePlayOverlay(false);
            isStarted = true;
        }
        percentComplete = mediaPlayer.currentTime / mediaPlayer.duration * 100;
        $("#progressbar").slider("option", "value", percentComplete);
        $('#timePosition').html(getPrettyTime(parseInt(mediaPlayer.currentTime)));
        var timeRemaining = mediaPlayer.duration - mediaPlayer.currentTime;
        if (timeRemaining > 0)
        {
        	$('#timePositionRemaining').html("-" + getPrettyTime(parseInt(timeRemaining)));
        }
        else
        {
        	$('#timePositionRemaining').html("-0:00");
        }
    }
}

function onFlashPlayProgress(obj)
{
    if (updateProgress)
    {
		currentDuration = obj.duration;
        if (obj.position > 0 && !isStarted)
        {
            // hide loading visual
            togglePlayOverlay(false);
            isStarted = true;
            flashDuration = obj.duration;
        }
        if (flashDuration > 0)
        {
            if (flashSeek != -1)
            {
                flashMediaPlayer.sendEvent('SEEK', flashSeek * flashDuration);
                flashSeek = -1;
            }
            else
            {
                percentComplete = obj.position / obj.duration * 100;
                $("#progressbar").slider("option", "value", percentComplete);
                $('#timePosition').html(getPrettyTime(parseInt(obj.position)));
       			var timeRemaining = obj.duration - obj.position;
        		if (timeRemaining > 0)
        		{
    		    	$('#timePositionRemaining').html("-" + getPrettyTime(parseInt(timeRemaining)));
          		}
    		    else
          		{
    		    	$('#timePositionRemaining').html("-0:00");
          		}
            }
        }
    }
}

function resetPositionValues()
{
	$("#progressbar").slider("option", "value", 0);
	$('#timePosition').html("0:00");
	$('#timePositionRemaining').html("-" +   getPrettyTime(currentDuration));
}

function getPrettyTime(secs)
{
    if (secs < 10) 
    {
        return "0:0" + parseInt(secs);
    }
    else if (secs < 60) 
    {
        return "0:" + parseInt(secs);
    }
    else
    {
        var minsPart = parseInt(secs / 60);
        var secsPart = parseInt(secs % 60);
        if (secsPart < 10)
        {
            return minsPart + ":0" + secsPart;
        }
        return minsPart + ":" + secsPart;
    }
}

function onFlashStateChange(obj)
{
    if (obj.newstate == 'COMPLETED')
    {
        onEnd();
    }
}

function onEnd()
{
    $('#stop').button().click();
    togglePlayOverlay(true);
    if (!isUsingFlash)
    {
        imagePlayer.style.display = "";
        videoPlayer.style.display = "none";
    }
    
    // select next item div
    if (playingElement != null && playingElement.id != null && playingElement.id.length > 9)
    {
        var itemKind = playingElement.id.substring(0, 9);   // assumes all item ids have same length
        var itemNumber = playingElement.id.substring(9, playingElement.id.length);
        itemNumber++;
        var newItem = itemKind + itemNumber;
        $('#' + newItem).click();
    }
}

function mouseOverPlaylist(el)
{
    //el.style.backgroundImage = "url('images/cell1.png')";
    el.style.backgroundColor = "#333333";
}

function mouseOutPlaylist(el)
{
    if (playingElement == null || el.id != playingElement.id)
    {
        //el.style.backgroundImage = "";
        el.style.backgroundColor = "";
    }
}

function togglePlayOverlay(doShow)
{
    $('#playBigBtn').button("option", "label", "Play");
    $('#playBigBtn').button("option", "disabled", false);
    if (doShow)
    {
        $('#playerOverlay').css('display', '');
    }
    else
    {
        $('#playerOverlay').css('display', 'none');
    }
}

function onCanPlayMedia()
{
	if (mediaPlayer != null) mediaPlayer.play();
}

function onCanPlayThroughMedia()
{
	if (mediaPlayer != null) mediaPlayer.play();
}

function checkPlayState()
{
	// BUG FIX FOR iPAD
	if (mediaPlayer.networkState == 1 && mediaPlayer.readyState == 0)
	{
		mediaPlayer.load();
 		mediaPlayer.play();
	}
	else if (mediaPlayer.readyState == 0)
	{
		mediaPlayer.play();
	}
	else if (mediaPlayer != null && $('#play').button().text() == 'pause')
	{
		if (mediaPlayer.networkState == 2 && mediaPlayer.readyState == 2)
		{
			mediaPlayer.load();
 			mediaPlayer.play();
		}
		else
		{
			clearInterval(mediaChecker);
		}
	}
	else
	{
		clearInterval(mediaChecker);
	}
}

