﻿
// ------------------------------------------------------------ Beans

var datepickerBean =
{
    isSelected: false,
    day: null,
    month: null,
    year: null
}

/*
 * The following structures will be created at runtime, one for each query string CatID parameter values.
 *
OndBean_<catsplit[i]>
{
    Catalog         : 'Canale10'

    suffix          : '<catsplit[i]>',

    maxVideos       : <maxsplit[i]>,

    pageCurrent     : 1,
    moreResults     : false,

    CatID: <catsplit[i]>
}
*/          

// ------------------------------------------------------------ 
// ------------------------------------------------------------ Categories Update
// ------------------------------------------------------------ 

$.manageAjax.create('ajaxManagedOndCategoryUpdate',
{ 
   // jQuery ajax options
   type: "GET",
   dataType : "text",
   cache: false,
   // manageAjax options
   queue: true,  
   cacheResponse: false 
});

function OndCategoryUpdate(OndBean, fadeEnabled)
{
    //-- disable pager --//
    
    var jpager = $('#OndPager_' + OndBean.suffix);

    if (jpager.length != 0)
    {
        jpager.find(".pagerLeft").unbind('click').addClass("disabled");
        jpager.find(".pagerRight").unbind('click').addClass("disabled");    
    }
                    
    //-- fade out pane --//

    var jpane = $('#OndPane_' + OndBean.suffix);

    if (jpane.length == 0)
        return;

    var jpaneFadeOutCompleted = false;
    var jpaneFadeOutCompletedRetry = 0;

    if (fadeEnabled)
        jpane.animate( {opacity:0}, 300, function() { jpaneFadeOutCompleted = true; } );
        //jpane.fadeOut(300, function() { jpaneFadeOutCompleted = true; } );

    //-- perform ajax request --//

    // e.g. http://localhost/Canale10/VideoEditAjaxService.aspx?action=SelectVideos&Catalog=Canale10&page=1&maxResults=30&CatID=9

    var _url = 'VideoEditAjaxService.aspx?action=SelectVideos' +
                                  '&Catalog=' + OndBean.Catalog +
                                  '&page=' + OndBean.pageCurrent + 
                                  '&maxResults=' + OndBean.maxVideos +
                                  '&CatID=' + OndBean.CatID;

    if (datepickerBean.isSelected)
        _url += "&dd=" + datepickerBean.day +
                "&mm=" + datepickerBean.month +
                "&yy=" + datepickerBean.year;

    //alert(_url);
                                  
    $.manageAjax.add('ajaxManagedOndCategoryUpdate',
    { 
       // jQuery ajax options
       url: _url,
       success: function(data)
       {
            var jsonClipsFromDB = null;
            
            try {
                eval('jsonClipsFromDB = ' + data);
			}
			catch(e) {
			}
            
            if (jsonClipsFromDB == null)
                ;
            else if (jsonClipsFromDB.status == 500)
                ;   //alert(jsonClipsFromDB.errorMsg);
            else
                if (fadeEnabled)
                {
                    var faux = function()
                    { 
                        if (jpaneFadeOutCompleted || jpaneFadeOutCompletedRetry == 10)
                        {
                            jpane.find('.ondvideo').css("display","none").find(".videoThumbnailImage").attr("src","Images/Home/empty.jpg");
                            OndCategoryUpdateCallback(OndBean, jsonClipsFromDB);
                            jpane.animate( {opacity:1}, 300 );
                            //jpane.fadeIn(300);
                        }
                        else                                                
                        {
                            jpaneFadeOutCompletedRetry++;
                            setTimeout(faux,100);
                        }
                    }
                    setTimeout(faux,100);
                }
                else
                {
                    jpane.find('.ondvideo').css("display","none").find(".videoThumbnailImage").attr("src","Images/Home/empty.jpg");
                    OndCategoryUpdateCallback(OndBean, jsonClipsFromDB);
                }
       },
       error: function(xmlHttpRequest, textStatus, errorThrown)
       { 
            // alert(erroThrown);
       },
       // manageAjax options
       abort: function()
       {
       }
    });    
}

