﻿///<reference path="..\..\core\jscript\CliPropConfig6.js" />
///<reference path="CliPspLibraryValueRenderers.js" />

//--------------------------------------------------------------------------------
function CliLibraryItemRowRenderer( libraryView )
{
    ///<summary>renders a row in the library for a single library item. provides
    ///utility methods to access items in divs rendered by this class</summary>
    ///<param name="libraryView">A CliLibraryView</param>
    
    this._libraryView = libraryView;
    
    this.RowSelectionChangedClickHandler = null;    // fn( CliLibraryItemRowSelectionChangedEventArgs )
    
    this._fnRenderTrimmedText = CliRenderTrimmedText;
    
    this._lengthTitle;
}

CliLibraryItemRowRenderer.prototype =
{
    //--------------------------------------------------------------------------------
    GenerateRowId : function( mediaContentId )
    {
        ///<summary>generates a unique row id for an item</summary>
        
        return "cli-lib-itemrow-moid-" + mediaContentId;
    },
    
    //--------------------------------------------------------------------------------
    Render : function( libraryItem, libraryCache ) // : div
    {
        this._CalculateTrimLengths( libraryItem );
        
        var self = this;
        var createElement = document.createElement;
        
        var rowDiv = document.createElement( "<div class=\"single-row\" />" );
        rowDiv.setAttribute( "id", this.GenerateRowId( libraryItem.MediaContentId ) );
        rowDiv.setAttribute( "cli-moid", libraryItem.MediaContentId );
        rowDiv.setAttribute( "cli-dbg-item-state", libraryItem.State );

        this._AddColumn( rowDiv, "titleCol generibut arrowRight",  function()
        {
            var detailsUrl = libraryItem.DetailsPageUrl;
            return CliRenderTextLink( libraryItem.Title, self._lengthTitle, function( srcElement )
            {
                self._ShowVideoDetailsClickHandler( srcElement, detailsUrl );
            } );
        } );
        
        this._AddColumn( rowDiv, "partofCol", function(){ return CliRenderTrimmedText( libraryItem.SecondaryTitle, self._lengthSecondaryTitle ); } );
        this._AddColumn( rowDiv, "priceCol",  function(){ return self._RenderPriceColumn( libraryItem, libraryCache ); } );
        this._AddColumn( rowDiv, "sizeCol",   function(){ return CliRenderTrimmedText( CliRenderFileSize( libraryItem.MediaSize ), self._lengthMediaSize ); } );

        //6=dloading 9=paused 5=bmark 10=downloaded
        var itemState = libraryItem.State;

        // bookmark
        if( itemState == 5 )
        {
            this._AddColumn( rowDiv, "expiryCol", function(){ return CliRenderTrimmedText( "N/A", 25 ); } );
            this._AddColumn( rowDiv, "statusCol",   function(){ return CliRenderTrimmedText( pageLookupText( "lib-status-bm-Default", libraryItem.ItemChannel ), 25 ); } );
        }
        
        // active download or paused download
        if( itemState == 6 || itemState == 9 )
        {
            this._AddColumn( rowDiv, "expiryCol", function(){ return CliRenderTrimmedText( "N/A", 25 ); } );
            this._AddColumn( rowDiv, "statusCol progressBar",   function(){ return CliRenderProgressBar( libraryItem.PercentageDownloaded ); } );
        }
        
        // downloaded
        if( itemState == 10 )
        {
            this._AddColumn( rowDiv, "expiryCol", function(){ return self._RenderContentExpiry( libraryItem ); } );
            this._AddColumn( rowDiv, "statusCol", function(){ return self._RenderSyncsRemaining( libraryItem, libraryCache ); } );
        }
        
        this._AddRowSelectionCheckbox( rowDiv, libraryItem );

        return rowDiv;
    },

    //--------------------------------------------------------------------------------
    _RenderPriceColumn : function( libraryItem, libraryCache )
    {
        var purchaseStatus = this._GetCacheValue( libraryCache, "PurchaseStatus", "", libraryItem.MediaContentId );
        
        if( purchaseStatus == "FREE" || purchaseStatus == "SUBSCRIBED" || purchaseStatus == "NOTSUBSCRIBED"
         || purchaseStatus == "PAID" )
        {
            return CliRenderTrimmedText( pageLookupText( "lib-price-" + purchaseStatus, libraryItem.ItemChannel ), this._lengthPrice );
        }
        
        var priceStr = this._GetCacheValue( libraryCache, "PriceToPay", pageLookupText( "lib-price-Default", libraryItem.ItemChannel ), libraryItem.MediaContentId );
        return CliRenderTrimmedText( priceStr, self._lengthPrice );
    },
    
    //--------------------------------------------------------------------------------
    _RenderSyncsRemaining : function( libraryItem, libraryCache )
    {
        var cachedSyncs = this._GetCacheValue( libraryCache, "RemainingSyncs", null, libraryItem.MediaContentId );
        var readyToSync = this._GetCacheValue( libraryCache, "StatusKey", null, libraryItem.MediaContentId );
        var channel = libraryItem.ItemChannel;
        
        var remainingSyncs = pageLookupText( "lib-status-syncs-Default", channel );

        if( readyToSync != null )
        {
            if( readyToSync == "READTOSYNC" )
            {
                remainingSyncs = pageLookupText( "lib-status-syncs-READTOSYNC", channel );
                if( cachedSyncs != null )
                    remainingSyncs += "(" + cachedSyncs + ")";
            }
            else if( readyToSync == "NOTSUBSCRIBED" || readyToSync == "MAXSYNCSEXCEEDED" )
            {
                remainingSyncs = pageLookupText( "lib-status-syncs-" + readyToSync, channel );
            }
        }

        return CliRenderTrimmedText( remainingSyncs, 25 );
    },

    //--------------------------------------------------------------------------------
    _RenderContentExpiry : function( libraryItem )
    {
        var exp = "";

        if( libraryItem.ContentExpiryDays < 1000 )
            exp = libraryItem.ContentExpiryDays + " days";
        
        return CliRenderTrimmedText( exp, 25 );
    },
    
    //--------------------------------------------------------------------------------
    GetRenderedRowState : function( rowDiv )
    {
        return rowDiv.getAttribute( "library-state" )
    },
    
    //--------------------------------------------------------------------------------
    _GetCacheValue : function( libraryCache, cacheValueName, defaultValue, mediaContentId )
    {
        ///<summary>Safely get a value form the cache, returning a default value if
        ///it is not available.</summary>
        
        var returnValue = defaultValue;
        
        if( libraryCache != null )
        {
            try
            {
                var cacheItem = libraryCache.GetItem( mediaContentId );
                        
                if( cacheItem != null )
                {
                    var cachedValue = cacheItem.GetAttribute( cacheValueName );
                    if( cachedValue != null && cachedValue != "" )
                        returnValue = cachedValue;
                }
            }
            catch( e ){}
        }
        
        return returnValue;
    },
    
    //--------------------------------------------------------------------------------
    _ShowVideoDetailsClickHandler : function( srcElement, detailsUrl )
    {
        ///<summary>a click handler that will show the video details overlay</summary>
        
        if( detailsUrl != null )
        {
            try
            {
                ajaxAnywhere.getAJAX( detailsUrl, "content" );
            }
            catch( e )
            {
                try { hide_waiting(); }catch( e ){}
                CliDebug( e.message );
            }
        }
    },
    
    //--------------------------------------------------------------------------------
    _AddRowSelectionCheckbox : function( rowDiv, libraryItem )
    {
        var chkBox = this._AddColumn( rowDiv, "rowSelect noSpace",
            function()
            {
                var chk = CliRenderCheckbox();
                chk.setAttribute( "row-select", "true" );
                chk.setAttribute( "library-state", libraryItem.State );
                return chk;
            } );
        
        var eventHandler = this.RowSelectionChangedClickHandler;
        
        var mediaContentId = libraryItem.MediaContentId;
        CliAttachOnclickEventHandler( chkBox,
            function( srcElement )
            {
                var eventArgs =  new CliLibraryItemRowSelectionChangedEventArgs(
                    mediaContentId, srcElement.checked, srcElement.getAttribute( "library-state" ) );
                
                eventHandler( eventArgs );
            } );
    },



    //--------------------------------------------------------------------------------
    _AddColumn : function( parent, className, fn ) // : div created
    {
        ///<summary>Adds a column to the row.  The column is created by calling the
        ///function 'fn', and is wrapped in a try catch.</summary>
        ///<param name="parent">div to add column to</param>
        ///<param name="className">class name string for div</param>
        ///<param name="fn">function to call to create column</param>
        
        try
        {
            var div = fn();
            div.className = className;
            parent.appendChild( div );
            
            return div;
        }
        catch( e )
        {
        }
    },
    
    //--------------------------------------------------------------------------------
    SelectRow : function( rowDiv, selected )
    {
        ///<summary>Looks at the child nodes of the div, locates the checkbox
        ///and clicks it.</summary>
        ///<param name="rowDiv">A row rendered by this class</param>
        
        var chk = this._FindRowSelectioncheckbox( rowDiv );
        if( chk != null && chk.getAttribute( "checked" ) != selected )
            chk.click();
    },
    
    //--------------------------------------------------------------------------------
    DeselectRow : function( rowDiv )
    {
        ///<summary>Looks at the child nodes of the div, locates the checkbox
        ///and clicks it.</summary>
        ///<param name="rowDiv">A row rendered by this class</param>
        
        var chk = this._FindRowSelectioncheckbox( rowDiv );
        if( chk != null && chk.getAttribute( "checked" ) == true )
            chk.click();
    },
    
    //--------------------------------------------------------------------------------
    _FindRowSelectioncheckbox : function( rowDiv ) // : input
    {
        for( var i = 0; i < rowDiv.childNodes.length; i++ )
        {
            var child = rowDiv.childNodes[ i ];
            if( child.getAttribute( "row-select" ) != null )
            {
                return child;
            }
        }
    },
    
    //--------------------------------------------------------------------------------
    _CalculateTrimLengths : function( libraryItem )
    {
        var channel = libraryItem.ItemChannel;
        
        this._lengthTitle          = 20;
        this._lengthSecondaryTitle = 16;
        this._lengthPrice          = 25;
        this._lengthMediaSize      = 25;

        try{ this._lengthTitle          = pageTrimLength( "lib-title",    this._lengthTitle,          channel ); }catch( e ){}
        try{ this._lengthSecondaryTitle = pageTrimLength( "lib-2ndtitle", this._lengthSecondaryTitle, channel ); }catch( e ){}
        try{ this._lengthPrice          = pageTrimLength( "lib-price",    this._lengthPrice,          channel ); }catch( e ){}
        try{ this._lengthMediaSize      = pageTrimLength( "lib-medsize",  this._lengthMediaSize,      channel ); }catch( e ){}
    }
}//
