var PDFCatalogueLibrary = {};

PDFCatalogueLibrary.domNodes        = {};
PDFCatalogueLibrary.sourceListArray = [];
PDFCatalogueLibrary.targetList      = null;

PDFCatalogueLibrary.DDList = function( id, sGroup, config )
{
    PDFCatalogueLibrary.DDList.superclass.constructor.call( this, id, sGroup, config );

    this.goingUp  = false;
    this.lastY    = 0;
    this.dropArea = YAHOO.util.Dom.get( 'pdfCatalogueTargetList' );
    this.children = [];
    this.isTarget = false;
    this.slot     = null;

    YAHOO.util.Dom.setStyle( this.getDragEl(), 'opacity', 0.85 );
};

YAHOO.extend( PDFCatalogueLibrary.DDList, YAHOO.util.DDProxy,
{
    isItem : true,

    init: function()
    {
        PDFCatalogueLibrary.DDList.superclass.init.apply( this, arguments );

    },
    startDrag: function( x, y )
    {
        var  dragEl = this.getDragEl(),
            clickEl = this.getEl();

        YAHOO.util.Dom.setStyle( clickEl, 'visibility', 'hidden' );

        dragEl.innerHTML = clickEl.innerHTML;

        var cssAttributes = [ 'border',
                              'borderStyle',
                              'backgroundColor',
                              'color'
                            ];

        for ( var cssAttributeIndex in cssAttributes )
        {
            var cssAttribute = cssAttributes[ cssAttributeIndex ],
                       style = YAHOO.util.Dom.getStyle( clickEl, cssAttribute );

            if ( style !== null && style !== undefined )
            {
                YAHOO.util.Dom.setStyle( dragEl, cssAttribute, style );
            }
        }

        YAHOO.util.Dom.setStyle( this.dropArea, 'border', '1px solid #120763' );
    },
    endDrag: function( e )
    {
        var srcEl              = this.getEl(),
            proxy              = this.getDragEl(),
            thisid             = this.id,
            pdfGenerateDOMNode = YAHOO.util.Dom.get( 'pdfCatalogueGenerateButton' );

        if ( srcEl.parentNode.id != 'pdfCatalogueTargetList' && srcEl.parentNode.id != srcEl.originalParent )
        {
            var newParent = YAHOO.util.Dom.get( srcEl.originalParent );

            newParent.appendChild( srcEl );
            YAHOO.util.DragDropMgr.refreshCache();
        }

        if ( srcEl.parentNode.id == 'pdfCatalogueTargetList' )
        {
            this.isTarget = true;
        }
        else
        {
            this.isTarget = false;
        }

        YAHOO.util.Dom.setStyle( proxy,  'visibility', '' );

        var a = new YAHOO.util.Motion
        (
            proxy, { points: { to: YAHOO.util.Dom.getXY( srcEl ) } },
            0.1,
            YAHOO.util.Easing.easeOut
        )

        if ( this.dropArea.isEmpty() )
        {
            pdfGenerateDOMNode.disabled = true;
        }
        else
        {
            pdfGenerateDOMNode.disabled = false;
        }

        if ( e.noAnimation )
        {
            YAHOO.util.Dom.setStyle( proxy.id, 'visibility', 'hidden' );
            YAHOO.util.Dom.setStyle( thisid,   'visibility', '' );
        }
        else
        {
            a.onComplete.subscribe(
                function()
                {
                    YAHOO.util.Dom.setStyle( proxy.id, 'visibility', 'hidden' );
                    YAHOO.util.Dom.setStyle( thisid,   'visibility', '' );
                }
            );
        }
        a.animate();

        YAHOO.util.Dom.setStyle( this.dropArea, 'border', '1px solid #AAAAAA' );

    },

    onDragDrop: function( e, id )
    {
        if ( YAHOO.util.DragDropMgr.interactionInfo.drop.length === 1 )
        {
            var pt     = YAHOO.util.DragDropMgr.interactionInfo.point,
                region = YAHOO.util.DragDropMgr.interactionInfo.sourceRegion;

            if ( !region.intersect( pt ) )
            {
                var destEl = YAHOO.util.Dom.get( id ),
                    destDD = YAHOO.util.DragDropMgr.getDDById( id );

                destEl.appendChild( this.getEl() );

                destDD.isEmpty = false;

                YAHOO.util.DragDropMgr.refreshCache();
            }
        }
    },
    onDrag: function( e )
    {
        var y = YAHOO.util.Event.getPageY(e);

        if ( y < this.lastY )
        {
            this.goingUp = true;
        }
        else if ( y > this.lastY )
        {
            this.goingUp = false;
        }

        this.lastY = y;
    },
    onDragOver: function( e, id )
    {

        var srcEl  = this.getEl(),
            destEl = YAHOO.util.Dom.get( id ),
            destDD = YAHOO.util.DragDropMgr.getDDById( id );

        this.lastDDid = id;

        if ( destEl.nodeName.toLowerCase() == 'li' )
        {
            var orig_p = srcEl.parentNode,
                     p = destEl.parentNode;

            if ( this.goingUp )
            {
                p.insertBefore( srcEl, destEl );
            }
            else
            {
                p.insertBefore( srcEl, destEl.nextSibling );
            }

            YAHOO.util.DragDropMgr.refreshCache();
        }
    }
});