function OndCategoryUpdateCallback(OndBean, jsonClipsFromDB)
{
    //-- thumbnails --//

    var clips = jsonClipsFromDB.videos;
    var jpane = $('#OndPane_' + OndBean.suffix);

    for(var i=0; i<clips.length; i++)
    {
        var jvideo = jpane.find(".ondvideo" + (i+1) + ":first");

        var serverID = parseInt(clips[i].StoreServerID);
        var folderID = parseInt(clips[i].StoreFolderID);
        
        // video object properties
        // notice that some might be null, they will be rendered by val() as an empty string

        jvideo.find(".videoVideoID").val(clips[i].VideoID);
        jvideo.find(".videoCatID").val(OndBean.CatID);
        jvideo.find(".videoTitle").val(clips[i].Title);
        jvideo.find(".videoDescription").val(clips[i].Description);        
        jvideo.find(".videoDate").val(clips[i].Date);
        jvideo.find(".videoSeconds").val(clips[i].Seconds);
        jvideo.find(".videoVideoNDFile").val(clips[i].VideoNDFile);        
        jvideo.find(".videoVideoLDFile").val(clips[i].VideoLDFile);
        jvideo.find(".videoVideoHDFile").val(clips[i].VideoHDFile);
        jvideo.find(".videoThumbFile").val(clips[i].ThumbFile);        
        jvideo.find(".videoThumbCount").val(clips[i].ThumbCount);        
        jvideo.find(".videoPictureFile").val(clips[i].PictureFile);        
        jvideo.find(".videoBackgroundFile").val(clips[i].BackgroundFile);        
        jvideo.find(".videoBannerFile").val(clips[i].BannerFile);        
        jvideo.find(".videoStoreServerID").val(serverID);        
        jvideo.find(".videoStoreFolderID").val(folderID);

        jvideo.find(".videoShareFacebookAnchor").attr('href', "http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.canaledieci.it%2FVideoShare.aspx%3FCatalog=" + OndBean.Catalog + "%26VideoID=" + clips[i].VideoID + "%26CatID=" + OndBean.CatID);
        jvideo.find(".videoShareEmailAnchor").attr('href', "mailto:?subject=Canale10&body=http://www.canaledieci.it/VideoShare.aspx?Catalog=" + OndBean.Catalog + "%26VideoID=" + clips[i].VideoID + "%26CatID=" + OndBean.CatID);

        // tooltip

        /* disabled
        jvideo.find(".videoTooltip").html(
                    "<div class='contents'>" +
                        (clips[i].Description == "" ? "<br />" : "") +
                        "<div class='label'>Title</div>" + clips[i].Title +
                        "<div class='label'>Duration</div>" + VisioTec.Utilities.DateTime.sec2str(parseInt(clips[i].Seconds)) +
                        (clips[i].description == "" ? "" : "<div class='label'>Description</div>" + clips[i].Description) +
                    "</div>");
        */
        
        // video label
        
        var labelText = "";
        if (clips[i].Title != null)
            labelText += "<div class='videoLabelSection'><span class='videoLabelBold'>" + clips[i].Title + "</span></div>";
        if (clips[i].Date != null)
            labelText += "<div class='videoLabelSection'>Pubblicato: " + clips[i].Date + "</div>";
        if (clips[i].Seconds != null)
            labelText += "<div class='videoLabelSection'>Durata: " + VisioTec.Utilities.DateTime.sec2str(parseInt(clips[i].Seconds)) + "</div>";

        jvideo.find(".videoLabelText").html(labelText);

        // thumbnail
                      
        var thumbUrl;

        if (clips[i].PictureFile != null)
            thumbUrl = 'http://' + TVConfig.getStoreServerAddressByID(serverID) + TVConfig.getImagesPathByID(folderID) + clips[i].PictureFile;
        else if (clips[i].ThumbFile != null)
            thumbUrl = 'http://' + TVConfig.getStoreServerAddressByID(serverID) + TVConfig.getThumbsPathByID(folderID) + clips[i].ThumbFile.replace("-XXX.", "-001.");
        else
            thumbUrl = "Images/ServerAdmin/noPicture.png";

        jvideo.find(".videoDefaultThumbnail").val(thumbUrl);
        jvideo.find(".videoThumbnailImage").attr("src",thumbUrl);
                
        // show
        
        jvideo.css("display","block");               
    }    

    //-- enable pager --//
    
    OndBean.more = jsonClipsFromDB.more;

    OndPagerUpdate(OndBean);
    
    // 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.
}

