﻿/* v 1.2 rev.c
- ls thumbnail rotation is still disabled, but url has been updated to LS API 2.0
*/

/* v 1.2 rev.b
- start/stop thumbnail rotation is now managed through a FIFO queue
- ls thumbnail rotation has been disabled due to poor performance
- 'Images/Default/videoImgEmpty.jpg' has been updated to 'Images/TV/videoImgEmpty.jpg'
*/

/* v 1.1
- added cmdKey support
*/

/* v 1.0
*/

// ------------------------------------------------------------ Channels management

$.manageAjax.create('ajaxManagedOndChannelUpdate',
{ 
   // jQuery ajax options
   type: "GET",
   dataType : "text",
   cache: false,
   // manageAjax options
   queue: true,  
   cacheResponse: false 
});

function ondChannelUpdate(ondChannel)
{
    //-- clear thumbnails and disable pagers --//

    var jpanel = $(ondChannel.panelID);
    
    for(i=1; i<=ondChannel.maxresults; i++)
        jpanel.find(".ondVideo" + i + ":first").css("display","none").find(".videoImg:first").attr("src","Images/TV/videoImgEmpty.jpg");

    jpager = jpanel.find(".channelPanelPager");
    jpager.find(".pagerLeft").addClass("disabled").unbind('click');
    jpager.find(".pagerRight").addClass("disabled").unbind('click');

    //-- perform ajax request --//

    var _url = 'TVClipsService.aspx?page=' + ondChannel.page + 
                                 '&maxresults=' + ondChannel.maxresults +
                                 '&catalog=' + ondChannel.catalog;                                                                 
    if (ondChannel.cdn == 'yt')
        _url += '&cdn=yt' + (ondChannel.tags == null ? '' : '&tags=' + ondChannel.tags) + (ondChannel.cmdKey == null ? '' : '&cmdKey=' + ondChannel.cmdKey)
    else // if (ondChannel.provider == 'ls')
        _url += '&cdn=ls&playlistID=' + ondChannel.playlistID;

    $.manageAjax.add('ajaxManagedOndChannelUpdate',
    { 
       // jQuery ajax options
       url: _url,
       success: function(data)
       {
            var jsonClipsFromDB = (new Function("return " + data))();
            ondChannelUpdateCallback(ondChannel, jsonClipsFromDB);
       },
       error: function(xmlHttpRequest, textStatus, errorThrown)
       { 
       },
       // manageAjax options
       abort: function()
       {
       }
    });    
}

function ondChannelUpdateCallback(ondChannel, jsonClipsFromDB)
{
    if (jsonClipsFromDB.status == 500)
        return;
        
    var clips = jsonClipsFromDB.bean.clips;

    var jpanel = $(ondChannel.panelID);

    //-- video pager --//
    
    jpager = jpanel.find(".channelPanelPager");
    
    jpager.find(".pagerText").text("Pagina " + ondChannel.page);

    if (ondChannel.page != 1)
        jpager.find(".pagerLeft").removeClass("disabled").click(function()
        {
            ondChannel.page--;
            ondChannelUpdate(ondChannel);
        });

    if (jsonClipsFromDB.more)
        jpager.find(".pagerRight").removeClass("disabled").click(function()
        {
            ondChannel.page++;
            ondChannelUpdate(ondChannel);
        });

    // Note.
    // In Javascript, if you assign a reference object to another object, you actually copy it by reference.
    // A JSON object is a reference object.

    //-- thumbnails --//
    
    for(var i=1; i<=clips.length; i++)
    {
        var jroot = jpanel.find(".ondVideo" + i + ":first");
        jroot.css("display","block");
        
        jroot.find(".videoImg").attr("src",clips[i-1].thumbnailUrl);        
        jroot.find(".videoInfo").text(clips[i-1].title);
        jroot.find(".videoTitle").val(clips[i-1].title);
        jroot.find(".videoDescription").val(clips[i-1].description);
        jroot.find(".videoGuid").val(clips[i-1].guid);
        
        jroot.find(".videoChannel").val(ondChannel.channelName);           
        jroot.find(".videoCDN").val(ondChannel.cdn);           

        var duration = clips[i-1].duration;
        if ((duration != null) && (ondChannel.cdn == 'ls'))
            duration /= 1000;
        jroot.find(".videoDuration").val(duration);

    }    
}

