/* General TVKaista JS functions
 * - Dependent on jQuery
 * - To play recodings a map of mediaFileClips is needed
 *
 * TODO: Add translator support
 */

// Formats, extensions & Bitrates

formatIdLookup = {
    mp4     : 3,
    flash   : 4,
    h264    : 3,
    ts      : 0,
    vlc300k : 3,
    vlc2M   : 3,
    vlc8M   : 0
};

formatNameLookup = {
    mp4     : 'H264 MP4',
    flash   : 'Flash Video',
    h264    : 'H264 MP4',
    ts      : 'MPEG2 TS',
    vlc300k : 'H264 MP4',
    vlc2M   : 'H264 MP4',
    vlc8M   : 'MPEG2 TS'
};

extensionLookup = {
    mp4     : 'mp4',
    flash   : 'flv',
    h264    : 'h264',
    ts      : 'ts',
    vlc300k : 'mp4',
    vlc2M   : '2M.mp4',
    vlc8M   : 'ts'
};

bitrateLookup = {
    mp4     : 300000,
    flash   : 1000000,
    h264    : 2000000,
    ts      : 8000000,
    vlc300k : 300000,
    vlc2M   : 2000000,
    vlc8M   : 8000000
};

clipFormats = {
    mp4     : 'f0',
    flash   : 'f1',
    h264    : 'f2',
    ts      : 'f3',
    vlc300k : 'f0',
    vlc2M   : 'f2',
    vlc8M   : 'f3'
};

function isTranscoding( clip ) {
    return clip.status == 'Transcoding';
}

function isRunning( clip ) {
    return clip.status == 'Running' || clip.status == 'Running Delayed';
}

function isCompleted( clip ) {
    return clip.status == 'Completed' || clip.status == 'Truncated';
}

function isFailed( clip ) {
    return clip.status == 'Failed';
}

// Get a mediafileclip with the wanted format
function getMediaFileClip( recordingId, format ) {
    var formatName = formatNameLookup[ format ];
    var bitrate = bitrateLookup[ format ];
    var clips = mediaFileClips[ recordingId ];
    var clip = null;
    var i = 0;

    // First try: Find the same format and bitrate
    for ( i = 0; i < clips.length; i++ ) {
        if ( isCompleted( clips[i] ) && clips[i].format == formatName && clips[i].bitrate == bitrate ) {
            clip = clips[i];
            break;
        }
    }

    // Second try: Find the same format, ignore bitrate. This will select clips with the format set to -1
    if( clip === null ) {
        for ( i = 0; i < clips.length; i++ ) {
            if ( isCompleted( clips[i] ) && clips[i].format == formatName ) {
                clip = clips[i];
                break;
            }
        }
    }
    return clip;
}

// Returns an integer id for an element
// The format to define the id for an element is
// id="XXXID" where XXX are three chars and ID is the
// identification number ex. id="rec12345"
// You can also store a second id using _ID2
// id="XXXID_ID2"
function getId( el ) {
    var id = el.attr( 'id' );
    if ( id.lastIndexOf('_') > 0 ) {
        return parseInt( id.substr( 0, id.lastIndexOf( '_' ) ).substr( 3 ), 10 );
    }
    else {
        return parseInt( id.substr( 3 ), 10 );
    }
}

function setId( el, id ) {
    var oldid = el.attr( 'id' );
    if ( oldid.lastIndexOf('_') > 0 ) {
        el.attr('id', oldid.substr( 0, 3 ) + id + oldid.substr( oldid.lastIndexOf('_') ) );
    }
    else {
        el.attr('id', oldid.substr( 0, 3 ) + id );
    }
}

// Returns a second interger that can be associated with an element
function getSecondId( el ) {
    return parseInt( el.attr( 'id' ).substr( el.attr( 'id' ).lastIndexOf('_') + 1 ), 10 );
}

function setSecondId( el, id ) {
    if ( el.attr( 'id' ).lastIndexOf('_') < 0 ) {
        el.attr( 'id', el.attr( 'id' ) + '_' );
    }

    el.attr('id', el.attr( 'id' ).substr( 0, el.attr( 'id' ).lastIndexOf('_') + 1 ) + id );
}


