/* Customer a/c URLS(high performance)*/
//var flightStartURL = 'http://'+ window.location.host + '/partner/query?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&contentType=LiveStream&expires=1362676856571&fields=labels&signature=7oYWWVqzIWwUuhNt55QP6Vwigg35O6%2F7bdG4zHq04tk';
//var recommendedURL = 'http://'+ window.location.host + '/partner/query?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&expires=1362677040682&label%5Ba%5D=Recommended&orderBy=uploadedat%2Cdesc&signature=G9ZfOEye5yQMH3aMoNz0K35H7krx1SIUf6znRyhza80';
//var archiveURL     = 'http://'+ window.location.host + '/partner/query?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&expires=1362677129919&label%5Ba%5D=Archive&orderBy=uploadedat%2Cdesc&signature=6MH7Suxhs22NnPgVekC4jwdSnGhgpjo33m5WzytEmbI';
//var highlightsURL  = 'http://'+ window.location.host + '/partner/query?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&expires=1362677196630&label[a]=Highlights&orderBy=uploadedat%2Cdesc&signature=bfydnIQFJYnS4mxlXmvbr2N3G5LJ90Nb62biLoL6FgU';
//var mostviewdURL   = 'http://'+ window.location.host + '/api/analytics?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&date=all&expires=1362677443731&format=xml&granularity=total&limit=18&method=account.videoTotals&orderby=plays&signature=qh7B5s7d9R25aI4iKImbuTp%2FTETOdWKr%2FQwxDJ%2BqxFQ';

//Customer a/c URLS(5 min expiry)
var flightStartURL = 'http://'+ window.location.host + '/partner/query?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&contentType=LiveStream&expires=1300173678795&fields=labels&signature=2QAX%2FeLIGF8cGzU%2F9r%2FgKYMnyhTkQGkhTawt%2FSUYzFQ';
var recommendedURL = 'http://'+ window.location.host + '/partner/query?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&expires=1300880972481&label%5Ba%5D=Recommended&orderBy=uploadedat%2Cdesc&status=live&signature=YkiSPRYcmDAyj7xtbHPnZ1t5Kockz8ZFC7S3GyXYuVw';
var archiveURL     = 'http://'+ window.location.host + '/partner/query?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&expires=1300881028726&label%5Ba%5D=Archive&orderBy=uploadedat%2Cdesc&status=live&signature=ZyyZhtcm46ULsREN5dULEMlvv78EphJw7lj6KYByBm0';
var highlightsURL  = 'http://'+ window.location.host + '/partner/query?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&expires=1300881084915&label%5Ba%5D=Highlights&orderBy=uploadedat%2Cdesc&status=live&signature=G9M%2BsEk5R6EkOrfUx04P0ZuolbdPG7q9SlrWwqE%2BI1I';
var mostviewdURL   = 'http://'+ window.location.host + '/api/analytics?pcode=t0OGs6fYfne9Gu5se1bX--fX12rS&date=all&expires=1300173919749&format=xml&granularity=total&limit=18&method=account.videoTotals&orderby=plays&signature=vZXWJOgFk5dRNifD61MU8SbVgPp4G006CeU768Do05Y';

