
//======================================
// constants
//======================================
var NBR_VIDEOS_PER_PAGE = 9



// When DOM is ready
$(document).ready(function () {
    // Re-size panes Related Videos and Description
    $(".scrollable").scrollable({size: 1, clickable:false, keyboard:false}).navigator();
    $("ul.tabs").tabs("div#tab_results > div.panes > div" , { initialIndex: 0 } );
    equalHeightResize($(".resize"));
   
    // Tabs from jquery tools
    $(function() {
        $("ul.tabs").tabs("div.panes > div", {
            initialIndex: _tabs
        });
    });
    
    // Sub_nav click
    $('.sub_nav a').live("click",
      function() {
        var myId = $(this).parent().attr("id");
        for (var i=0; i < allPlaylists.length; i++) {
            var playlist = allPlaylists[i];
            if( playlist.id == myId ) {
                // Switch subnav select playlist
                var txt = $('span.select').html();
                $('span.select').replaceWith('<a href="" title="' + txt + '">' + txt + '</a>');
                var txt = $('#'+playlist.id + ' a').html();
                $('#'+playlist.id + ' a').replaceWith('<span class="select">' + txt + '</span>');

                /* true : reset pagination */
                displayVideo(playlist["videos"], myId, true);
                $('.data-videolist .' + mainVideoId).addClass('current');
                break;
            }
        }
        return false;
    });

    // NAV click
    $('#nav > li > a').live("click",
      function() {
        var classe = $(this).parent().attr("class");
        var title =  $(this).parent().attr("title");

        $('li.select .sub_nav').hide();   // Hide the selected
        $('.sub_nav > li > span.select').replaceWith('<a title="' + $('span.select').html() + '" href="">' + $('span.select').html() + '</a>');
        $('#nav > li.select > span').replaceWith('<a title="' + $('#nav > li.select > span').html() + '" href="">' + $('#nav > li.select > span').html() + '</a>');
        $('#nav .select').removeClass('select'); // Remove the red box ( facultatif )
        $(this).parent().children('ul').show(); // Display the clicked one
        $(this).parent().addClass('select'); // Add the red box
        //$(this).replaceWith('<span>' + $(this).html() + '</span>'); // Replace the a with span

        if(classe.search("allchannel") != -1) {
            displaySpecial(_BRAND,mainVideoId, true);
        }
        else if(classe.search("first") != -1) {
            displaySpecial(_BRAND + ':featured',mainVideoId, true);
        }
        else {
            displaySpecial(_BRAND + ':channel:' + title,mainVideoId, true);
        }
        $('.data-videolist .' + mainVideoId).addClass('current');
        return false;
    });
    
    //======================================
    // use allPlaylists and videos data to initalise the page
    //======================================
    initializeData();
    
    $('.sub_nav li:last-child').addClass("last");
    $('#nav li:last-child').addClass("last");
});

/* ======================================
 *  Get playlist by regex in referenceId
 * 
 * @param regEx The regular expression to sue to match in the refenrenceId
 * @return The playlist, or null if there is no match
 * 
 * ======================================*/
function getPlaylistByRegExInReferenceId(regEx) 
{
    for (var i=0; i < allPlaylists.length; i++) 
    {
        var playlist = allPlaylists[i];
        if(playlist.referenceId.search(regEx) != -1)
        {
            return playlist;
        }
    }
    return null;
}

/* ======================================
 *  Get playlist by id
 * 
 * @param playlistId The playlist id
 * @return The playlist, or null if there is no match
 * 
 * ======================================*/
function getPlaylist(playlistId) 
{
    for (var i=0; i < allPlaylists.length; i++) 
    {
        var playlist = allPlaylists[i];
        if(playlist.id == playlistId)
        {
            return playlist;
        }
    }
    return null;
}


/* ======================================
 *  Get the first playlist the specified video is in.
 * 
 * @param videoId The video id to find
 * @return The first playlist found containing the specified video, or null if no one found.
 * 
 * ======================================*/