// ------------------------------------------------------------ 
// ------------------------------------------------------------ Thumbnail Rotation
// ------------------------------------------------------------ 

var ThumbRotationVars  = 
{ 
    jimg: null, 

    cdn: null,      // 'yt', 'ls'
    guid: null,     // ls clip guid, yt video id
    channel: null,  // ls channel name

    thumbNr: 0,
    
    updateThumbnailRef: null
}

function preloadThumbnails()
{
    if (ThumbRotationVars.cdn == 'ls')
    {
        return; // disabled
    
        for(var thumbNr=1; thumbNr<=4; thumbNr++)
        {
            var thumbURL = "http://x" + ThumbRotationVars.channel + "x.channel-api.livestream-api.com/2.0/thumbnail?" + 
                           "id=" + ThumbRotationVars.guid +
                           "&time=" + (thumbNr * 40);
            //var thumbURL = "http://clipthumbnail.api.livestream.com/?" +
            //               "clipID=" + ThumbRotationVars.guid + 
            //               "&channel=" + ThumbRotationVars.channel +
            //               "&time=" + (thumbNr * 40);

            $("<img src='" + thumbURL + "' />");
        }   
            
    }        
    //-- YT video thumbnail --//
    else if (ThumbRotationVars.cdn == 'yt')      
    {  
        for(var thumbNr=1; thumbNr<=3; thumbNr++)
        {
            var thumbURL = 'http://i.ytimg.com/vi/' + ThumbRotationVars.guid + '/' +  thumbNr + '.jpg';

            $("<img src='" + thumbURL + "' />");
        }   
    }
}

function updateThumbnail()
{    
    //-- LS OnDemand video thumbnail --//
    // http://clipthumbnail.api.livestream.com/?clipID=flv_dfb71da2-f13b-4962-8f25-95bd6d3e4bd2&channel=tvsalsa&time=10
    if (ThumbRotationVars.cdn == 'ls')
    {    
        return; // disabled

        var jimg = ThumbRotationVars.jimg;   
        var thumbURL = "http://x" + ThumbRotationVars.channel + "x.channel-api.livestream-api.com/2.0/thumbnail?" + 
                       "id=" + ThumbRotationVars.guid +
                       "&time=" + (ThumbRotationVars.thumbNr * 40);
        //var thumbURL = "http://clipthumbnail.api.livestream.com/?" +
        //               "clipID=" + ThumbRotationVars.guid + 
        //               "&channel=" + ThumbRotationVars.channel +
        //               "&time=" + (ThumbRotationVars.thumbNr * 40);
             
        jimg.attr("src",thumbURL);
            
        ThumbRotationVars.thumbNr++;    
        if (ThumbRotationVars.thumbNr > 4)
            ThumbRotationVars.thumbNr = 1;    
            
    }        
    //-- YT video thumbnail --//
    else if (ThumbRotationVars.cdn == 'yt')      
    {  
        var jimg = ThumbRotationVars.jimg;        
        var thumbURL = 'http://i.ytimg.com/vi/' + ThumbRotationVars.guid + '/' +  ThumbRotationVars.thumbNr + '.jpg';
        jimg.attr("src",thumbURL); 
                       
        ThumbRotationVars.thumbNr++;    
        if (ThumbRotationVars.thumbNr > 3)
            ThumbRotationVars.thumbNr = 1;
    }
}