/* URLs for testing in our account(high performance)
var flightStartURL = 'http://'+ window.location.host + '/partner/query?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&contentType=LiveStream&expires=64412446631&fields=labels&orderby=flightStartTime&signature=M7zX%2FLK0FvIpeMa46ohB2Ra%2BaBWwf21bfMQYT3YJtAQ';
var recommendedURL = 'http://'+ window.location.host + '/partner/query?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&expires=1362329811474&label[a]=Recommended&orderBy=uploadedat%2CDESC&signature=TXFHy%2BEaHslP9CdzOMCxC4RtlWi5iRYI2tU0QQjIPD8';
var archiveURL     = 'http://' + window.location.host + '/partner/query?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&expires=1362331201257&label[a]=Archive&orderBy=uploadedAt%2Cdesc&signature=CaM6Xt0ZN%2FlSIJdI3BBMVI1Mzmbv78Z9ooCZBojswZ4';
var highlightsURL  = 'http://' + window.location.host + '/partner/query?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&expires=1362331333294&label[a]=Highlights&orderBy=uploadedAt%2Cdesc&signature=07H4erEtDz9bd3O5rvo%2FxreWibSZ7eKEeZHhCWE8%2F3U';
var mostviewdURL   = 'http://' + window.location.host + '/api/analytics?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&date=all&expires=1362000106818&format=xml&granularity=total&limit=18&method=account.videoTotals&orderby=plays&signature=8PtOOQa3Ufa5jaG7zpMCTY2EDpEQZWY%2BmDOHHt3Dv3U';
*/
//URLs for testing in our account(5 min expiry)
//var flightStartURL = 'http://'+ window.location.host + '/partner/query?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&contentType=LiveStream&expires=1300172580101&fields=labels&signature=8nyySYeThQqUaBgAyDDvIgb7HuwM4LVLno7%2BQDOFkkQ';
//var recommendedURL = 'http://'+ window.location.host + '/partner/query?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&expires=1300172978419&label%5Ba%5D=Recommended&orderBy=uploadedat%2Cdesc&signature=6GjRb%2FxySDUmpjWShD4fQDG4IbzElF8%2B3kuKKL5wMrQ';
//var archiveURL     = 'http://'+ window.location.host + '/partner/query?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&expires=1300173081050&label%5Ba%5D=Archive&orderBy=uploadedat%2Cdesc&signature=MEBxyQoatm3E9wksNIzLZJcipVLBYnV3H2ANNrOFJp4';
//var highlightsURL  = 'http://'+ window.location.host + '/partner/query?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&expires=1300172892883&label%5Ba%5D=Highlights&orderBy=uploadedat%2Cdesc&signature=DqC5j2jqXnVz1D%2FJvi2s1hX%2FTIAc%2Fn0y4xiDwU8JkD0';
//var mostviewdURL   = 'http://'+ window.location.host + '/api/analytics?pcode=NscWk6DpWjRj7LpsNXZqvmb2cgph&date=all&expires=1300173375293&format=xml&granularity=total&limit=18&method=account.videoTotals&orderby=plays&signature=1HHwLCjP%2FsUt907O0AIn%2FGoVxpXPIOXftB7gS7d6HIQ';

var arrItems = new Array();
var isPageLoad = true;
var arrEmbeds = new Array();
var arrflightStart = new Array();
var apiReadyCalled = 1;

jQuery(document).ready(function($) {    
    setData(flightStartURL);
    setResponseData(recommendedURL,$("#recommendedTable"));
    setResponseData(highlightsURL,$("#highlightsTable"));
    setResponseData(archiveURL,$("#archiveTable"));
    setResponseData(mostviewdURL,$("#mostViewedTable"));
});

function setVideo(){
    var currentURL = window.location.toString();
    var arrParams = [];
    arrParams = currentURL.split("html");
    if(arrParams[1] != "")
    {
        arrParams     = currentURL.split("ooid=");
        var newEmbedCode = arrParams[1];
        document.getElementById("sportFivePlayer").setEmbedCode(newEmbedCode);
    }
    else
    {       
        document.getElementById("sportFivePlayer").setEmbedCode("RiNzVyMTrguBdDc4nBoYHpUFkScK4PKv");
    }
}
function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

function playVideo(embedCode) {
    document.getElementById("sportFivePlayer").setEmbedCode(embedCode);
    window.scrollTo(0,50);
}

function receiveOoyalaEvent(playerId, eventName, eventArgs) {    
    switch(eventName) {
        case "companionAdsReady":
            getCompAds(eventArgs);
            break;
        case "embedCodeChanged":
            showTitleDesc(playerId,eventArgs);
            break;
        case "apiReady" :
            if(apiReadyCalled == 1){
                apiReadyCalled = 0;
                setVideo();
            }
            break;
    }
}

function showTitleDesc(playerId,eventArgs) {
    $("#videoPanel_title").html(eventArgs.title);
    $("#videoPanel_description").html(eventArgs.description);
}

function setData(url) {
    jQuery.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        success: function(xml){
            extractLiveMatches(xml,$("#gallery-wrap"));
        },
        error: function(){
            $("#CarouselArea").html("No live broadcasts active or scheduled at this time.");
        }
    });
}

function setResponseData(url,table){
    jQuery.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        success: function(xml){
            showResponse(xml,table);
        }
    });
}