function getFirstPlaylistVideoIsIn(videoId) 
{
    for (var i=0; i < allPlaylists.length; i++) 
    {
        var playlist = allPlaylists[i];
        
        for(var j=0; j < playlist["videos"].length; j++ ) 
        {
            var video = playlist["videos"][j];
            if( videoId == video.id ) 
            {
                return playlist;
            }
        }
    }
    return null;
}

/* ======================================
 *  Get the page a video is at (zero index based!) from a videos array
 * 
 * @param videos The video array
 * @param videoId The id of the video
 * @param nbrPerPage The number of video per page. Default to NBR_VIDEOS_PER_PAGE
 * @return The page where videoId is located. Return "0" if not found.
 * 
 * ======================================*/
function getPageForVideo(videos, videoId, nbrPerPage) 
{
    if(typeof nbrPerPage == 'undefined') nbrPerPage = NBR_VIDEOS_PER_PAGE;
    
    var pos = -1;
    for(var i=0; i < videos.length; i++) 
    {
        pos++;

        var video = videos[i];
        if( videoId == video.id ) 
        {
            return Math.floor(pos / nbrPerPage);
        }
    }
    
    return 0;
}

/* ======================================
 *  Initialize all with initial data
 * ======================================*/
function initializeData() {
     if(!_paylistID || _GET['id'] == null) { // Its a fresh without _GET data
        if (_GET['id'] == null) { // Its the homepage , i want the "special feature" content
            playlist = getPlaylistByRegExInReferenceId(_BRAND + ":featured");
            if(!playlist)
            {
                return;    
            }
            displayPlaylist(playlist, true, false);
            
            displayVideo(playlist["videos"], mainVideoId);
        }
        else{
            playlist = getFirstPlaylistVideoIsIn(mainVideoId);
            
            // playlist not found: show featured playlist instead
            if(!playlist)
            {
                 playlist = getPlaylistByRegExInReferenceId(_BRAND + ":featured");
            }
            displayPlaylist(playlist, false, true);
            
            displayVideo(playlist["videos"], mainVideoId);
        } 
    }
    // specified playlist
    else {

        playlistRequested   = getFirstPlaylistVideoIsIn(_GET['id']);
        playlistVideoCoikie = getFirstPlaylistVideoIsIn(_videoID);

        if(playlistRequested['id'] != playlistVideoCoikie['id'])
            _paylistID = playlistRequested['id'];

        var classe = $('#' +  _paylistID).parent().attr("class");
        if(classe == 'sub_nav' && _GET['id'] != null) {   // specific playlist
            playlist = getPlaylist(_paylistID);
            if(!playlist)
            {
                return;
            }
        
            displayPlaylist(playlist , false ,true);
            
            displayVideo(playlist["videos"], mainVideoId);

        }
        else {
            displayPlaylist( _paylistID , false, false);
            var title = $('#' + _paylistID).attr("title");
            if(_paylistID == 0 && _GET['id'] != null) { //  all channel
                type = _BRAND;
                displaySpecial(type, mainVideoId);
            }
            else if (title && _GET['id'] != null) {   // section level 1 have title ( hack )
                type = _BRAND + ":channel:" + title;
                displaySpecial(type, mainVideoId);
            }
            else { // featured
                type = _BRAND + ":featured";
                displaySpecial(type, mainVideoId);
            }
         }
    }
    return false;
}

/*
 * Generic function to merge list of videos from playlist
 * type = Regex
 * id   = id of the current video
 * resetPage = reset pagination page to 0? Default to "false"
 */
function displaySpecial( type, id, resetPage ) {
    
    // default values
    if (typeof resetPage == 'undefined') resetPage = false;

    var all = [];
    for (var i=0; i < allPlaylists.length; i++) {
        var referenceId = new String(allPlaylists[i]["referenceId"]);
        if( referenceId.search( type ) != -1 ) {
            var videos = allPlaylists[i]["videos"];
            $.merge(all,videos);
        }
    }

    displayVideo(all, id, resetPage);
}

/*
 *  Select the menu with the specific playlist
 *  playlist    = id or playlist json object
 *  homepage    = (boolean)
 *  subnav      = (boolean)
 */