function activateOnDemandCategories()
{
    var cats = VisioTec.Utilities.Http.getQueryParameter('CatID');
    var maxv = VisioTec.Utilities.Http.getQueryParameter('maxVideos');

    var catsplit;
    var maxsplit;
    
    if (cats == null || maxv == null || cats == "" || maxv == "")
    {
        catsplit = [ 9,1,2,3,4 ];
        maxsplit = [ 30,7,7,7,7 ];
    }
    else
    {
        catsplit = cats.split(',');
        maxsplit = maxv.split(',');
    }
    
    for (var i=0; i<catsplit.length; i++)
    {
        eval(
            "OndBean_" + catsplit[i] + " = " +
            "{ " +
                "Catalog         : 'Canale10', " +

                "suffix          : '" + catsplit[i] + "', " +

                "maxVideos       : " + maxsplit[i] + ", " +

                "pageCurrent     : 1, " +
                "moreResults     : false, " +

                "CatID: " + catsplit[i] +
            " }"
            );

        OndCategoryUpdate(eval("OndBean_" + catsplit[i]), false);
    }
}

// ------------------------------------------------------------ 
// ------------------------------------------------------------ Pager
// ------------------------------------------------------------ 

function OndPagerUpdate(OndBean)
{
    var jpager = $('#OndPager_' + OndBean.suffix);
    
    if (jpager.length != 0)
    {    
        // pager appearance and behaviour
        
        jpager.find(".pagerText").text("Pagina " + OndBean.pageCurrent);

        if (OndBean.pageCurrent != 1)
            jpager.find(".pagerLeft").removeClass("disabled").click(function()
            {
                OndBean.pageCurrent--;
                OndCategoryUpdate(OndBean, true);
            });

        if (OndBean.more)
            jpager.find(".pagerRight").removeClass("disabled").click(function()
            {
                OndBean.pageCurrent++;
                OndCategoryUpdate(OndBean, true);
            });
            
            
        // hide siblings, show pager
        
        OndPagerShow(OndBean.suffix)
    }
}

function OndPagerShow(suffix)
{
    var jpager = $('#OndPager_' + suffix);

    // hide siblings, show pager
    
    jpager.siblings('.pager').css('display','none');
    jpager.css('display','block');
}

// ------------------------------------------------------------ 
// ------------------------------------------------------------ Video Info
// ------------------------------------------------------------ 

function publishVideoInfo(jvideo)
{
    $('#InfoPane_VideoInfo .infoContents').html(
                "<div class='section'><span class='bold'>Titolo: </span>" + jvideo.find(".videoTitle").val() + "</div>" +
                "<div class='section'><span class='bold'>Pubblicato: </span>" + jvideo.find(".videoDate").val() + "</div>" +
                "<div class='section'><span class='bold'>Durata: </span>" + VisioTec.Utilities.DateTime.sec2str(parseInt(jvideo.find(".videoSeconds").val())) + "</div>" +
                ( jvideo.find(".videoDescription").val().length == 0 ? "" : "<div class='section'>" + jvideo.find(".videoDescription").val() + "</div>" ));
     
    // anchor to video info pane is initially invisible (through css property visibility:hidden),
    // when the information is published we remove the style attribute to make it visible.
    $('#anchorVideoInfo').removeAttr('style'); //.css('visibility','visible');
}

function showVideoInfoPanel(withScroll)
{    
    try
    {
        var api = $("#infopanes").data("scrollable");

        if (withScroll)
            api.seekTo(1);
        else
            api.seekTo(1,0);
    }
    catch(e) {}
}

// ------------------------------------------------------------ 
// ------------------------------------------------------------ Thumbnail Rotation
// ------------------------------------------------------------ 

var thumbrotationBean  = 
{ 
    jvideo: null,

    ThumbFile: null,       // e.g. http://localhost:8080/Canale10/thumbs2/2010-07-16-p1-XXX.jpg
    ThumbCount: null,
    currentCount: 0,    

    videoDefaultThumbnail: null,
    
    updateThumbnailRef: null
}