function setupGallery(){
    // Gallery
    if($("#gallery").length){
        // Variables aren't use properly due to Webkit
        var totalImages = $("#gallery > li").length,
        imageWidth = $("#gallery > li:first").outerWidth(true),
        totalWidth = imageWidth * totalImages,
        visibleImages = Math.round($("#gallery-wrap").width() / imageWidth),
        visibleWidth = visibleImages * imageWidth,
        stopPosition = (visibleWidth - totalWidth);
        if($("#gallery").position().left == 0)
            $("#gallery-prev").html('<img src="SliderSource/prev1.png" alt="" border="0">');

        if(totalImages > 4)
        {
            //  setButtons();
            $("#gallery-next").html('<img src="SliderSource/next.png" alt="" border="0">');
            $("#gallery").width(totalWidth);
            $("#gallery-prev").click(function(){
                if($("#gallery").position().left < 0 && !$("#gallery").is(":animated"))
                {
                    $("#gallery").animate({
                        left : "+=" + visibleWidth + "px"
                    });

                    setButtons();
                    if(($("#gallery").position().left == 0) ||(($("#gallery").position().left + visibleWidth ) == 0))
                        $("#gallery-prev").html('<img src="SliderSource/prev1.png" alt="" border="0">');
                }
                return false;
            });

            $("#gallery-next").click(function(){
                if($("#gallery").position().left > stopPosition && !$("#gallery").is(":animated"))
                {
                    $("#gallery").animate({
                        left : "-=" + visibleWidth + "px"
                    });

                    setButtons();
                    if(($("#gallery").position().left - visibleWidth )  < stopPosition)
                        $("#gallery-next").html('<img src="SliderSource/next1.png" alt="" border="0">');
                }
                return false;
            });
        }
        else
        {
            $("#gallery-prev").html('<img src="SliderSource/prev1.png" alt="" border="0">');
            $("#gallery-next").html('<img src="SliderSource/next1.png" alt="" border="0">');
        }
    }

}

function setButtons(){
    $("#gallery-prev").html('<img src="SliderSource/prev.png" alt="" border="0">');
    $("#gallery-next").html('<img src="SliderSource/next.png" alt="" border="0">');
}