function startThumbnailRotation(jimg)
{ 
    //-- Stop rotation, just in case --//
    
    if (ThumbRotationVars.jimg != null)
        stopThumbnailRotation(ThumbRotationVars.jimg);

    //-- Get/Set parameters and start rotation --//

    var interval = 800;
    
    var cdn         = jimg.find("~ .videoCDN").val();
    var guid        = jimg.find("~ .videoGuid").val();
    var channel     = jimg.find("~ .videoChannel").val();
    var title       = jimg.find("~ .videoTitle").val()    
    var description = jimg.find("~ .videoDescription").val()    
    var duration    = VisioTec.Utilities.DateTime.sec2str( parseInt(jimg.find("~ .videoDuration").val()) );

    ThumbRotationVars.jimg = jimg;
    ThumbRotationVars.cdn = cdn;
    ThumbRotationVars.guid = guid;
    ThumbRotationVars.channel = channel;
    
    if (cdn == 'ls')
        ThumbRotationVars.thumbNr = 1;
    else //if (cdn == 'yt')
        ThumbRotationVars.thumbNr = 3;  // la thumb di default coincide con la 2

    preloadThumbnails();
    ThumbRotationVars.updateThumbnailRef = 
        setInterval( function() { updateThumbnail() }, interval);

    //-- CSS hilight of video information --//

    jimg.css("width",120+40);        
    jimg.css("height",90+30);        
    jimg.css("left",-20);        
    jimg.css("top",-15);        

    jimg.find("~ .videoInfo").css("display","none");
    
    jttip = jimg.find("~ .videoTooltip");    
    jttip.html("<div class='contents'>" +
                    (description == "" ? "<br />" : "") +
                    "<div class='label'>Title</div>" + title +
                    "<div class='label'>Duration</div>" + duration +
                    (description == "" ? "" : ("<div class='label'>Description</div>" + description) +
               "</div>"));

    // <bug fix>
    if (mediaPlayer.shown != 'si')
    // </bugfix>   
    jttip.show(); //fadeIn(500);    
}

function stopThumbnailRotation(jimg)
{
    //-- Stop rotation --//

    clearInterval(ThumbRotationVars.updateThumbnailRef);    

    //-- Restore CSS --//

    jimg.find("~ .videoTooltip").css("display","none");

    jimg.css("width",120);        
    jimg.css("height",90); 
    jimg.css("left",0);        
    jimg.css("top",0);        
           
    jimg.find("~ .videoInfo").css("display","block");
}

// ------------------------------------------------------------ 
// ------------------------------------------------------------ Document Ready
// ------------------------------------------------------------ 

$(document).ready(function()
{
    /*
     * Fill OnDemand channels
     */
     
    for(var i=0; i<ondActiveChannels.length; i++)
        ondChannelUpdate(ondActiveChannels[i]);
        
    /*
     * Set thumbnail rotation and playback functions
     */
    
    $(".ondVideo .videoImg").each(function()
    {
        // thumbnail rotation

        $(this).mouseenter(function() {
            var jimg = $(this);
            VisioTec.Utilities.SynchQueue.Add("ThumbFx", function() { startThumbnailRotation(jimg); })
        }).mouseleave(function() {
            var jimg = $(this);
            VisioTec.Utilities.SynchQueue.Add("ThumbFx", function() { stopThumbnailRotation(jimg) })
        });
        
        // playback
        
        $(this).click(function() {
            var _cdn = $(this).find("~ .videoCDN").val();
            var _title = $(this).find("~ .videoTitle").val();
            var _duration = parseInt($(this).find("~ .videoDuration").val());
            var _guid = $(this).find("~ .videoGuid").val();
            var _channel = $(this).find("~ .videoChannel").val();

            if (_cdn == 'yt')
                switchSource("yt", { videoid: _guid, title: _title });
            else //if (_cdn == 'ls')
                switchSource("ls", { channelName: _channel, guid: _guid, title: _title, duration: _duration });
        });
    }); 
});
