﻿/*
Title: Advent site - videos page javascript
Author: josh@josgherdes.com
*/

// Define global variables
var searchYoutube = {}; 
var displayVideos = {};
var callYoutube = {};
var totalVideos = 0;
var startIndex = 1;
var maxResults = 48; // Max of 50 allowed
        
$(document).ready(function() {

    // Method used to pull youtube video data with search filter
    searchYoutube = function(filter) {
        // Reset counters
        totalVideos = 0;
        startIndex = 1;
        
        // Reset previous and next buttons
        $('a.youtube-videos-prev').hide();
        $('a.youtube-videos-next').hide();
        $('span.youtube-videos-divider').hide();
        
        // Call youtube API to retrive video feed
        callYoutube(filter);
    }
    
    callYoutube = function(filter) {
        // Set the base query
        var query = 'http://gdata.youtube.com/feeds/api/users/adventmd/uploads?v=2&alt=json-in-script&format=5&orderby=published&start-index=' + startIndex + '&max-results=' + maxResults;
        
        // Check if search given and set search parameters
        if(filter != null) {
            filter = filter.replace(/ /gi, '+');
            filter = escape(filter);
            query += '&q=' + filter;
        }

        // Add callback parameter for proper json return data
        query += '&callback=?';
        
        // Clear previous videos
        $('div#youtube-videos').empty();
        
        // Call youtube API to get videos
        $.getJSON(query, function(data, textStatus){ 
        
            // Determine the total videos returned
            totalVideos = data.feed.openSearch$totalResults.$t;
           
            // Determine if Next should be shown               
            if ( totalVideos - startIndex > maxResults )
                $('a.youtube-videos-next').show();
            else
                $('a.youtube-videos-next').hide();
                     
            // Determine if Previous should be shown
            if ( startIndex > maxResults )
                $('a.youtube-videos-prev').show();
            else
                $('a.youtube-videos-prev').hide();
                
            // Determine if Divider should be shown    
            if ($('a.youtube-videos-next').is(':visible') && $('a.youtube-videos-prev').is(':visible'))
                $('span.youtube-videos-divider').show();
            else
                $('span.youtube-videos-divider').hide();
                
            // Display the video data                
            displayVideos(data);
            
            // Add click event to video links
            $('a[rel*=youtube]').click(function() {
                showVideo($(this).attr('href'), false);
                return false;
            });
            
            data = null; // Destroys the reference to the data
        });
    }
    
    displayVideos = function(data) {
        // Reset counter
        var count = 0;
        
        // Loop through data to display videos
        $.each(data.feed.entry, function(id, item){
            // Increment the counter
            count++;
            
            // Get title, if available
            var title = '';
            if(item.media$group.media$title.$t != null)
                title = item.media$group.media$title.$t;
            
            // Get description, if available
            var description = '';
            if(item.media$group.media$description.$t != null)
                description = item.media$group.media$description.$t;   
            
            // Get video url
            var playerUrl = item.media$group.media$content[0].url;

            // Get video thumbnail url
            var thumbnail = item.media$group.media$thumbnail[1].url;

            // Get video duration, and convert to minutes and seconds
            var duration = item.media$group.media$content[0].duration
            var durationSeconds = duration % 60;
            var durationMinutes = Math.floor((duration % 3600 ) /60);
            durationSeconds = durationSeconds.toString();
            if(durationSeconds.length < 2)
                durationSeconds = '0' + durationSeconds;
            duration = durationMinutes + ':' + durationSeconds;
            
            // Get posted date
            var published = item.published.$t;
            var publishedDate = published.substring(0, 10).replace(/-/gi, '/');
            var publishedTime = published.substring(12, 19);
            published = new Date(publishedDate + ' ' + publishedTime);
            var publishedDisplay = '<span class="videoPublishedLabel">Posted:</span>&nbsp;' + (published.getMonth()+1) + '/' + published.getDate() + '/' + published.getFullYear();
            
            // Create page elements
            var video = $(document.createElement('img')).attr('class', 'videoThumb').attr('src', thumbnail).attr('alt', '');
            var label = $(document.createElement('div')).attr('class', 'videoTitle').html(title);
            var link =  $(document.createElement('a')).attr('class', 'videoLink').attr('href', playerUrl).attr('rel', 'youtube').attr('title', title).append(video).append(label);;
            var listItem = $(document.createElement('div')).attr('class', 'video').append(link);
            var labelDuration = $(document.createElement('div')).attr('class', 'videoDuration').html(duration);
            listItem.append(labelDuration);
            var labelPublished = $(document.createElement('div')).attr('class', 'videoPublished').html(publishedDisplay);
            listItem.append(labelPublished);
            
            // Add to page
            $('div#youtube-videos').append(listItem);  

            // Add spacers after every 3rd video (for row alignment)
            if(count % 3 == 0)
                $('div#youtube-videos').append($(document.createElement('div')).attr('class', 'videoSpacer'));
        });
    }
    
    // Setup previous button
    $('a.youtube-videos-prev').click(function() {
        // Set new start index
        startIndex -= maxResults;
        
        // Get new videos
        callYoutube($('#searchBox').val());
        
        return false;
    });
    
    // Setup next button
    $('a.youtube-videos-next').click(function() {
        // Set new start index
        startIndex += maxResults;
        
        // Get new videos
        callYoutube($('#searchBox').val());
        
        return false;
    });
    
    // Setup search button
    $('#searchButton').click(function() {
        searchYoutube($('#searchBox').val());
        return false;
    });
    
    $('#searchBox').keypress(function(e) {
        var evt = (e) ? e : window.event;
        var key = (evt.keyCode) ? evt.keyCode : evt.which;

        if(key == 13) {
            searchYoutube($('#searchBox').val());
            evt.returnValue = false;
            return false;
        }
    });
    
    // Call init for page
    searchYoutube();
});