PDFCatalogueLibrary.getDOMObjectById = function( domID )
{
    if ( document.getElementById )
    {
        var domObject = document.getElementById( domID );
        if ( domObject !== undefined && domObject !== null )
        {
            return domObject;
        }
    }
    return false;
}

PDFCatalogueLibrary.getTagTextContentByObject = function( domObject )
{
    var tagText = false;
    if ( domObject.textContent !== undefined && domObject.textContent !== null )
    {
        tagText = domObject.textContent;
    }
    else if ( domObject.innerText !== undefined && domObject.innerText !== null )
    {
        tagText = domObject.innerText;
    }
    return tagText;
}

PDFCatalogueLibrary.getTagTextContentById = function( domID )
{
    var domObject = PDFCatalogueLibrary.getDOMObjectById( domID );
    if ( domObject !== false )
    {
        return PDFCatalogueLibrary.getTagTextContentByObject( domObject );
    }
    return false;
}

PDFCatalogueLibrary.pdfGenerate = function()
{
    var getElementIDList = function( ul )
    {
        var elementIDList = [],
            listItems     = ul.getElementsByTagName( 'li' ),
            itemIDList    = false;

        if  ( listItems.length < 1 )
        {
            return false;
        }

        for ( i = 0; i < listItems.length; i++ )
        {
            if ( listItems[i].id )
            {
                itemIDList = listItems[i].id.split( '_' );
                if ( itemIDList[2] !== false && itemIDList[2] !== null )
                {
                    elementIDList.push( itemIDList[2] );
                }
            }
        }
        return elementIDList;
    };

    var selectedListElementIDs = getElementIDList( YAHOO.util.Dom.get( 'pdfCatalogueTargetList' ) );

    if ( selectedListElementIDs == false )
    {
        alert( PDFCatalogueLibrary.config.noDocumentsWarning );
        return false;
    }

    var JSONParameterString = YAHOO.lang.JSON.stringify(
        {
            catid : PDFCatalogueLibrary.config.catalogueID,
            list  : selectedListElementIDs
        }
    );

    PDFCatalogueLibrary.domNodes.generateButton.hideDomNode();
    PDFCatalogueLibrary.domNodes.generatingImage.showDomNode();

    if ( PDFCatalogueLibrary.config.downloadMode == 'SYNC' )
    {
        PDFCatalogueLibrary.syncRequest( JSONParameterString, PDFCatalogueLibrary.config.pdfFilename );
    }
    else
    {
        PDFCatalogueLibrary.asyncRequest( JSONParameterString );
    }
}

