//
// for Home.php
//
function init() {
    CrossSite_getVideos(1, 'by_date');
    updateRecentlyWatched();
}

function callback_getVideos(jsonObj) {
    $('newestlist').innerHTML = htmlMovieList(jsonObj.videos)
        + '<div id="newestlist_extralink"><a href="javascript:showAllMoviesTab()">' + (lang=='en' ? 'more "Newest"' : 'tất cả phim mới') +' &raquo; </div>';
}

function showAllMoviesTab() {
    if( parent!=null && typeof parent.showTab != 'undefined' )
        parent.showTab('All');
}

function playVideo(iVideoId) {
    if( parent!=null && typeof parent.onPlayRequest != 'undefined' )
        parent.onPlayRequest(iVideoId);
}

//
// process cookies to update list of recently watched movies
//
var arRecentlyWatched = [];
function updateRecentlyWatched() {
    arRecentlyWatched = [];

    var arCookies = getCookies();
    for( var name in arCookies ) {

        // only process recently-watched-movie cookies
        if( name.indexOf('v_')==0 ) {

            var arFields = arCookies[name].split('|');
            var oVideo = {  id: name.substring(2),
                            title: arFields[0],
                            image_link: arFields[1],
                            clips_count: arFields[2],
                            last_watched: arFields[3] };
            if( oVideo.image_link.indexOf('http:')<0 )
                oVideo.image_link = CrossSite_url + oVideo.image_link;
            
            // insert to array order by 'last_watch desc'
            var iInsertIndex = 0;
            for( var i=0; i<arRecentlyWatched.length; i++ ) {
                if( arRecentlyWatched[i].last_watched < oVideo.last_watched ) {
                    iInsertIndex = i;
                    break;
                }
            }
            arRecentlyWatched.splice(iInsertIndex, 0, oVideo);
        }

    }
    
    // only keep 20 recently watched items
    var iKeepNum = 20;
    if( arRecentlyWatched.length>iKeepNum ) {
        for( var i=arRecentlyWatched.length-1; i>=iKeepNum; i-- ) {
            setCookie('v_' + arRecentlyWatched[i].id, '', -1);  // remove cookies
        }
        arRecentlyWatched.splice(iKeepNum-1, arRecentlyWatched.length-iKeepNum);
    }

    var arShort = [];
    var arExtra = [];
    for( var i=0; i<arRecentlyWatched.length; i++ ) {
        if( i<4 )
            arShort.push(arRecentlyWatched[i]);
        else
            arExtra.push(arRecentlyWatched[i]);
    }

    if( arRecentlyWatched.length>0 ) {
        $('welcome').style.display = 'none';
        $('recent').style.display = '';
        
        $('recentlist_short').innerHTML = htmlMovieList(arShort);
        if( $('recentlist_extralink').style.display!='none' )
            $('recentlist_extra').style.display = 'none';
        $('recentlist_extra').innerHTML = htmlMovieList(arExtra, 5);
    }
}

function showRecentListExtra() {
    $('recentlist_extralink').style.display = 'none';
    $('recentlist_extra').style.display = '';
}
