// Rewrites the links to media details pages to have correct offsets.
// startIndex must be set to the initial offset (based on current page index * page size).
function rewriteDetailsLinks ( container, startIndex ) {
    // If the current page is only showing media from one channel then we shouldn't remap the offsets.
    if ( /channel=[0-9]+/.test ( document.location.toString () ) )
        return;

    if ( ( typeof ( container ) == 'undefined' ) || ( container == null ) )
        throw ( 'No container specified' );

    container = $( container );

    if ( typeof ( startIndex ) == 'undefined' )
        startIndex = 0;

    // This will contain the current offset of media items in each channel displayed in the container element
    var channelOffsets = new Hash ();

    // This will contain the offsets assigned to media items
    var mediaOffsets = new Hash ();

    function getFixedURI ( inputURI ) {
        var offsetRegEx = /offset=([0-9]+)/;
        var mediaIDRegEx = /\/entry\/([0-9]+)/;

        var matches = inputURI.match ( /channel=([0-9]+)/ );

        // If we didn't find a channel ID then we shouldn't be modifying this URI
        if ( matches == null )
            return inputURI;

        var channelID = matches [ 1 ];

        // No offset => no modification
        if ( !offsetRegEx.test ( inputURI ) )
            return inputURI;

        matches = inputURI.match ( mediaIDRegEx );

        // No media ID => no modification
        if ( matches == null )
            return inputURI;

        var mediaID = matches [ 1 ];

        var existingMediaOffset = mediaOffsets.get ( mediaID );

        // If we've already assigned an offset to this media item then use it
        if ( typeof ( existingMediaOffset ) != 'undefined' )
            return inputURI.replace ( offsetRegEx, 'offset=' + existingMediaOffset );

        var existingChannelOffset = channelOffsets.get ( channelID );

        if ( typeof ( existingChannelOffset ) == 'undefined' )
            existingChannelOffset = 0;
        else
            existingChannelOffset++;

        channelOffsets.set ( channelID, existingChannelOffset );

        // Save this media's offset for later use for other links to this media item
        mediaOffsets.set ( mediaID, existingChannelOffset );

        return inputURI.replace ( offsetRegEx, 'offset=' + existingChannelOffset );
    }

    container.select ( 'a[href^="/entry"]' ).each (
        function ( element ) {
            element.href = getFixedURI ( element.href );
        }
    );
}