PDFCatalogueLibrary.syncRequest = function( jsonstring, filename )
{
    var fileNameParameter = filename;
    if ( !filename.search( '/.*\.pdf$/i' ) )
    {
        fileNameParameter = fileNameParameter + '.pdf';
    }
    var sURL = PDFCatalogueLibrary.config.generateURL + '/' + jsonstring + '/live/' + escape( fileNameParameter );

    window.setTimeout(
        function()
        {
            PDFCatalogueLibrary.domNodes.generatingImage.hideDomNode();
            PDFCatalogueLibrary.domNodes.generateButton.showDomNode();
        }, 1500
    );

    window.location.href = sURL;
}

PDFCatalogueLibrary.asyncRequest = function( jsonstring )
{
    YAHOO.util.Connect.asyncRequest
    (
        'GET', PDFCatalogueLibrary.config.generateURL + '/' + jsonstring + '/cache',
        {
            success: function( o )
            {
                var self = this.argument[0];
                try
                {
                    var resObj = YAHOO.lang.JSON.parse( o.responseText );
                }
                catch( e )
                {
                }

                PDFCatalogueLibrary.domNodes.generatingImage.hideDomNode();
                PDFCatalogueLibrary.domNodes.generateButton.showDomNode();

                if ( resObj != undefined && resObj.success == true )
                {
                    if ( resObj.hash != undefined )
                    {
                        var fileNameParameter = resObj.filename;
                        if ( !resObj.filename.search( '/.*\.pdf$/i' ) )
                        {
                            fileNameParameter = fileNameParameter + '.pdf';
                        }
                        var href = PDFCatalogueLibrary.config.downloadURL + '/' + resObj.hash + '/' + fileNameParameter;
                        window.location.href = href;
                    }
                }
            },
            failure: function(o)
            {
                PDFCatalogueLibrary.domNodes.generatingImage.hideDomNode();
                PDFCatalogueLibrary.domNodes.generateButton.showDomNode();
            },
            argument: [ this ]
        },
        null
    );
}

PDFCatalogueLibrary.removeListItemById = function( id )
{
    var domObject = YAHOO.util.DragDropMgr.getDDById( id );
    if ( domObject !== false && domObject !== undefined )
    {
        var liDomObject = domObject.getEl();
        if ( liDomObject !== false && liDomObject !== undefined )
        {
            var targetDomObject = YAHOO.util.Dom.get( liDomObject.originalParent );

            if ( targetDomObject !== false && targetDomObject !== undefined  )
            {
                targetDomObject.appendChild( liDomObject );

                domObject.endDrag( { noAnimation : true } );

                YAHOO.util.DragDropMgr.refreshCache();
            }
        }
    }

}

