var vTest = document.createElement('video')
var isHTML5Video = true
var isiOS = navigator.userAgent.match(/iP[ad|od|hone]+/i) != null;
var isFirefox = navigator.userAgent.match(/Firefox/i) != null;
var video = document.getElementById('videoPlayer')
//video.addEventListener('play', playOrPauseVideo, false)
//video.addEventListener('pause', playOrPauseVideo, false)

if (vTest.play) {
    if (video) {
        video.addEventListener('timeupdate', updateProgressBar, false)
        video.addEventListener('loadeddata', videoCanPlay, false)
        video.addEventListener('error', failed, false)
    }
} else {
    isHTML5Video = false
}


jQuery(document).ready(function($) {
  
    if ( ! isHTML5Video) 
        $('#videoPlayer, #videoControls').remove() 
    
    $('.grid li:nth-child(3n)').addClass('third')
    
    
    $('.grid.films li').append('<div class="play"></div>').css('zIndex', '20')
    $('.grid.films li').hover(function() {
        $(this).find('.caption').animate({
            bottom: 0
        }, 500)
    }, function() {
        $(this).find('.caption').animate({
            bottom: -50
        }, 500)
    })
    $('.grid.films li').click(function(e) {
        var videoURL = $(this).find('a').attr('href')
        
        if (isFirefox) {
            // Firefox needs an ogg version of the video
            videoURL = videoURL.substring(0, videoURL.indexOf('.mov')) + '.theora.ogv'
        }
        
        if (isHTML5Video)
            $('#videoPlayer').attr('src', videoURL)
        else {
            $('#player').flash({
                swf: 'media/films/ch-player.swf?movie=' + videoURL.substr(12),
                id: 'flashVideoPlayer',
                params: {
                    wmode: 'transparent',
                    allowFullScreen: true,
                    autoplay: true
                },
                height: 600,
                width: 950
            })
        }    
        hideGrid()
        e.preventDefault()
    })
    
    $('#gridNav.illustrations a').click(function() {
        var gridIndex = $('#gridNav.illustrations a').index($(this))
        var totalGrids = $('.grid.illustrations').length
        var nextGridIndex = (gridIndex + 1 == totalGrids) ? 0 : gridIndex + 1
        
        $('#gridNav a').removeClass('current')
        $('#gridNav a').eq(gridIndex).addClass('current')
        
        $('.grid.illustrations').stop(true, true).fadeOut(500)
        $('.grid.illustrations').eq(gridIndex).delay(700).fadeIn(500)
    })

    $('.grid.illustrations a').fancybox({
        transitionIn:	'elastic',
    	transitionOut:	'elastic',
    	overlayOpacity: 0.9,
    	overlayColor: '#111',
    	opacity: true
    })
    
    $('#viewGrid.enabled').live('click', function() {
        showGrid()
        return true
    })
    
    $('#playVideo').live('click', function() {
        playOrPauseVideo()
    })
    
    $('#seekBarHandle').draggable({
        containment: 'parent',
        axis: 'x',
        cursor: 'crosshair',
        drag:  function() {
            var delta = $(this).position().left / 360 * video.duration
            video.currentTime = delta
        }
    })
});

hideGrid = function() {
    $('.loading').fadeIn('fast')
    var count = $('.grid li').length - 1
    $('.grid li').each(function(index, elem) {
        $('.grid li').eq(count - index).delay(index * 200).fadeOut(500, function() {
            if (index == count) {
                $('#viewGrid').addClass('enabled').fadeIn(500)
                
                $('#player').delay(count * 500).stop(true,true).fadeIn('slow')
                
                if (isHTML5Video && !isiOS) {
                    $('#videoControls').delay(count * 500).stop(true,true).fadeIn('slow')
                    if (video.readyState >= 1)
                        video.currentTime = 0
                    playOrPauseVideo()
                }
            }
        })
        
    })
}

showGrid = function() {
    $('#player').stop(true,true).fadeOut('slow', function() {
        $('.grid li').each(function(index, elem) {
            $(elem).delay(index * 200).fadeIn(500)
        })
        
        if (isHTML5Video && !isiOS) {
            video.pause()
            $('#videoControls').fadeOut('slow', function() {
                $(this).find('.loading').show()
            })
        } else {
            $('#flashVideoPlayer').remove()
        }
        $('#viewGrid').removeClass('enabled').fadeOut(500)
    })
}

playOrPauseVideo = function() {
    if (video.paused) {
        $('#playVideo em').text('pause')
        video.play()
    } else {
        $('#playVideo em').text('play')
        video.pause()
    }
}
function updateProgressBar() {
    var delta = video.currentTime/video.duration * 360
    $('#seekBarBg').css('width', delta)
    $('#seekBarHandle').css('left', delta)
}
function videoCanPlay() {
    //alert('media loaded')
    $('.loading').fadeOut('fast')
}
function failed(e) {
   // video playback failed - show a message saying why
   switch (e.target.error.code) {
     case e.target.error.MEDIA_ERR_ABORTED:
       alert('You aborted the video playback.');
       break;
     case e.target.error.MEDIA_ERR_NETWORK:
       alert('A network error caused the video download to fail part-way.');
       break;
     case e.target.error.MEDIA_ERR_DECODE:
       alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
       break;
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
       alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');
       break;
     default:
       alert('An unknown error occurred.');
       break;
   }
 }