function startThumbnailRotation(jvideo)
{ 
    //-- stop rotation, just in case --//
    
    if (thumbrotationBean.jvideo != null)
        stopThumbnailRotation();

    //-- set rotation parameters --//
    
    var serverID    = parseInt(jvideo.find('.videoStoreServerID').val());
    var folderID    = parseInt(jvideo.find('.videoStoreFolderID').val());
    var thumbFile   = jvideo.find(".videoThumbFile").val();
    var thumbCount  = parseInt(jvideo.find(".videoThumbCount").val());
 
    if (thumbFile == null || thumbCount == null)
        return;

    thumbrotationBean.ThumbCount = thumbCount
    thumbrotationBean.ThumbFile = "http://" + TVConfig.getStoreServerAddressByID(serverID) + TVConfig.getThumbsPathByID(folderID) + thumbFile;

    thumbrotationBean.jvideo = jvideo;
    thumbrotationBean.currentCount = 2;
    thumbrotationBean.videoDefaultThumbnail = jvideo.find(".videoDefaultThumbnail").val();

    //-- start rotation --//

    preloadThumbnails();

    updateThumbnail();
    thumbrotationBean.updateThumbnailRef = 
        setInterval( function() { updateThumbnail() }, 700);

    //-- tooltip --//

    //jvideo.find(".videoTooltip").css('display','block');
}

function stopThumbnailRotation()
{
    //-- tooltip --//

    //thumbrotationBean.jvideo.find(".videoTooltip").css('display','none');

    //-- stop rotation --//

    clearInterval(thumbrotationBean.updateThumbnailRef);    
    thumbrotationBean.jvideo.find('.videoThumbnailImage').attr("src",thumbrotationBean.videoDefaultThumbnail); 

    //-- clear rotation properties --//
    
    thumbrotationBean.jvideo = null;
    thumbrotationBean.updateThumbnailRef = null;
}

function preloadThumbnails() 
{
    var ThumbFile   = thumbrotationBean.ThumbFile;     
    var ThumbCount  = thumbrotationBean.ThumbCount;

    for(var i=1; i<=ThumbCount; i++)
    {
        count = i + '.';
        
        if (count.length == 2)
            count = "-00" + count;
        if (count.length == 3)
            count = "-0" + count;

        $("<img src='" + ThumbFile.replace("-XXX.", count) + "' />");
    } 
}

function updateThumbnail()
{    
    var jvideo      = thumbrotationBean.jvideo;   
    var ThumbFile   = thumbrotationBean.ThumbFile;     
    var count       = thumbrotationBean.currentCount + ".";        
    
    if (count.length == 2)
        count = "-00" + count;
    if (count.length == 3)
        count = "-0" + count;
    
    jvideo.find('.videoThumbnailImage').attr("src", ThumbFile.replace("-XXX.",count)); 
                   
    thumbrotationBean.currentCount++;    
    if (thumbrotationBean.currentCount > thumbrotationBean.ThumbCount)
        thumbrotationBean.currentCount = 1;
}

// ------------------------------------------------------------ 
// ------------------------------------------------------------ Playback and Commercial
// ------------------------------------------------------------ 

var playingVideo =
{
    spotVideoFile: null,
    spotSeconds: null,
    spotBackgroundFile: null,
    spotBannerFile: null,
    
    JVideo: null,
    VideoFile: null,
    Seconds: null,
    BackgroundFile: null,
    BannerFile: null
}

var preloadedSpot =
{
    spotVideoFile: null,
    spotSeconds: null,
    spotBackgroundFile: null,
    spotBannerFile: null
}

var preloadNextSpotRef = null;


function startPlayback(jvideo)
{ 
    // show boxplayer if it's hidden

    var jboxplayer = $('#BoxPlayer');
    if (jboxplayer != null && jboxplayer.css('display') == 'none')
    {
        $('#BoxInfo').css('visibility','hidden').css('display','block');
        jboxplayer.css('display','block');
    }

    // check whether spots are disabled for this video's category

    var videoCatID = parseInt(jvideo.find(".videoCatID").val());

    var noSpot = false;

    for (var j = 0; j < TVConfig.NoSpotCatIDs.length; j++)
        if (videoCatID == TVConfig.NoSpotCatIDs[j])
            noSpot = true;

    if (noSpot) {
        $f().play(chooseVideoFile(jvideo)).unmute();
        return;
    }
        
    // copy spot information and preload next spot
    
    playingVideo.spotVideoFile = preloadedSpot.spotVideoFile;
    playingVideo.spotSeconds = preloadedSpot.spotSeconds;
    playingVideo.spotBackgroundFile = preloadedSpot.spotBackgroundFile;
    playingVideo.spotBannerFile = preloadedSpot.spotBannerFile;

    clearTimeout(preloadNextSpotRef);
    preloadNextSpotRef = setTimeout(preloadNextSpot, 2000);
        
    // copy video information
    
    playingVideo.JVideo = jvideo;
    playingVideo.VideoFile = chooseVideoFile(jvideo);
    playingVideo.Seconds = null;
    playingVideo.BackgroundFile = null;
    playingVideo.BannerFile = null;

    var serverID = parseInt(jvideo.find('.videoStoreServerID').val());
    var folderID = parseInt(jvideo.find('.videoStoreFolderID').val());

    var Seconds = jvideo.find(".videoSeconds").val();            
    var BackgroundFile = jvideo.find(".videoBackgroundFile").val();
    var BannerFile = jvideo.find(".videoBannerFile").val();
    var imagesPath = "http://" + TVConfig.getStoreServerAddressByID(serverID) + TVConfig.getImagesPathByID(folderID);

    if (Seconds != null && Seconds != "" && Seconds != "null")
        playingVideo.Seconds = parseInt(Seconds);
    if (BackgroundFile != null && BackgroundFile.length > 4)
	    playingVideo.BackgroundFile = imagesPath + BackgroundFile;
    if (BannerFile != null && BannerFile.length > 4)
	    playingVideo.BannerFile = imagesPath + BannerFile;

    // set playlist and start playback

    if (playingVideo.spotVideoFile != null)
        $f().play([
            {
                url: playingVideo.spotVideoFile,
                isCommercial: true
            },
            {
                url: playingVideo.VideoFile
            }
        ]).unmute();
    else
        $f().play( playingVideo.VideoFile ).unmute();
}