function displayPlaylist( playlist , homepage , subnav)
{
    var id;
    var isSpecialPlaylist = false;
    if(typeof playlist == "object") {
        id = playlist.id;
        
    } else {
        id = playlist;
        playlist = getPlaylist(playlist);
        if(!playlist){
            subnav = false;
        }
    }
    
    // check if we're dealing with a special playlist, like the "featured" one
    if(playlist){
        isSpecialPlaylist = playlist.referenceId.search(_BRAND + ":channel:") == -1;
    }

    if(homepage || isSpecialPlaylist) {
        $('#nav #' + id).addClass("select"); // Homepage => Featured video selected, or other special "not regular channels" playlist
    }
    else {
        if(subnav){
            $('#' + id + ' a').replaceWith('<span class="select">' + $('#' + id + ' a').html() + '</span>'); // Add red arrow
            $('#' + id).parent().show(); // Display the sub_nab

            var parent = $('#'+id).parent().parent(); // the nav
            parent.addClass("select"); // Add red box
            //parent.children('a').replaceWith('<span>' + parent.children('a').html() + '</span>'); // Replace the a with span
        }
        else {
            $('#' + id).children('ul.sub_nav').show(); // Display the clicked one
            $('#' + id).addClass('select'); // Add the red box
            //$('#' + id + '> a').replaceWith('<span>' + $('#' + id + '> a').html() + '</span'); // Replace the a with span
        }
    }

    // To show the current video channel after video title
    for (var i=0; i < allPlaylists.length; i++) {
        var playlistChecker = allPlaylists[i];
        if( $('#'+playlistChecker.id).attr("class") == 'select' || $('#'+playlistChecker.id).attr("class") == 'first select' ) { // current menu
            var txtCurrent = $('#'+playlistChecker.id).attr("title");
            if(txtCurrent == '' || txtCurrent == null) txtCurrent = $('#'+playlistChecker.id+' > span').html();
            if(txtCurrent == '' || txtCurrent == null) txtCurrent = $('#'+playlistChecker.id+' > a').html();
            break;
        }
        else {
            if( $('#'+playlistChecker.id+' > span').attr("class") == 'select' ){
                    var txtCurrent = $('#'+playlistChecker.id+' > span').html();
                    break;
            }
            else {
                if($('#'+playlistChecker.id).parents("li").attr("class") == 'select' || $('#'+playlistChecker.id).parent().parent().attr("class") == 'first select' || $('#'+playlistChecker.id).parent().parent().attr("class") == 'last select'){ // current grnad parent menu
                    var txtCurrent = $('#'+playlistChecker.id).parent().parent().attr("title");
                }
            }
        }
    }
    if( $('#0').attr("class") == 'allchannel select') { // current menu
        var txtCurrent = $('#0 > span').html();
        if(txtCurrent == '' || txtCurrent == null) txtCurrent = $('#0 > a').html();
    }
}

 /* In-place partition */
 function partition(array,left,right,pivotIndex,field ) {
     var pivotValue = array[pivotIndex][field];
     array = swap(array,pivotIndex,right);
     var storeIndex = left;
     for( var i = left; i < right ; i++ ) {
         if( array[i][field] > pivotValue ) { // Desc order
             swap(array,i,storeIndex);
             storeIndex = storeIndex + 1;
         }
     }
     swap(array,storeIndex,right);
     return storeIndex;
 }

 /* quicksort */
 function qs(array,left,right,field) {
     if( right > left ) {
         var pivotIndex = left + Math.ceil((right-left) / 2);
           var pivotNew = partition(array,left,right,pivotIndex,field);
         array = qs(array,left,(pivotNew - 1), field);
         array = qs(array,(pivotNew + 1) , right , field);
     }
     return array;
 }
/* Swap 2 element of arra */
 function swap(a,i,j) {
    var tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
    return a;
}


/* remove duplicate id in arr[][] */
function removeDuplicate( arr ) {
    var newArr = new Array();
    for(var i = 0; i < arr.length;i++) {
        for(var j = 0 ; j < newArr.length;j++ ) {
            if( arr[i]['id'] == newArr[j]['id']) {
                break;
            }
        }
        if(j == newArr.length) {
            newArr.push(arr[i]);
        }
    }
    return newArr;
}