function playRecording( recordingId ) {
    var selFormat = $("#format").val();
    
    switch( selFormat ) {
        case 'mp4':
        case 'flash':
        case 'h264':
        case 'ts':
            playRecordingWithFormat( recordingId, formatIdLookup[ selFormat ], bitrateLookup[ selFormat ] );
            break;
        case 'vlc300k':
        case 'vlc2M':
        case 'vlc8M':
            playVLCRecordingWithFormat( recordingId, formatIdLookup[ selFormat ], bitrateLookup[ selFormat ] );
            break;
    }
}

function setSize( sizeChange ) {
	
	size = parseInt( $.cookie('viewsize') );
	
	// 0 resets the view size, +-1 changes the current size
	if( sizeChange == 0 )
		size = 0;
	else if( ( sizeChange < 0 && size > -2 ) || ( sizeChange > 0 && size < 2 ) )
		size += sizeChange;
	
    $.cookie('viewsize', size, {
        expires: 365, path: '/'
    });

    $('.setsize').removeClass('selected');
    
    switch( size ) {
	    case -2:
	    	$.stylesheetSwitch( "size8" );
	    break;
        case -1:
        	$.stylesheetSwitch( "size10" );
        break;
        case 0:
        	$.stylesheetSwitch( "size13" );
        break;
        case 1:
        	$.stylesheetSwitch( "size17" );
        break;
        case 2:
        	$.stylesheetSwitch( "size21" );
        break;
    }
}

function setInfomessageVisibility( id, visible ) {
    if( visible == "visible" ) {
        $('.infomessage').slideDown('fast');
    }
    else {
        $.cookie('infomessageVisible' + id, $.md5( $('.infomessage .msg').text() ), { expires: 365, path: '/' } );
        $('.infomessage').slideUp('fast');
    }
}

function doSearch() {
    $('#programsearchform').submit();
}

function errorHandler( msg, e ) {
    if( e.javaClassName == 'com.agentum.lib.common.exception.AuthenticationFailedException' ) {
        showMsgBox( _('general_session_timeout'), function() { document.location = baseUrl + 'login/'; } );
    } else {
        showMsgBox( _('general_ajax_error') );
    }
}

function playVLCRecordingWithFormat( recordingid, format, bitrate ) {
    document.location = baseUrl + 'VLC?id=' + recordingid + '&format=' + format + '&bitrate=' + bitrate;
}

function playRecordingWithFormat( recordingId, format, bitrate ) {
    var url = baseUrl + 'recordings/play/' + recordingId + '/' + format + ( bitrate != -1 ? '/' + bitrate + '/' : '/' );
    var width = 655;
    var height = 450;

    if ( format === 0 ) { // ts file
        width = 1024;
        height = 661;
    }

    var newwindow = window.open( url,'recordingwindow','menubar=0,resizable=yes,scrollbars=no,width='+width+',height='+height );

    if ( format != 5 && window.focus ) {
        newwindow.focus();
    }
}