function onBeginPlaying(clip)
{
    // stop timing

    clearInterval(spotTimingRef);

    // enable/disable controls and start timing

    if (clip.isCommercial)
    {
        ScrollTo(0, 116);
    
        this.getPlugin('controls').setAutoHide({enabled:false}).hide();
        
        var contentPlugin = this.getPlugin('content');
        var player = this;
        var seconds = playingVideo.spotSeconds;
        
        spotTimingRef = setInterval(function() { spotTiming(player, contentPlugin, seconds) }, 1000);
        setTimeout(function() { contentPlugin.css( {display:'block'} ) },1000);
    }
    else
    {
        this.getPlugin('controls').setAutoHide({enabled:true, mouseOutDelay:6000, fullscreenOnly:false, hideStyle:'fade'}).show();

        this.getPlugin('content').css( {display:'none'} );
    }
    
    // background

    tweakAppearance(clip.isCommercial);

}

function onFinishPlaying(clip)
{
    // stop timing

    //clearInterval(spotTimingRef);
    //this.getPlugin('content').css( {display:'none'} );

    // background
    
    //resetAppearance();    
}

function onErrorPlayer(errorCode, errorMessage)
{
    // stop timing
    
    clearInterval(spotTimingRef);
    this.getPlugin('content').css( {display:'none'} );
    
    // background
    
    resetAppearance();    
}

function ScrollTo(targetX, targetY)
{
    var done = false;

    try
    {
        scroll(targetX, targetY);
        done = true;
    }catch(e){}
    
    if (!done)
    try
    {
        window.scrollTo(targetX, targetY);
        done = true;
    }catch(e){}
}

function ScrollToObj(id)
{
    try{
        var objpos = ObjectPosition(id);
        ScrollTo(0, objpos[1]);
    }catch(e){}
}