/* Callback from when changing pages */
function handlePaginationClick(page_index) {
    // Keep track of the current playlist
    var playlistId = $('span.select').parent().attr('id');
    if(!playlistId) { // its not a subnav
        playlistId = $('#nav').children('li.select').attr('id');
        // '#nav > li.select' not working ?!?
    }
    // select number video to display
    var max_elem = Math.min( ( page_index + 1 ) * this.items_per_page, this.content.length );

    $(this.div + ' .data-videolist').html('');  // clear html

    for(var i = ( page_index * this.items_per_page );i < max_elem; i++) {
        var video = this.content[ i ];
        var path = video.thumbnailURL;

        if( path == null) {
            path = "/media/images/default_200px.png";
        }
        //alert(strip_tags(video.shortDescription));
        var lengthText = (video.length)/1000/60+'';
        var valuesLength = lengthText.split('.');
        var secondsText = Math.round((video.length/1000) - (valuesLength[0] * 60));
        if(secondsText<10) secondsText = '0' + secondsText;
        var duration = valuesLength[0] + ':' + secondsText;

        var currentTab = parseInt((this.div).charAt(4));

        var targetUrl = '/' + video.id + '/' + formatMediaUrlToken(video.name); // + '/?playlistId=' + playlistId +"&tabs=" + currentTab; // + "&page=" + this.current_page;

        var descriptionText = showDescription(video.shortDescription, video.longDescription);

        var content = '<li class="' + video.id + ' hmedia">\n<div class="data">\n<div class="video-title">\n\<a href="' 
                    + targetUrl + '" title="' + htmlEntities(strip_tags(video.name)) + '" class="fn" \n\
                    onClick="setCKParameters(' + video.id + ',\'' + playlistId + '\',' + currentTab + ');false;">' + strip_tags(video.name)
                    + '</a>\n</div>\n<div class="entry-summary" onclick="window.location=\'' + targetUrl + '\'">' + descriptionText
                    + '</div></div><div class="duration">' + duration + '</div>\n<div class="thumbnail"><a href="' 
                    + targetUrl + '"rel="enclosure" title="' + htmlEntities(strip_tags(video.name))
                    + '"><img src="' + path + '" class="image photo"/></a></div></li>';
        
        $(this.div + ' .data-videolist').append(content);
        
        
    }

    // Truncate the title & description
    $('.panes .video-title > a').truncate(43);
    $('.panes div.entry-summary').truncate(115);
    $('div.entry-content div.entry-summary').truncate(250);
    return false;
}

/* Add videos in the 3 tabs 
* 
* resetPage : force page to 0, default to false
*/
function displayVideo( videos, id, resetPage) {
    //console.log(videos);
    
    if(typeof resetPage == 'undefined')resetPage = false;

    // page to select
    var p1 = 0, p2 = 0, p3 = 0;

    videos = removeDuplicate(videos);
    
    // sort videos
    var recentVideos = $.extend(true,[],videos);
    recentVideos = qs(recentVideos,0,(recentVideos.length-1),"publishedDate");
    
    // find page to display
    if(typeof _tabs == 'undefined' || _tabs == '1')
    {
        p1 = getPageForVideo(recentVideos, id);
    }
 
    $tabs1 = $("#tab1 .pagination_nav").pagination(recentVideos.length , {
        div:'#tab1',
        id:id,
        content:recentVideos,
        items_per_page:NBR_VIDEOS_PER_PAGE,
        current_page:p1,
        num_edge_entries:1,
        num_display_entries:7,
        prev_text:'prev',
        callback:handlePaginationClick
    });

    // sort videos
    var totalVideos = $.extend(true, [], videos);
    totalVideos = qs(totalVideos, 0, (totalVideos.length-1), "playsTotal" );

    // find page to display
    if(typeof _tabs != 'undefined' && _tabs == '2')
    {
        p2 = getPageForVideo(totalVideos, id);
    }
    
    
    $("#tab2 .pagination_nav").pagination(totalVideos.length , {
        div:'#tab2',
        content:totalVideos,
        id:id,
        items_per_page:NBR_VIDEOS_PER_PAGE,
        current_page:p2,
        num_edge_entries:1,
        num_display_entries:7,
        prev_text:'prev',
        callback:handlePaginationClick
    });

    // sort videos
    var totalTVideos = $.extend(true, [], videos);
    totalTVideos = qs( totalTVideos, 0,(totalTVideos.length-1), "playsTrailingWeek" );

    // find page to display
    if(typeof _tabs != 'undefined' && _tabs == '3')
    {
        p3 = getPageForVideo(totalTVideos, id);
    }
    
    $("#tab3 .pagination_nav").pagination(totalTVideos.length , {
        div:'#tab3',
        content:totalTVideos,
        id:id,
        items_per_page:NBR_VIDEOS_PER_PAGE,
        current_page:p3,
        num_edge_entries:1,
        num_display_entries:7,
        prev_text:'prev',
        callback:handlePaginationClick
    });

    // Add the red border in the video listing
    $('.data-videolist .' + id).addClass('current');
}