function extractLiveMatches(xml,div) {

    var currentTime =  parseInt((new Date()).getTime()/1000);    
    var ul          = $('<ul class="galleryLive" id="gallery"></ul>')
    var finishedAiringCnt = 0;
    if( ($(xml).length > 0 )|| ($(xml).find('item').length >0))
    {        
        var arrOrderedVideos = [];
        $(xml).find('item').each(function(){
            var resp        = new response();
            resp.title       = $(this).find('title').text();
            resp.embedcode   = $(this).find('embedCode').text();
            resp.desc        = $(this).find('description').text();
            resp.thumbnail   = $(this).find('thumbnail').text();
            resp.status      = $(this).find('status').text();
            resp.label       = $(this).find('labels').find('label').text();
            resp.content     = $(this).find('content_type').text();
            resp.flightStart = parseInt($(this).find('flightStartTime').text());
            resp.flightEnd   = parseInt($(this).find('flightEndTime').text());
            arrOrderedVideos.push(resp);
        });
            arrOrderedVideos.sort(function(a,b){
            return a.flightStart - b.flightStart
            });
        for(var j=0; j <arrOrderedVideos.length ; j++)
        {
            var flightStart          = arrOrderedVideos[j]['flightStart'];
            var flightEnd            = arrOrderedVideos[j]['flightEnd'];
            d = new Date(flightStart*1000)
            var flightStartStr = $.format.date(d,"dd.MM.yyyy HH:mm");
            var arr = new Array();
            arr = flightStartStr.split(".");
            var timeformat ;
            timeformat = toDoubleDigit(arr[0]) + "." + toDoubleDigit(arr[1]) + "." + toDoubleDigit(arr[2]) + "" ;
            flightStartStr = timeformat ;

            if(flightEnd < currentTime)
            {

            }
            else if(!isNaN(flightStart))
            {
                var title       = arrOrderedVideos[j]['title'];
                var embedCode   = arrOrderedVideos[j]['embedcode'];
                var thumbnail   = arrOrderedVideos[j]['thumbnail'];
                var status      = arrOrderedVideos[j]['status'];
                var label       = arrOrderedVideos[j]['label']; 
                if(title.length > 48){
                   title = title.substring(0,45) + "...";
                }
                var thumbdivHTML = '';
                if (thumbnail != null && thumbnail != "") {
                    thumbdivHTML = '<a href="javascript:playVideo(\'' + embedCode + '\')" ><img src="' + thumbnail  +'" alt="ThumbImg001" height="56" width="94" ' +
                    'border="0"/></a>';
                }
                else
                {
                    thumbdivHTML = '<a href="javascript:playVideo(\'' + embedCode + '\')" ><img src="images/NoVideo.jpg" alt="ThumbImg001" height="56" width="94" border="0"/></a>';
                }
            

                var titleAndTimeDiv = $('<span class="TextWhite">'+flightStartStr +'</span><br><span class="TextYellow">'+title+'</span>' );

                var thumbDiv = $('<div class="videoThumb"></div>').html(thumbdivHTML);     //videothumb
                var titleDiv = $('<div class ="CarouselThumbTitle"></div>').html(titleAndTimeDiv);    //title

                var innerData = $('<li class="liveVideoList"></li>');                //single element
                var innerHtmlData = $('<div class="liveVideoDiv"></div>');


                if((flightStart < currentTime))
                {
                    var liveBadge = $('<div class="LiveBadge"></div>').html('<img border="0" title="Live Match" alt="Live Match" src="images/live-badge.png">');
                    innerHtmlData = innerHtmlData.append(liveBadge);
                }

                var arrLabels = new Array();
                arrLabels = label.split("/");
                for(var k=0;k<arrLabels.length;k++)
                {
                    if( arrLabels[k] == 'premium' || arrLabels[k] == 'Premium')
                    {
                        var premium = $('<div class="PremiumBadge"></div>').html('<img border="0" title="Premium Match" alt="Premium Match" src="images/premium-badge.png">');
                        innerHtmlData = innerHtmlData.append(premium);
                    }
                }

                innerHtmlData = innerHtmlData.append(thumbDiv).append(titleDiv);
                ul = ul.append(innerData.append(innerHtmlData));

            }
            else
            {
                finishedAiringCnt++;
                if(finishedAiringCnt == $(xml).find('item').length)
                    $("#CarouselArea").html("No live broadcasts active or scheduled at this time.");
            }
        

            div.append(ul);

        }
    }
    else
        $("#CarouselArea").html("No live broadcasts active or scheduled at this time.");

    setupGallery();
}


function showResponse(xml,table)
{
    var arrVideoItems = [];
   
    if(table.selector == "#mostViewedTable")
    {
        $(xml).find('result').find('account').find('video').each(function()
        {
            var resp        = new response();
            resp.title       = $(this).find('title').text();
            resp.embedcode   = $(this).find('embedCode').text();
            arrEmbeds.push(resp.embedcode);
        //            //arrVideoItems.push(resp);
        });
        getThumbnail();
        return;
    }
    else
    {
        $(xml).find('item').each(function()
        {
            var resp        = new response();
            var currentTime =  parseInt((new Date()).getTime()/1000);

            resp.flightStart =  parseInt($(this).find('flightStartTime').text());
            resp.flightEnd   = parseInt($(this).find('flightEndTime').text());
            if(resp.flightEnd < currentTime)
            {

            }
            else if(!isNaN(resp.flightStart))
            {
                resp.title       = $(this).find('title').text();
                resp.embedcode   = $(this).find('embedCode').text();
                resp.desc        = $(this).find('description').text();
                resp.thumbnail   = $(this).find('thumbnail').text();
                resp.status      = $(this).find('status').text();
                resp.label       = $(this).find('labels').find('label').text();
                resp.content     = $(this).find('content_type').text();
                if( resp.content !="LiveStream")
                {
                     arrVideoItems.push(resp);
                }
               
            }

        });
    }
    if(table.selector == "#recommendedTable"){
        arrRecommended = arrVideoItems;
    }
    else if(table.selector == "#highlightsTable"){
        arrHighlights  = arrVideoItems;
    }
    else if(table.selector == "#archiveTable"){
        arrArchive     = arrVideoItems;
    }
    else if(table.selector == "#mostViewedTable"){
        arrMostViewed  = arrVideoItems;
    }
    currentPageID = 1;
    toHTML(1,table,arrVideoItems);
}