PDFCatalogueLibrary.initialize = function()
{
    PDFCatalogueLibrary.domNodes.generateButton  = YAHOO.util.Dom.get( 'pdfCatalogueGenerateButton' );
    PDFCatalogueLibrary.domNodes.generatingImage = YAHOO.util.Dom.get( 'pdfCatalogueGeneratingImage' );

    for ( elementName in PDFCatalogueLibrary.domNodes )
    {
        var elementObject = PDFCatalogueLibrary.domNodes[ elementName ];

        if ( elementObject === undefined || elementObject === null ||
             elementObject.id === undefined || elementObject.id === false
           )
        {
            continue;
        }

        elementObject.hideDomNode = function()
        {
            YAHOO.util.Dom.setStyle( this, 'display', 'none' );
        }

        elementObject.showDomNode = function()
        {
            YAHOO.util.Dom.setStyle( this, 'display', 'block' );
        }

        elementObject.toggleVisibility = function()
        {
            if ( this.style.display == undefined ||
                 this.style.display == '' ||
                 this.style.display == 'block'
               )
            {
                this.hideDomNode();
            }
            else
            {
                this.showDomNode();
            }
        }
    }

    PDFCatalogueLibrary.targetList = 'pdfCatalogueTargetList';

    var tray = new YAHOO.util.DDTarget( 'pdfCatalogueTargetList' );

    if ( PDFCatalogueLibrary.config.documentList !== null && PDFCatalogueLibrary.config.documentList !== undefined )
    {
        for ( var i = 0; i < PDFCatalogueLibrary.config.documentList.length; i++ )
        {
            var sourceListItems  = PDFCatalogueLibrary.config.documentList[ i ],
                sourceListName   = 'pdfCatalogueSourceList_' + i,
                sourceDropTarget = new YAHOO.util.DDTarget( sourceListName );

            PDFCatalogueLibrary.sourceListArray.push( sourceListName );

            for ( var j = 0; j < sourceListItems.length ; j++ )
            {
                var dropSource  = new PDFCatalogueLibrary.DDList( sourceListItems[ j ] ),
                    listElement = YAHOO.util.Dom.get( sourceListItems[ j ] );

                listElement.originalParent = 'pdfCatalogueSourceList_' + ( i + 1 );
            }
        }
    }

    var dropArea = YAHOO.util.Dom.get( 'pdfCatalogueTargetList' );

    if ( dropArea !== null && dropArea !== undefined )
    {
        dropArea.hideBackground = function()
        {
            YAHOO.util.Dom.setStyle( this, 'background-position', 'right center' );
        }
        dropArea.showBackground = function()
        {
            YAHOO.util.Dom.setStyle( this, 'background-position', 'left center' );
        }
    }
    else
    {
        return;
    }

    var areaList = [];

    areaList = areaList.concat( PDFCatalogueLibrary.targetList, PDFCatalogueLibrary.sourceListArray );

    for ( var key in areaList )
    {
        var areaID      = areaList[ key ],
            areaDomNode = YAHOO.util.Dom.get( areaID );

        if ( areaDomNode === null || areaDomNode === undefined )
        {
            continue;
        }

        areaDomNode.isEmpty = function()
        {
            var areaListItems = this.getElementsByTagName( 'li' );

            return ( areaListItems.length < 1 );
        }

    }

    YAHOO.util.Event.on( 'pdfCatalogueGenerateButton', 'click', PDFCatalogueLibrary.pdfGenerate, null, this );

    YAHOO.util.Dom.setStyle( YAHOO.util.Dom.get( 'pdfCatalogueTabContainer' ), 'display', 'block' );
    YAHOO.util.Dom.setStyle( YAHOO.util.Dom.get( 'pdfCatalogueTabLoader' ),    'display', 'none' );
}

PDFCatalogueLibrary.setupPDFCatalogue = function()
{
    new YAHOO.widget.TabView( 'pdfCatalogueTabContainer' );
    var documentList       = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueDocumentList' ),
        catalogueID        = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueCatalogueID' ),
        pdfFileName        = PDFCatalogueLibrary.getTagTextContentById( 'pdfCataloguePDFFileName' ),
        downloadMode       = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueDownloadMode' ),
        noDocumentsWarning = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueNoDocumentsWarning' ),
        downloadURL        = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueDownloadURL' ),
        generateURL        = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueGenerateURL' );
    PDFCatalogueLibrary.config =
    {
        documentList       : eval( '(' + documentList + ')' ),
        catalogueID        : catalogueID,
        downloadMode       : downloadMode,
        pdfFilename        : pdfFileName,
        noDocumentsWarning : noDocumentsWarning,
        generateURL        : generateURL,
        downloadURL        : downloadURL
    };
    PDFCatalogueLibrary.initialize();
}

if ( window.attachEvent )
{
    window.attachEvent( 'onload', PDFCatalogueLibrary.setupPDFCatalogue );
}
else if ( window.addEventListener )
{
    window.addEventListener( 'load', PDFCatalogueLibrary.setupPDFCatalogue, false );
}