/* http://www.stemkoski.com/what-is-javascript%E2%80%99s-equivalent-to-php-strip_tags/
function strip_tags(html){
    //PROCESS STRING
    if(arguments.length < 3) {
        html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
    } else {
        var allowed = arguments[1];
        var specified = eval("["+arguments[2]+"]");
        if(allowed){
            var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
            html=html.replace(new RegExp(regex, 'gi'), '');
        } else{
            var regex='</?(' + specified.join('|') + ')\b[^>]*>';
            html=html.replace(new RegExp(regex, 'gi'), '');
        }
    }
    return html;
}
*/

/*
  function strip_tags (input, allowed) {
        allowed = (((allowed || "") + "")
              .toLowerCase()
              .match(/<[a-z][a-z0-9]*>/g) || [])
              .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
        var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
        return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
              return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
        });
    }
*/

/*
 * Show short description by default, if not show the long truncated
 **/
function showDescription(shortDescription, longDescription){
    if(shortDescription != '' && shortDescription != '<!-- Empty -->' && shortDescription != null)
        showDescriptionText = strip_tags(shortDescription);
    else
        showDescriptionText = strip_tags(longDescription).substr(0,122);
    return showDescriptionText;
}

function strip_tags(input, allowed){
    
    if(!input)
    {
        return "";
    }
    
    allowed = (((allowed || "") + "")
        .toLowerCase()
        .match(/<[a-z][a-z0-9]*>/g) || [])
        .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var reg = /(<\/?([a-z][a-z0-9]*)\b[^>]*>)/gi;
    var returnV = input.replace(reg, function($0, $1, $2){
        return allowed.indexOf('<' + $2.toLowerCase() + '>') > -1 ? $0 : '';
    });
    return returnV.replace('<' , '');
}

/* Truncate after nb caracter */
(function( $ ){
    $.fn.truncate = function(nb) {
        return this.each(function() {
            var $this = $(this);
            if($this.html().length > nb ) {
               var cont = ($this.html()).substr(0,nb);
               $this.html(cont + " ...");
            }
        });
    };

})( jQuery );


/***********************************
* Escape: & < > " '
* 
* str : the string to escape
************************************/
function htmlEntities(str)
{
    if(!str)
    {
        return "";
    }
    
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}