$( document ).ready( function() {

    // Ser error handler
    DWREngine.setErrorHandler( errorHandler );

    // Read infomessage state from cookie
    // If the cookie stores the hash from the infomessage then we should autohide it
    if ($('.infomessage').length > 0) {
        var id = getId( $('.infomessage') );
        if ($.cookie('infomessageVisible' + id)) {
            var infomessagehash = $.cookie('infomessageVisible' + id);
            var newinfomessage = $('.infomessage .msg').text();
            if( $.md5(newinfomessage) != infomessagehash ) {
                setInfomessageVisibility(id, "visible");
            }
        }
        else {
            setInfomessageVisibility(id, "visible");
        }
    }
    
    // Style switcher
    $.stylesheetInit();
    
    // Read fontsize from cookie
    if ( $.cookie('viewsize') ) {
        size = $.cookie('viewsize');
        // Using small timeout to get it working
        // Todo: Look into why the timeout is needed
        setTimeout( 'setSize(' + size + ');', 1 );
    }
    else {
        // Set default text size
        setSize( 0 );
    }

    // Infomessage hide
    $( '#hideinfomessage' ).click( function() {
        var id = getId( $('.infomessage') );
        setInfomessageVisibility( id, "hidden" );
    } );

    // Search recordings when search button pressed
    $( '#searchbutton' ).click( function() {
      doSearch();
    });

    // Add playback functionlity
    $( '.playback' ).live( 'click', function() {
        if( $(this).hasClass('disabled') ) {
            return;
        }

        id = getId( $(this) );
        playRecording( id );

        return false;
    } );

    // Add 'add to playlist' functionality to recordings view
    $( '#channelboard .addtoplaylist' ).live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        id = getId( el );

        // Switch to remove instead of add to playlist
        $('#plr' + id ).removeClass('addtoplaylist');
        $('#plr' + id ).addClass('removefromplaylist');
        
        if( !$('#plr' + id ).hasClass( 'legacy' ) ) {
        	$('#pul' + id ).replaceWith( '<span class="playlistmarker">' + _('recordings_added') + '</span>' );
        	$('#plr' + id ).html(_('recordings_remove_from_playlist'));
        }

        TVKaistaCentreServer.addToPlaylist( id, {
            callback:function ( ) {
                $('#pid' + id ).after( ' <span id="plm' + id + '" class="playlistmarker">*</span>' );
            }
        });

        return false;
    } );

    // Add 'remove from playlist' functionality
    $( '#channelboard .removefromplaylist' ).live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        id = getId( el );

        // Switch to remove instead of add to playlist
        $('#plr' + id ).removeClass('removefromplaylist');
        $('#plr' + id ).addClass('addtoplaylist');
        
        if( !$('#plr' + id ).hasClass( 'legacy' ) ) {
        	$('#pul' + id ).replaceWith( '<span class="playlistmarker">' + _('recordings_removed') + '</span>' );
        	$('#plr' + id ).html(_('recordings_add_to_playlist'));
        }
        
        TVKaistaCentreServer.removeFromPlaylist( id, {
            callback:function ( ) {
                $('#plm' + id ).remove(); // Marker on main view
            }
        });

        return false;
    } );

    // Add 'add to seasonpass' functionality to recordings view
    $( '#channelboard .addtoseasonpass' ).live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        id = getId( el );

        // Add notification
        el.replaceWith( '<span class="playlistmarker">' + _('recordings_added') + '</span>' );

        TVKaistaCentreServer.addToSeasonPass( id, {
            callback:function ( ) {
            }
        });

        return false;
    } );

    // Add 'add to storage' functionality
    $('.useractions .addtofavorites').live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }
        var id = getId( el );

        CentreServer.addFavorite( id, {
            callback:function ( succeeded ) {
                if (succeeded) {
                    // Switch to remove instead of add to favorite
                    el.removeClass('addtofavorites');
                    el.addClass('removefromfavorites');
                    el.html(_('recordings_remove_from_favorites'));
                }
                else {
                    showMsgBox(_('recordings_too_many_favorite_recordings'));
                }

            }
        });

        return false;
    });

    // Add 'remove from storage' functionality.
    $('.useractions .removefromfavorites').live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        var id = getId( el );

        // Are we on the storage page. If so, remove row.
        var onStoragePage = $('#storagepage').length > 0;

        el.removeClass( 'removefromfavorites' );


        if (onStoragePage) {
            $('#row' + id).css('cursor', 'wait');
            $('#row' + id).fadeOut(function(){
                el.remove();
            }); // Row on storage page
        }
        else {
            el.addClass('addtofavorites');
            el.html(_('recordings_add_to_favorites'));
        }

        CentreServer.removeFavorite( id, {
            callback:function ( ) { }
        });

        return false;
    });

    // Add 'remove from playlist' functionality
    $( '.useractions .removefromplaylist' ).live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        id = getId( el );

        // Are we on the playlist page. If so, remove row.
        var onPlaylist = $('#playlistpage').length > 0;

        el.removeClass( 'removefromplaylist' );

        if (onPlaylist) {
            $('#row' + id).css('cursor', 'wait');
            $('#row' + id).fadeOut(function(){
                el.remove();
            }); // Row on playlist page
        }
        else {
            el.addClass('addtoplaylist');
            el.html(_('recordings_add_to_playlist'));
        }

        TVKaistaCentreServer.removeFromPlaylist( id, {
            callback:function ( ) { }
        });

        return false;
    } );


    // Add 'add to playlist' functionality to generic lists
    $( '.useractions .addtoplaylist' ).live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        id = getId( el );

        // Switch to remove instead of add to playlist
        el.removeClass('addtoplaylist');
        el.addClass('removefromplaylist');
        el.html(_('recordings_remove_from_playlist'));

        TVKaistaCentreServer.addToPlaylist( id, {
            callback:function() {}
        });

        return false;
    } );

    // Add 'add to season pass' functionality to generic lists
    $( '.useractions .addtoseasonpass' ).live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        id = getId( el );

        // Switch to remove instead of add to playlist
        el.removeClass('addtoseasonpass');
        el.addClass('removefromseasonpass');
        el.html(_('recordings_remove_from_seasonpass'));

        // Set id to -1 temporarely until we get the real id for the seasonpass on the callback
        setSecondId( el, -1 );
        el = el;

        TVKaistaCentreServer.addToSeasonPass( id, {
            callback:function ( id ) {
                setSecondId( el, id );
            }
        });

        return false;
    } );

    // Add 'remove from season pass' functionality to generic lists
    $( '.useractions .removefromseasonpass' ).live( 'click', function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        id = getSecondId( el );

        // Switch to remove instead of add to playlist
        el.removeClass('removefromseasonpass');
        el.addClass('addtoseasonpass');
        el.html(_('recordings_add_to_seasonpass'));

        TVKaistaCentreServer.removeFromSeasonPass( id, {
            callback:function ( ) {	}
        });

        return false;
    } );

    // Add 'remove seasonpass' functionality to seasonpass page
    $( '.removeseasonpass' ).click( function() {
        var el = $(this);
        if( el.hasClass('disabled') ) {
            return;
        }

        id = getId( el);

        $('#spl' + id ).fadeOut(function(){
                el.remove();
        });

        TVKaistaCentreServer.removeFromSeasonPass( id, {
            callback:function() {}
        });

        return false;
    });

    // Add option to change font size
    $( '.setsize' ).click( function() {
    	if( $(this).attr('id') == 'zoomreset' )
    		setSize( 0 );
    	else if( $(this).attr('id') == 'zoomin' )
        	setSize( 1 );
        else
        	setSize( -1 );

        return false;
    });

    // Save format in session and cookie
    $( '#format' ).change( function() {
        TVKaistaCentreServer.saveView( $( '#format' ).val(), {
            callback:function() {}
        });

        $.cookie('format', $( '#format' ).val(), { expires: 365, path: '/' } );
    } );

    // Read format from cookie if possible. Important to do before setting change event.
    if( $.cookie('format') ) {
        $( '#format' ).val( $.cookie('format') );
    }

    $( 'td', '.highlight' ).hbHighlight();

    $( 'label.overlabel' ).overlabel();

    $( '#menu td' ).click( function() {
        document.location = baseUrl + $( this ).find("a").attr("href");
    });

    // Channel selector
    $( '#channelselector' ).change( function() {
        if( $(this).val() == '0' ) {
            document.location = baseUrl + 'recordings/allchannels/';
        } else if( $( 'option:selected', this ).hasClass( 'channel' ) ) {
            document.location = baseUrl + 'recordings/channel/' + $(this).val() + '/';
        } else {
            document.location = baseUrl + 'recordings/channelgroup/' + $(this).val() + '/';
        }
    } );

    // Return to All Channels view button
    $( '#allchannels' ).click( function() {
        document.location = baseUrl + 'recordings/allchannels/';
    });

    // Quicklinks
    $( '#quicklink' ).change( function() {
        if( $(this).val() != '0' ) {
            document.location = baseUrl + $(this).val();
        }
    });

    // Add hover to calendar and allow user to click anywhere in th calendar cell
    $( '.calendar td.day' ).hover( function() {
            $(this).data( 'oldclass', $(this).attr('class') );
            $(this).addClass('selected');
            if( $(this,'a:first') ) {
                $(this).css('cursor','pointer');

                $(this).click( function() { document.location = baseUrl + $(this).children().attr("href"); } );
            }
        },
        function() {
            $(this).attr('class', $(this).data('oldclass'));
        }
    );
    
    // Star score 
    $('.score').stars( { inputType: "select", cancelShow: false, callback : function( ui, type, value ) {
         var id = parseInt( ui.element.attr('id').substr(5), 10 );
         value = parseInt( value, 10 );
         $('#scorecontainer' + id ).animate( { opacity: 0.01 } );
         
         CentreServer.rateRecording( id, value, { callback: function( score ) {
                $('#scorecontainer' + id ).animate( { opacity: 1 } );
                $('#scorevalue' + id ).text( score.toFixed(2) + ' / 5.00' );
                $('#scorecontainer' + id ).fadeIn();
            }
         });         
    } } );
} );