function ObjectPosition(id)
{
    var obj = document.getElementById('PlayerWrapper');
    
    var curleft = 0;
    var curtop = 0;
    if (obj.offsetParent)
    {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

/* ------------------------------------------ */

var spotTimingRef = null;
function spotTiming(player, contentPlugin, videoSeconds)
{   
    var status = player.getStatus();
    
    if (status.state <= 2)
        contentPlugin.setHtml("<span class='contents'>Loading...</span>");
    else if (status.state <= 4)
    {
        var time = status.time;       
        var eta = null;
        
        if (time != null && videoSeconds != null)
            eta = Math.floor(videoSeconds - time);

         if (eta != null && eta >= 0)
            contentPlugin.setHtml("<span class='contents'>Video will start in " + eta + " seconds</span>");
     }
    else if (status.state == 5)
        contentPlugin.setHtml("<span class='contents'>Completed</span>");
}

/* ------------------------------------------ */

function tweakAppearance(isCommercial)
{          
    if ($("#SpotBackground").length != 0)
    {
        if (isCommercial)
        {
            if (playingVideo.spotBackgroundFile == null)
            {
                $('body').css('background-image','url(Images/Home/BkgGold.jpg)');
                $('#PageWrapper').css('background-image','url(Images/Home/BkgBodyTrans.png)');
                $('#BoxInfo').css('visibility','visible');
                $('#OndVideosWrapper').css('visibility','visible');

                $("#SpotBackground").css('display','none'); 
            }
            else
            {
                $('body').css('background-image','none');
                $('#PageWrapper').css('background-image','none');
                $('#BoxInfo').css('visibility','hidden');
                $('#OndVideosWrapper').css('visibility','hidden');
                
                $("#SpotBackground").css('display','none').attr('src', playingVideo.spotBackgroundFile).fadeIn(1000); 
            }

            if (playingVideo.spotBannerFile == null)
                $('#InfoPane_VideoInfo .infoMiniBanner').css('display','none');
            else
                $('#InfoPane_VideoInfo .infoMiniBanner').attr('src', playingVideo.spotBannerFile).css('display','block');
        }
        else
        {   
            publishVideoInfo( playingVideo.JVideo );
            showVideoInfoPanel(false);        
        
            $('body').css('background-image','url(Images/Home/BkgGold.jpg)');
            $('#PageWrapper').css('background-image','url(Images/Home/BkgBodyTrans.png)');
            $('#BoxInfo').css('visibility','visible');
            $('#OndVideosWrapper').css('visibility','visible');

            if (playingVideo.BackgroundFile == null)
                $("#SpotBackground").css('display','none')
            else
                $("#SpotBackground").css('display','none').attr('src', playingVideo.BackgroundFile).fadeIn(1000);
                
            if (playingVideo.BannerFile != null)
                $('#InfoPane_VideoInfo .infoMiniBanner').attr('src', playingVideo.BannerFile).css('display','block');
        }
    }
}

function resetAppearance()
{ 
    $('body').css('background-image','url(Images/Home/BkgGold.jpg)');
    $('#PageWrapper').css('background-image','url(Images/Home/BkgBodyTrans.png)');
    $('#BoxInfo').css('visibility','visible');
    $('#OndVideosWrapper').css('visibility','visible');

    $("#SpotBackground").css('display','none'); 

    /*
    var jbkg = $("#SpotBackground");

    if (jbkg.length != 0 && jbkg.css('display') != 'none')
    {
        jbkg.fadeOut(1000, function() {
            //$('body').css('background-image','url(Images/Home/BkgGold.jpg)');
            //$('#PageWrapper').css('background-image','url(Images/Home/BkgBodyTrans.png)');
            //$('#BoxInfo').css('visibility','visible');
            //$('#OndVideosWrapper').css('visibility','visible');
            //$("#SpotBackground").attr('src', 'Images/Home/empty.png');  // IE workaround
        });
    }
    
    //$('#InfoPane_VideoInfo .infoMiniBanner').attr('src', 'Images/Home/empty.png').css('border-color','Transparent')
    */
}

/* ------------------------------------------ */

// Very Important Notice.
// If an input element has value="", on FF val() will return "" whereas on IE it'll return "null"!
// So it seems we must check for xx != null, xx != "" and even xx != "null" (the latter two can be compressed with xx.length > 4)

function chooseVideoFile(jvideo)
{ 
    var VideoNDFile = jvideo.find(".videoVideoNDFile").val();
    var VideoLDFile = jvideo.find(".videoVideoLDFile").val();    
    var VideoHDFile = jvideo.find(".videoVideoHDFile").val();

    var serverID = parseInt(jvideo.find('.videoStoreServerID').val());
    var folderID = parseInt(jvideo.find('.videoStoreFolderID').val());
    var videosPath = "http://" + TVConfig.getStoreServerAddressByID(serverID) + TVConfig.getVideosPathByID(folderID);
    
    var _url = null;

    if ($("#fpOND").length != 0)
    {
        if (VideoNDFile != null && VideoNDFile.length > 4)
            _url = videosPath + VideoNDFile;
        else if (VideoLDFile != null && VideoLDFile.length > 4)
            _url = videosPath + VideoLDFile;
        else if (VideoHDFile != null && VideoHDFile.length > 4)
            _url = videosPath + VideoHDFile;
        
    }

    if ($("#fpHD").length != 0)
    {
        if (VideoHDFile != null && VideoHDFile.length > 4)
            _url = videosPath + VideoHDFile;
        else if (VideoNDFile != null && VideoNDFile.length > 4)
            _url = videosPath + VideoNDFile;
        else if (VideoLDFile != null && VideoLDFile.length > 4)
            _url = videosPath + VideoLDFile;

    }
    
    return _url;
}

/* ------------------------------------------ */

function preloadNextSpot()
{	
    preloadedSpot.spotVideoFile = null;
    preloadedSpot.spotSeconds = null;
    preloadedSpot.spotBackgroundFile = null;
    preloadedSpot.spotBannerFile = null;

	$.ajax(
	{
		type: "GET",
		url: "VideoSpotAjaxService.aspx?Catalog=" + TVConfig.Catalog + "&action=next&CatID=" + TVConfig.SpotCatID,
		dataType : "text",
		cache: false,
		success: function(response)
		{
			var jresponse = null;
			try {
				eval("jresponse = " + response);
			}
			catch(e) {
			}
			
			if (jresponse == null)
			    ;
			else if (jresponse.status == '500' || jresponse.status == '204' )
			    ;
			else
			{
			    var serverID = parseInt(jresponse.StoreServerID);
			    var folderID = parseInt(jresponse.StoreFolderID);

			    var imagesPath = "http://" + TVConfig.getStoreServerAddressByID(serverID) + TVConfig.getImagesPathByID(folderID);
			    var videosPath = "http://" + TVConfig.getStoreServerAddressByID(serverID) + TVConfig.getVideosPathByID(folderID);
 
                if (jresponse.VideoFile != null)
			        preloadedSpot.spotVideoFile = videosPath + jresponse.VideoFile;
                if (jresponse.Seconds != null)
			        preloadedSpot.spotSeconds = jresponse.Seconds;
                if (jresponse.BackgroundFile != null)
    			    preloadedSpot.spotBackgroundFile = imagesPath + jresponse.BackgroundFile;
                if (jresponse.BannerFile != null)
	    		    preloadedSpot.spotBannerFile = imagesPath + jresponse.BannerFile;

			    // preload images

			    if (preloadedSpot.spotBackgroundFile != null)
			        $("<img src='" + preloadedSpot.spotBackgroundFile + "' />");
			    if (preloadedSpot.spotBannerFile != null)
			        $("<img src='" + preloadedSpot.spotBannerFile + "' />");
			}
		},
		error: function (xmlHttpRequest, textStatus, errorThrown)
		{ 
		}    
	});    
}

preloadNextSpot();

// ------------------------------------------------------------ 
// ------------------------------------------------------------ Document Ready
// ------------------------------------------------------------ 

$(document).ready(function()
{   
    /*
     * Activate OnDemand Categories
     */

    var jdatepicker = $('#OndVideosWrapper').find('#datepicker');
    if (jdatepicker.length != 0)
        jdatepicker.datepicker({
        inline: true,
            dateFormat: 'dd-mm-yy',
			showOn: 'both',
			buttonImage: 'Images/Home/calendar.png',
			buttonImageOnly: true,
			
			onSelect: function(dateText, inst) { 
			    var split = dateText.split('-');
			    datepickerBean.day = split[0];
			    datepickerBean.month = split[1];
			    datepickerBean.year = split[2];
			    
			    /* at the moment, datepicker is enabled only for TG */
			    datepickerBean.isSelected = true;
			    OndBean_10.pageCurrent = 1;
			    OndCategoryUpdate(OndBean_10, true);
			}
		});

    /*
     * Activate OnDemand Categories
     */

    activateOnDemandCategories();
    
    /*
     * Set thumbnail rotation, show video details, playback video
     */
    
    $(".ondvideo .videoThumbnail").each(function()
    {
        // mouseenter/leave: thumbnail rotation

        $(this).mouseenter(function() {
            var jvideo = $(this).parent();   
            VisioTec.Utilities.SynchQueue.Add("ThumbFx", function() { startThumbnailRotation( jvideo ) });
        }).mouseleave(function() {
            VisioTec.Utilities.SynchQueue.Add("ThumbFx", function() { stopThumbnailRotation() });
        });

        // mouse click: start playback + show details
                
        $(this).click(function() {
            startPlayback( $(this).parent() );
        });
    }); 
    
    /* disabled
     *
    $(".ondvideo .videoInfoIcon").each(function()
    {
        $(this).click(function() {
            publishVideoInfo( $(this).parent() );
            showVideoInfoPanel(true);
        });

        $(this).mouseenter(function() {
            publishVideoInfo( $(this).parent() );
        });
    }); 
    */
    
});