/***********************************
* Format a media url token so it doesn't contain any invalid character or space
* 
* urlToken : the token to format
************************************/
function formatMediaUrlToken(t)
{
    if(!t)
    {
        t = "";
    }
    
    // replace accents with non accentuated char
	t = t.replace(new RegExp("[àÀáÁâÂãÃäÄåÅªąĄаАạẠảẢẦầẤấẬậẨẩẪẫĂăẮắẴẵẶặẰằẲẳあアαΑ]", 'g'), "a");
	t = t.replace(new RegExp("[бБب]", 'g'), "b");
	t = t.replace(new RegExp("[çÇćĆčČ]", 'g'), "c");
	t = t.replace(new RegExp("[ÐдДدضđĐδΔ]", 'g'), "d");
	t = t.replace(new RegExp("[èÈéÉêÊëËęĘеЕёЁэЭẸẹẺẻỀềẾếỆệỂểỄễえエεΕ]", 'g'), "e");
	t = t.replace(new RegExp("[фФﻑφΦ]", 'g'), "f");
	t = t.replace(new RegExp("[ğĞгГγΓ]", 'g'), "g");
	t = t.replace(new RegExp("[ìÌíÍîÎïÏıİиИỊịỈỉĨĩいイηΗΙι]", 'g'), "i");
	t = t.replace(new RegExp("[ج]", 'g'), "j");
	t = t.replace(new RegExp("[кКكκΚ]", 'g'), "k");
	t = t.replace(new RegExp("[łŁлЛلλΛ]", 'g'), "l");
	t = t.replace(new RegExp("[мМمμΜ]", 'g'), "m");
	t = t.replace(new RegExp("[ñÑńŃнНنんンνΝ]", 'g'), "n");
	t = t.replace(new RegExp("[òÒóÓôÔõÕöÖøØºоОỌọỎỏỘộỐốỖỗỒồỔổƠơỜờỚớỢợỞởỠỡおオοΟωΩ]", 'g'), "o");
	t = t.replace(new RegExp("[пПπΠ]", 'g'), "p");
	t = t.replace(new RegExp("[ق]", 'g'), "q");
	t = t.replace(new RegExp("[®рРر]", 'g'), "r");
	t = t.replace(new RegExp("[şŞśŚсСسصšŠσςΣ]", 'g'), "s");
	t = t.replace(new RegExp("[тТتطτΤţŢ]", 'g'), "t");
	t = t.replace(new RegExp("[ùÙúÚûÛüÜуУỤụỦủŨũƯưỪừỨứỰựỬửỮữうウυΥ]", 'g'), "u");
	t = t.replace(new RegExp("[вВβΒ]", 'g'), "v");
	t = t.replace(new RegExp("[و]", 'g'), "w");
	t = t.replace(new RegExp("[×ξΞ]", 'g'), "x");
	t = t.replace(new RegExp("[ýÝÿйЙыЫيỲỳỴỵỶỷỸỹ]", 'g'), "y");
	t = t.replace(new RegExp("[żŻźŹзЗزظžŽζΖ]", 'g'), "z");
    
    // replace all non alphanum remaining by "_"
    t = t.replace(new RegExp("[^a-zA-Z0-9-]", 'g'), "_");
    
    // replace "__" by "_"
    t = t.replace(new RegExp("[_]+", 'g'), "_");
    
    // no "-" or "_" at both ends
    t = t.replace(/[_-]+$/, ""); 
    t = t.replace(/^[_-]+/, ""); 
    
    // empty? show "media" instead
    if(t == "")
    {
        t = "media";
    }
    
    return t;
}

/**Set BRAND cookie
 * int videoID = Video id of the
 * int playlistID = Playlist of the video requested
 * int currentTab = Last tab where the user is located before to request other page
**/
function setCKParameters(videoID, playlistID, currentTab)
{
    document.cookie = 'videoServer='+videoID+':'+playlistID+':'+currentTab+';path=/';
}

//Get cookie - return the BRAND cookie
function getCookie() {
    var search = "videoServer="
    var returnvalue = "";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search)
        // if cookie exists
        if (offset != -1) {
            offset += search.length
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);
            // set index of end of cookie value
            if (end == -1) end = document.cookie.length;
            returnvalue=unescape(document.cookie.substring(offset, end))
        }
    }
    return returnvalue;
}

 /* Equal height */
function equalHeightResize(group) {
    tallest = 0;

    lastHeigth = $("#Description").height();
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    if($("#Description").height() > 63) {
        if(lastHeigth > 60)
            tallest = lastHeigth + 158;
        group.height(tallest);
        $("#Description").height(lastHeigth);
    }
}

