var PDFCatalogueLibrary = {};

PDFCatalogueLibrary.domNodes                 = {};
PDFCatalogueLibrary.targetList               = false;
PDFCatalogueLibrary.commonTargetAreaPrepared = false;
PDFCatalogueLibrary.commonDropSource         = null;
PDFCatalogueLibrary.commonNodeIDList         = [];
PDFCatalogueLibrary.currentNodeID            = false;
PDFCatalogueLibrary.generatePDFNodeID        = false;

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 = true;
    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();

        if ( PDFCatalogueLibrary.isDedicatedPDFCatalogue )
        {
            YAHOO.util.Dom.setStyle( clickEl, 'visibility', 'hidden' );

            dragEl.innerHTML = clickEl.innerHTML;

            var cssAttributes = [ 'border',
                                  'background',
                                  'color',
                                  'width',
                                  'boxShadow',
                                  'borderRadius',
                                  'MozBoxShadow',
                                  'MozBorderRadius',
                                  'WebkitBoxShadow',
                                  'WebkitBorderRadius',
                                  'KhtmlBoxShadow',
                                  'KhtmlBorderRadius',
                                  'filter',
                                  'MsFilter'
                                ];

            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( dragEl, 'height', '' );
        }
        else
        {
            // Drag from target list
            if ( clickEl.parentNode.id == 'pdfCatalogueTargetList' &&
                 PDFCatalogueLibrary.targetList !== false
               )
            {
                YAHOO.util.Event.on( 'pdfCatalogueCommonTargetArea', 'mouseover', null, null, this );
                YAHOO.util.Event.on( 'pdfCatalogueCommonTargetArea', 'mouseout', null, null, this );
            }

            YAHOO.util.Dom.setStyle( clickEl, 'visibility', 'hidden' );
            dragEl.innerHTML = clickEl.innerHTML;
            YAHOO.util.Dom.setStyle( dragEl, 'height', 'auto' );
            PDFCatalogueLibrary.showCommonTargetArea( false );
        }
    },
    endDrag: function( e )
    {
        var srcEl              = this.getEl(),
            proxy              = this.getDragEl(),
            thisid             = this.id,
            pdfGenerateDOMNode = YAHOO.util.Dom.get( 'pdfCatalogueGenerateButton' ),
            pdfSendDOMNode     = YAHOO.util.Dom.get( 'pdfCatalogueSendButton' ),
            pdfSendAreaDomNode = YAHOO.util.Dom.get( 'pdfCatalogueSendArea' ),
            pdfSendMailDOMNode = YAHOO.util.Dom.get( 'pdfCatalogueSendEmailButton' );

        if ( PDFCatalogueLibrary.isDedicatedPDFCatalogue )
        {
            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();
            }
        }
        else
        {
            // From source to target list
            if ( srcEl.parentNode.id == 'pdfCatalogueTargetList' && srcEl.originalParent == 'pdfCatalogueCommonSource' )
            {
                e.noAnimation = true;
                PDFCatalogueLibrary.setCommonTargetListItems();
                PDFCatalogueLibrary.generatePDFNodeID = PDFCatalogueLibrary.currentNodeID;
            }
            else if ( srcEl.parentNode.id == 'pdfCatalogueTargetList' && srcEl.originalParent == 'pdfCatalogueTargetList' ) // From target list to target list
            {
                PDFCatalogueLibrary.setCommonTargetListItems();
            }
        }

        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
        )

        var isSendAreaVisible = false;

        if ( pdfSendAreaDomNode !== null && pdfSendAreaDomNode !== undefined &&
             pdfSendAreaDomNode.style.display == 'block'
           )
        {
            isSendAreaVisible = true;
        }

        if ( this.dropArea !== null && this.dropArea.isEmpty() )
        {
            if ( pdfGenerateDOMNode !== null )
            {
                pdfGenerateDOMNode.disabled = true;
            }
            if ( pdfSendDOMNode !== null && !isSendAreaVisible )
            {
                pdfSendDOMNode.disabled = true;
            }
            if ( pdfSendMailDOMNode !== null && isSendAreaVisible )
            {
                pdfSendMailDOMNode.disabled = true;
            }
        }
        else
        {
            if ( pdfGenerateDOMNode !== null )
            {
                pdfGenerateDOMNode.disabled = false;
            }
            if ( pdfSendDOMNode !== null && !isSendAreaVisible )
            {
                pdfSendDOMNode.disabled = false;
            }
            if ( pdfSendMailDOMNode !== null && isSendAreaVisible )
            {
                pdfSendMailDOMNode.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();
    },

    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 clickEl = this.getEl();
        if ( clickEl.parentNode.id == 'pdfCatalogueTargetList' &&
             PDFCatalogueLibrary.targetList !== false &&
             YAHOO.util.Dom.getStyle( PDFCatalogueLibrary.targetList, 'display' ) == 'none'
           )
        {
            PDFCatalogueLibrary.showCommonTargetArea( false );
        }

        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.setTagHTMLByObject = function( tagDOMObject, tagText )
{
    if ( tagDOMObject.innerHTML !== undefined && tagDOMObject.innerHTML !== null )
    {
        if ( tagText.search( '<html' ) == -1 ) // Problem with IE if the text contains a <html> tag
        {
            tagDOMObject.innerHTML = tagText;
        }
    }
}

PDFCatalogueLibrary.clearDebug = function( debugText )
{
    var targetDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfDebug' );
    if ( targetDomNode !== false )
    {
        PDFCatalogueLibrary.setTagHTMLByObject( targetDomNode, '' );
    }
}

PDFCatalogueLibrary.writeDebug = function( debugText )
{
    var targetDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfDebug' );
    if ( targetDomNode !== false )
    {
        var domNodeText = PDFCatalogueLibrary.getTagTextContentByObject( targetDomNode );
        if ( domNodeText !== false )
        {
            domNodeText = domNodeText + "\n" + debugText;
            PDFCatalogueLibrary.setTagHTMLByObject( targetDomNode, domNodeText );
        }
    }
}

PDFCatalogueLibrary.pdfGenerateCommon = function()
{
    var targetListDomNode = PDFCatalogueLibrary.getDOMObjectById( PDFCatalogueLibrary.targetList ),
              formDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueCommonGenerateForm' ),
        inputFieldDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueCommonItemNodeIDString' );
    if ( targetListDomNode !== false && formDomNode !== false && inputFieldDomNode !== false )
    {
        var     itemDomNodeList = targetListDomNode.getElementsByTagName( 'li' ),
                     nodeIDList = new Array();

        for ( var i = 0; i < itemDomNodeList.length; ++i )
        {
            var itemIDList = itemDomNodeList[i].id.split( '_' );
            if ( itemIDList.length > 1 )
            {
                nodeIDList.push( itemIDList[1] );
            }
        }
        var nodeIDString = YAHOO.lang.JSON.stringify( { node_id_list: nodeIDList } );
        inputFieldDomNode.value = nodeIDString;
        formDomNode.submit();
    }
}

PDFCatalogueLibrary.getElementIDList = function( listID, full )
{
    var itemsObject = PDFCatalogueLibrary.getDOMObjectById( listID );

    if ( itemsObject === false )
    {
        return false;
    }

    var elementIDList = [],
        listItems     = itemsObject.getElementsByTagName( 'li' ),
        itemIDList    = false
        itemObject    = null;

    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] !== undefined && itemIDList[2] !== null &&
                 itemIDList[3] !== undefined && itemIDList[3] !== null
               )
            {
                itemObject = { document_id : itemIDList[2],
                               pdf_id : itemIDList[3]
                             }
                if ( full === true && itemIDList[1] !== undefined && itemIDList[1] !== null )
                {
                    itemObject.chapter_id = itemIDList[1];
                    elementIDList.push( itemObject );
                }
                else
                {
                    elementIDList.push( itemObject );
                }
            }
        }
    }
    return elementIDList;
};

PDFCatalogueLibrary.pdfGenerate = function( eventObject )
{
    var selectedListElementIDs = PDFCatalogueLibrary.getElementIDList( 'pdfCatalogueTargetList', false );

    if ( selectedListElementIDs === false )
    {
        alert( PDFCatalogueLibrary.config.noDocumentsWarning );
        return false;
    }

    var JSONParameterString = YAHOO.lang.JSON.stringify(
        {
            catid : PDFCatalogueLibrary.config.catalogueID,
            list  : selectedListElementIDs
        }
    );

    if ( PDFCatalogueLibrary.domNodes.generateButton )
    {
        PDFCatalogueLibrary.domNodes.generateButton.hideDomNode();
    }
    if ( PDFCatalogueLibrary.domNodes.sendButton )
    {
        PDFCatalogueLibrary.domNodes.sendButton.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();
            if ( PDFCatalogueLibrary.domNodes.sendButton )
            {
                PDFCatalogueLibrary.domNodes.sendButton.showDomNode();
            }
            if ( PDFCatalogueLibrary.domNodes.generateButton )
            {
                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();
                if ( PDFCatalogueLibrary.domNodes.generateButton )
                {
                    PDFCatalogueLibrary.domNodes.generateButton.showDomNode();
                }
                if ( PDFCatalogueLibrary.domNodes.sendButton )
                {
                    PDFCatalogueLibrary.domNodes.sendButton.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();
                if ( PDFCatalogueLibrary.domNodes.generateButton )
                {
                    PDFCatalogueLibrary.domNodes.generateButton.showDomNode();
                }
                if ( PDFCatalogueLibrary.domNodes.sendButton )
                {
                    PDFCatalogueLibrary.domNodes.sendButton.showDomNode();
                }
            },
            argument: [ this ]
        },
        null
    );
}

PDFCatalogueLibrary.ajaxRequest = function( url, destinationElementId, postData, forwardFunction )
{
    var destinationElement = false;

    if ( destinationElementId !== false && destinationElementId !== null && destinationElementId !== undefined )
    {
        if ( ( typeof destinationElementId ) == 'object' )
        {
            destinationElement = destinationElementId;
        }
        else
        {
            destinationElement = PDFCatalogueLibrary.getDOMObjectById( destinationElementId );
        }
    }

    var callBack =
    {
        success: function( response )
        {
            if ( ( typeof forwardFunction ) == 'string' )
            {
                eval( forwardFunction );
            }
            else if ( ( typeof forwardFunction ) == 'function' )
            {
                forwardFunction( destinationElementId, response.responseText );
            }
            else if ( destinationElement !== false )
            {
                PDFCatalogueLibrary.setTagHTMLByObject( destinationElement, response.responseText );
            }
        },
        failure: function( response )
        {
            if ( forwardFunction )
            {
                alert( 'Request failed ');
            }
            else if ( ( typeof forwardFunction ) == 'function' )
            {
                forwardFunction( destinationElementId, response.responseText );
            }
            else if ( destinationElement !== false )
            {
                PDFCatalogueLibrary.setTagHTMLByObject( destinationElement, '<!-- AJAX request ' + url + ' failed -->' );
            }
        }
    };

    if ( postData )
    {
        var transaction = YAHOO.util.Connect.asyncRequest( 'POST', url, callBack, postData );
    }
    else
    {
        var transaction = YAHOO.util.Connect.asyncRequest( 'GET', url, callBack, null );
    }
}

PDFCatalogueLibrary.emailVerificationResult = function( targetDomNodeID, resultText )
{
    if ( resultText == '1' )
    {
        var targetDomNode = PDFCatalogueLibrary.getDOMObjectById( targetDomNodeID );
        if ( targetDomNode !== false )
        {
            targetDomNode.style.display = 'none';
        }
    }
    PDFCatalogueLibrary.pdfVerifyEmailForm( false, true );
}

PDFCatalogueLibrary.pdfVerifyEmailForm = function( eventObject, noEmailVerification )
{
    var   emailSenderDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailSender' ),
        emailReceiverDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailReceiver' ),
         emailSubjectDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailSubject' ),
            sendEmailDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueSendEmailButton' ),
           targetListDomNode = PDFCatalogueLibrary.getDOMObjectById( PDFCatalogueLibrary.targetList );

    if ( emailReceiverDomNode === false || emailSubjectDomNode === false ||
         sendEmailDomNode === false || emailSenderDomNode === false  || targetListDomNode === false
       )
    {
        return false;
    }

    var   emailSenderText = emailSenderDomNode.value,
        emailReceiverText = emailReceiverDomNode.value,
         emailSubjectText = emailSubjectDomNode.value;

    if ( noEmailVerification !== true )
    {
        var JSONParameterString ='',
                      targetURL = '';

        if ( emailSenderText.trim() !== '' )
        {
            JSONParameterString = YAHOO.lang.JSON.stringify(
                {
                    email : emailSenderText
                }
            );

            targetURL = PDFCatalogueLibrary.config.verifyURL + '/' + JSONParameterString;

            PDFCatalogueLibrary.ajaxRequest( targetURL, 'pdfCatalogueEmailSenderStatus', false, PDFCatalogueLibrary.emailVerificationResult );
        }

        if ( emailReceiverText.trim() !== '' )
        {
            JSONParameterString = YAHOO.lang.JSON.stringify(
                {
                    email : emailReceiverText
                }
            );
            targetURL = PDFCatalogueLibrary.config.verifyURL + '/' + JSONParameterString;

            PDFCatalogueLibrary.ajaxRequest( targetURL, 'pdfCatalogueEmailReceiverStatus', false, PDFCatalogueLibrary.emailVerificationResult );
        }

    }

    if ( emailReceiverText.trim() !== '' && emailSubjectText.trim() !== '' && emailSenderText.trim() != '' &&
         targetListDomNode.isEmpty() == false
       )
    {
        var   senderStatusDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailSenderStatus' ),
            receiverStatusDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailReceiverStatus' );

        if ( senderStatusDomNode !== false && receiverStatusDomNode !== false &&
                senderStatusDomNode.style.display === 'none' &&
                receiverStatusDomNode.style.display === 'none'
            )
        {
            sendEmailDomNode.disabled = false;
            return true;
        }
    }
    sendEmailDomNode.disabled = true;
    return false;
}

PDFCatalogueLibrary.pdfCancelSend = function( eventObject )
{
    var  sendAreaDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueSendArea' ),
        sendEmailDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueSendEmailButton' ),
       targetListDomNode = PDFCatalogueLibrary.getDOMObjectById( PDFCatalogueLibrary.targetList );

    if ( sendAreaDomNode === false || sendEmailDomNode === false )
    {
        return false;
    }

    sendAreaDomNode.style.display = 'none';
    sendEmailDomNode.disabled = true;
    if ( targetListDomNode === false || targetListDomNode.isEmpty() == false )
    {
        if ( PDFCatalogueLibrary.domNodes.sendButton )
        {
            PDFCatalogueLibrary.domNodes.sendButton.disabled = false;
        }
    }
}

PDFCatalogueLibrary.emailSendResult = function( targetDomNodeID, resultText )
{
    if ( resultText === '1' )
    {
        var  sendAreaDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueSendArea' ),
            sendEmailDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueSendEmailButton' );

        sendAreaDomNode.style.display = 'none';
        if ( PDFCatalogueLibrary.domNodes.sendButton )
        {
            PDFCatalogueLibrary.domNodes.sendButton.disabled = false;
        }
        sendEmailDomNode.disabled = true;
    }
}

PDFCatalogueLibrary.pdfSendEmail = function()
{
    var     emailSenderDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailSender' ),
          emailReceiverDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailReceiver' ),
           emailSubjectDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailSubject' ),
              emailTextDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailText' ),
           catalogueURLDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueEmailCatalogueURL' ),
        selectedListElementIDs = PDFCatalogueLibrary.getElementIDList( PDFCatalogueLibrary.targetList, true ),
                   selectedIDs = [];

    var   emailSenderText = emailSenderDomNode.value,
        emailReceiverText = emailReceiverDomNode.value,
         emailSubjectText = emailSubjectDomNode.value
            emailTextText = emailTextDomNode.value,
         catalogueURLText = catalogueURLDomNode.value;

    for ( var i = 0; i < selectedListElementIDs.length; ++i )
    {
        selectedIDs.push( selectedListElementIDs[i].chapter_id + '_' + selectedListElementIDs[i].document_id + '_' + selectedListElementIDs[i].pdf_id );
    }

    var JSONParameterString = YAHOO.lang.JSON.stringify(
        {
            sender : emailSenderText,
            subject : emailSubjectText,
            receiver : emailReceiverText,
            body : emailTextText,
            link : catalogueURLText,
            idlist: selectedIDs.join( ',' )
        }
    );

    var targetURL = PDFCatalogueLibrary.config.sendURL,
        postData = 'JSONData=' + encodeURIComponent( JSONParameterString );

    PDFCatalogueLibrary.ajaxRequest( targetURL, false, postData, PDFCatalogueLibrary.emailSendResult );

}

PDFCatalogueLibrary.pdfShowSend = function( eventObject )
{
    var  sendAreaDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueSendArea' ),
        sendEmailDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueSendEmailButton' );

    if ( sendAreaDomNode === false || sendEmailDomNode === false )
    {
        return false;
    }

    sendAreaDomNode.style.display = 'block';
    if ( PDFCatalogueLibrary.domNodes.sendButton )
    {
        PDFCatalogueLibrary.domNodes.sendButton.disabled = true;
    }
    sendEmailDomNode.disabled = true;
    PDFCatalogueLibrary.pdfVerifyEmailForm( false, false );
}

PDFCatalogueLibrary.removeCommonListItemById = function( id )
{
    var domNode = PDFCatalogueLibrary.getDOMObjectById( id );
    if ( domNode !== false )
    {
        var idList = domNode.id.split( '_' );
        if ( idList.length > 1 )
        {
            if ( idList[1] == PDFCatalogueLibrary.currentNodeID )
            {
                var dropSource = YAHOO.util.DragDropMgr.getDDById( domNode.id );
                if ( dropSource !== null && dropSource !== undefined && dropSource !== false )
                {
                    dropSource.unreg();
                    dropSource = null;
                    YAHOO.util.DragDropMgr.refreshCache();
                }
                var commonSource = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueCommonSource' );
                if ( commonSource !== false )
                {
                    commonSource.appendChild( domNode );
                }
            }
            PDFCatalogueLibrary.removeCommonTargetListItem( idList[1] );
        }
    }
}

PDFCatalogueLibrary.removeListItemById = function( id )
{
    var domObject = YAHOO.util.DragDropMgr.getDDById( id );
    if ( domObject !== false && domObject !== undefined && domObject !== null )
    {
        var liDomObject = domObject.getEl();
        if ( liDomObject !== false && liDomObject !== undefined && liDomObject !== null )
        {
            var targetDomObject = YAHOO.util.Dom.get( liDomObject.originalParent );

            if ( targetDomObject !== false && targetDomObject !== undefined && targetDomObject !== null )
            {
                targetDomObject.appendChild( liDomObject );

                domObject.endDrag( { noAnimation : true } );

                YAHOO.util.DragDropMgr.refreshCache();
            }
        }
    }

}

PDFCatalogueLibrary.showCommonTargetArea = function( eventObject )
{
    if ( PDFCatalogueLibrary.targetList !== false )
    {
        YAHOO.util.Dom.setStyle(  PDFCatalogueLibrary.targetList, 'display', 'block' );
        YAHOO.util.DragDropMgr.refreshCache();
    }
}

PDFCatalogueLibrary.hideCommonTargetArea = function()
{
    if ( PDFCatalogueLibrary.targetList !== false )
    {
        YAHOO.util.Dom.setStyle(  PDFCatalogueLibrary.targetList, 'display', 'none' );
    }
}

PDFCatalogueLibrary.removeCommonTargetListItem = function( domNodeID )
{
    if ( PDFCatalogueLibrary.commonTargetActionURL !== false &&
         PDFCatalogueLibrary.currentLocale !== false
       )
    {
        var postData = 'ContentObjectID=0&PDFCatalogueRemoveItemBotton=PDFCatalogueRemoveItemBotton&PDFCatalogueItemNodeID=' + encodeURIComponent( domNodeID ) + '&PDFCatalogueGetItemListTranslation=' + encodeURIComponent( PDFCatalogueLibrary.currentLocale );
        PDFCatalogueLibrary.ajaxRequest( PDFCatalogueLibrary.commonTargetActionURL,
                                         PDFCatalogueLibrary.commonTargetAreaDomNode,
                                         postData,
                                         PDFCatalogueLibrary.responseUpdateCommonTargetList
                                       );
    }
}

PDFCatalogueLibrary.setCommonTargetListItems = function()
{
    if ( PDFCatalogueLibrary.commonTargetActionURL !== false &&
         PDFCatalogueLibrary.currentLocale !== false &&
         PDFCatalogueLibrary.targetList !== false
       )
    {
        var   targetListDomNode = PDFCatalogueLibrary.getDOMObjectById( PDFCatalogueLibrary.targetList );
                itemDomNodeList = targetListDomNode.getElementsByTagName( 'li' ),
                     nodeIDList = new Array(),
            currentNodeSelected = false;

        for ( var i = 0; i < itemDomNodeList.length; ++i )
        {
            var itemIDList = itemDomNodeList[i].id.split( '_' );
            if ( itemIDList.length > 1 )
            {
                if ( itemIDList[1] == PDFCatalogueLibrary.currentNodeID )
                {
                    currentNodeSelected = true;
                }
                nodeIDList.push( itemIDList[1] );
            }
        }
        if ( nodeIDList.length > 0 )
        {
            var nodeIDString = YAHOO.lang.JSON.stringify( { node_id_list: nodeIDList } ),
                    postData = 'ContentObjectID=0&PDFCatalogueSetItemListBotton=PDFCatalogueSetItemListBotton&PDFCatalogueItemNodeIDString=' + encodeURIComponent( nodeIDString ) + '&PDFCatalogueGetItemListTranslation=' + encodeURIComponent( PDFCatalogueLibrary.currentLocale );
            PDFCatalogueLibrary.ajaxRequest( PDFCatalogueLibrary.commonTargetActionURL,
                                             PDFCatalogueLibrary.commonTargetAreaDomNode,
                                             postData,
                                             PDFCatalogueLibrary.responseUpdateCommonTargetList
                                           );
        }
    }
}

PDFCatalogueLibrary.setupTargetList = function()
{
    PDFCatalogueLibrary.targetList = 'pdfCatalogueTargetList';

    var targetListDomNode = PDFCatalogueLibrary.getDOMObjectById( PDFCatalogueLibrary.targetList );

    if ( targetListDomNode !== false )
    {
        var tray = new YAHOO.util.DDTarget( PDFCatalogueLibrary.targetList );

        PDFCatalogueLibrary.addIsEmptyFunction( targetListDomNode );

        if ( targetListDomNode !== false )
        {
            targetListDomNode.hideBackground = function()
            {
                YAHOO.util.Dom.setStyle( this, 'background-position', 'right center' );
            }
            targetListDomNode.showBackground = function()
            {
                YAHOO.util.Dom.setStyle( this, 'background-position', 'left center' );
            }
        }
    }

}

PDFCatalogueLibrary.removeCommonTargetDDSources = function()
{
    var sourceDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueTargetList' );
    if ( sourceDomNode !== false )
    {
        var liDomNodeList = sourceDomNode.getElementsByTagName( 'li' );
        for ( var i = 0; i < liDomNodeList.length; ++i )
        {
            var dropSource = YAHOO.util.DragDropMgr.getDDById( liDomNodeList[i].id );
            if ( dropSource !== null && dropSource !== undefined && dropSource !== false )
            {
                dropSource.unreg();
                dropSource = null;
            }
            if ( liDomNodeList[i].id == 'document_' + PDFCatalogueLibrary.currentNodeID )
            {
                PDFCatalogueLibrary.commonDropSource = null;
            }
        }
        YAHOO.util.DragDropMgr.refreshCache();
    }
}

PDFCatalogueLibrary.responseUpdateCommonTargetList = function( destinationElementId, resultText )
{
    if ( PDFCatalogueLibrary.generatePDFNodeID !== false )
    {
        var postData = 'ContentObjectID=0&PDFCatalogueGeneratePDFByNodeID=PDFCatalogueGeneratePDFByNodeID&PDFCatalogueItemNodeID=' + encodeURIComponent( PDFCatalogueLibrary.generatePDFNodeID ) + '&PDFCatalogueGeneratePDFTranslation=' + encodeURIComponent( PDFCatalogueLibrary.currentLocale );
        PDFCatalogueLibrary.ajaxRequest( PDFCatalogueLibrary.commonTargetActionURL,
                                         false,
                                         postData,
                                         false
                                       );
        PDFCatalogueLibrary.generatePDFNodeID = false;
    }
    var destinationElement = PDFCatalogueLibrary.getDOMObjectById( destinationElementId );

    if ( ( typeof destinationElementId ) == 'object' )
    {
        destinationElement = destinationElementId;
    }

    if ( destinationElement !== false )
    {
        PDFCatalogueLibrary.removeCommonTargetDDSources();

        YAHOO.util.Event.on( 'pdfCatalogueCommonTargetArea', 'mouseover', PDFCatalogueLibrary.showCommonTargetArea, null, this );

        PDFCatalogueLibrary.setTagHTMLByObject( destinationElement, resultText );

        var commonNodeIDListString = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueCommonNodeIDList' ),
                     sourceDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueCommonSource' );

        PDFCatalogueLibrary.commonNodeIDList = commonNodeIDListString.split( ',' );

        var isInCommonNodeList = false;
        for ( var i = 0; i < PDFCatalogueLibrary.commonNodeIDList.length; ++i )
        {
            if ( PDFCatalogueLibrary.commonNodeIDList[i] == PDFCatalogueLibrary.currentNodeID )
            {
                isInCommonNodeList = true;
            }
        }
        if ( isInCommonNodeList && sourceDomNode !== false )
        {
            sourceDomNode.innerHTML = '';
        }
        for ( var i = 0; i < PDFCatalogueLibrary.commonNodeIDList.length; ++i )
        {
            var        dropSource = new PDFCatalogueLibrary.DDList( 'document_' + PDFCatalogueLibrary.commonNodeIDList[i] ),
                dropSourceDomNode = PDFCatalogueLibrary.getDOMObjectById( 'document_' + PDFCatalogueLibrary.commonNodeIDList[i] );

            if ( dropSourceDomNode !== false )
            {
                dropSourceDomNode.originalParent = dropSourceDomNode.parentNode.id;
            }
        }

        var insertDomNodeID = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueCommonSourceAreaInsertID' ),
              insertDomNode = false,
             insertPosition = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueCommonSourceAreaInsertPosition' );
        if ( insertDomNodeID !== false )
        {
            insertDomNode = PDFCatalogueLibrary.getDOMObjectById( insertDomNodeID );
        }
        if ( insertPosition === false || ( insertPosition !== 'first' && insertPosition !== 'last' ) )
        {
            insertPosition = 'first';
        }
        var sourceItemDomNode = PDFCatalogueLibrary.getDOMObjectById( 'document_' + PDFCatalogueLibrary.currentNodeID );

        if ( !isInCommonNodeList && PDFCatalogueLibrary.commonDropSource === null )
        {
            PDFCatalogueLibrary.commonDropSource = new PDFCatalogueLibrary.DDList( 'document_' + PDFCatalogueLibrary.currentNodeID );
            PDFCatalogueLibrary.commonDropSource.isTarget = false;
            sourceItemDomNode.originalParent     = 'pdfCatalogueCommonSource';
        }
        if ( insertDomNode !== false && sourceDomNode !== false &&
             sourceDomNode.parentNode.id !== insertDomNode.parentNode.id
           )
        {
            if ( insertPosition === 'first' )
            {
                insertDomNode.parentNode.insertBefore( sourceDomNode, insertDomNode );
            }
            else
            {
                insertDomNode.parentNode.appendChild( sourceDomNode );
            }
            sourceDomNode.style.display = 'block';
            sourceDomNode.style.top = insertDomNode.offsetTop + 'px';
            sourceDomNode.style.left = insertDomNode.offsetLeft + 'px';
            sourceDomNode.style.width = insertDomNode.offsetWidth + 'px';
        }

        PDFCatalogueLibrary.setupTargetList();
        if ( !PDFCatalogueLibrary.commonTargetAreaPrepared )
        {
            YAHOO.util.Dom.setStyle(  PDFCatalogueLibrary.commonTargetAreaDomNode, 'display', 'none' );
        }
    }
}

PDFCatalogueLibrary.updateCommonTargetList = function()
{
    if ( PDFCatalogueLibrary.commonTargetActionURL !== false &&
         PDFCatalogueLibrary.commonTargetAreaDomNode !== false &&
         PDFCatalogueLibrary.currentLocale !== false
       )
    {
        var postData = 'ContentObjectID=0&PDFCatalogueGetItemListButton=PDFCatalogueGetItemListButton&PDFCatalogueGetItemListTranslation=' + encodeURIComponent( PDFCatalogueLibrary.currentLocale );
        PDFCatalogueLibrary.ajaxRequest( PDFCatalogueLibrary.commonTargetActionURL,
                                         PDFCatalogueLibrary.commonTargetAreaDomNode,
                                         postData, PDFCatalogueLibrary.responseUpdateCommonTargetList
                                       );
    }
}

PDFCatalogueLibrary.prepareCommonTargetArea = function()
{
    var insertDomNodeID = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueCommonTargetAreaInsertID' ),
          insertDomNode = false,
         insertPosition = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueCommonTargetAreaInsertPosition' );
    if ( insertDomNodeID !== false )
    {
        insertDomNode = PDFCatalogueLibrary.getDOMObjectById( insertDomNodeID );
    }
    if ( insertPosition === false || ( insertPosition !== 'first' && insertPosition !== 'last' ) )
    {
        insertPosition = 'first';
    }

    PDFCatalogueLibrary.commonTargetAreaDomNode = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueCommonTargetArea' );
    PDFCatalogueLibrary.commonTargetActionURL   = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueCommonTargetActionURL' );
    PDFCatalogueLibrary.currentLocale           = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueCurrentLocale' );

    if ( insertDomNode !== false &&
         PDFCatalogueLibrary.commonTargetAreaDomNode !== false &&
         PDFCatalogueLibrary.commonTargetActionURL !== false &&
         PDFCatalogueLibrary.currentLocale !== false
       )
    {
        if ( insertPosition === 'first' )
        {
            insertDomNode.insertBefore( PDFCatalogueLibrary.commonTargetAreaDomNode, insertDomNode.firstChild );
        }
        else
        {
            insertDomNode.appendChild( PDFCatalogueLibrary.commonTargetAreaDomNode );
        }
        PDFCatalogueLibrary.commonTargetAreaPrepared = true;
    }
    else
    {
        PDFCatalogueLibrary.commonTargetAreaDomNode = false;
        PDFCatalogueLibrary.commonTargetActionURL = false;
        PDFCatalogueLibrary.currentLocale = false;
    }
}

PDFCatalogueLibrary.addIsEmptyFunction = function( domNode )
{
    domNode.isEmpty = function()
    {
        var areaListItems = this.getElementsByTagName( 'li' );

        return ( areaListItems.length < 1 );
    }
}

PDFCatalogueLibrary.initialize = function()
{
    PDFCatalogueLibrary.domNodes.generateButton  = YAHOO.util.Dom.get( 'pdfCatalogueGenerateButton' );
    PDFCatalogueLibrary.domNodes.sendButton      = YAHOO.util.Dom.get( 'pdfCatalogueSendButton' );
    PDFCatalogueLibrary.domNodes.generatingImage = YAHOO.util.Dom.get( 'pdfCatalogueGeneratingImage' );

    PDFCatalogueLibrary.isDedicatedPDFCatalogue = false;

    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();
            }
        }
    }

    if ( PDFCatalogueLibrary.config.documentList !== null &&
         PDFCatalogueLibrary.config.documentList !== undefined
       )
    {
        if ( PDFCatalogueLibrary.config.documentList.length > 0 )
        {
            PDFCatalogueLibrary.isDedicatedPDFCatalogue = true;
        }
        for ( var i = 0; i < PDFCatalogueLibrary.config.documentList.length; i++ )
        {
            var sourceListItems   = PDFCatalogueLibrary.config.documentList[ i ],
                  sourceListID    = 'pdfCatalogueSourceList_' + i,
                sourceListDomNode = PDFCatalogueLibrary.getDOMObjectById( sourceListID ),
                sourceDropTarget  = new YAHOO.util.DDTarget( sourceListID );

            if ( sourceListDomNode !== false )
            {
                PDFCatalogueLibrary.addIsEmptyFunction( sourceListDomNode );
            }

            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 );
            }
        }
    }

    String.prototype.trim = function()
    {
        return this.replace( '/^\s+|\s+$/g', '' );
    }

    if ( !PDFCatalogueLibrary.isDedicatedPDFCatalogue )
    {
        PDFCatalogueLibrary.currentNodeID = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueNodeID' );
        if ( PDFCatalogueLibrary.currentNodeID !== false )
        {
            PDFCatalogueLibrary.prepareCommonTargetArea();
            PDFCatalogueLibrary.updateCommonTargetList();
        }
    }
    else
    {
        PDFCatalogueLibrary.setupTargetList();

        var predefinedIDList = PDFCatalogueLibrary.getTagTextContentById( 'pdfCataloguePredefinedIDList' );

        if ( predefinedIDList !== false )
        {
            var      idList = predefinedIDList.split( ',' ),
                 targetList = PDFCatalogueLibrary.getDOMObjectById( 'pdfCatalogueTargetList' ),
                currentItem = false;
            if ( targetList !== false )
            {
                for ( var i = 0; i < idList.length; ++i )
                {
                    currentItem = PDFCatalogueLibrary.getDOMObjectById( 'document_' + idList[i] );
                    if ( currentItem !== false )
                    {
                        targetList.appendChild( currentItem );
                    }
                }
            }
            if ( !targetList.isEmpty() )
            {
                if ( PDFCatalogueLibrary.domNodes.generateButton )
                {
                    PDFCatalogueLibrary.domNodes.generateButton.disabled = false;
                }
                if ( PDFCatalogueLibrary.domNodes.sendButton )
                {
                    PDFCatalogueLibrary.domNodes.sendButton.disabled = false;
                }
                PDFCatalogueLibrary.pdfGenerate( false );
            }
        }

        YAHOO.util.Event.on( 'pdfCatalogueGenerateButton', 'click', PDFCatalogueLibrary.pdfGenerate, null, this );
        YAHOO.util.Event.on( 'pdfCatalogueSendButton', 'click', PDFCatalogueLibrary.pdfShowSend, null, this );
        YAHOO.util.Event.on( 'pdfCatalogueCancelSendButton', 'click', PDFCatalogueLibrary.pdfCancelSend, null, this );
        YAHOO.util.Event.on( 'pdfCatalogueEmailSender', 'change', PDFCatalogueLibrary.pdfVerifyEmailForm, null, this );
        YAHOO.util.Event.on( 'pdfCatalogueEmailSubject', 'change', PDFCatalogueLibrary.pdfVerifyEmailForm, null, this );
        YAHOO.util.Event.on( 'pdfCatalogueEmailReceiver', 'change', PDFCatalogueLibrary.pdfVerifyEmailForm, null, this );
        YAHOO.util.Event.on( 'pdfCatalogueSendEmailButton', 'click', PDFCatalogueLibrary.pdfSendEmail, 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.convertPage = function( targetURL )
{
    targetURL = targetURL + '/' + PDFCatalogueLibrary.currentNodeID;
    window.location.href = targetURL;
}

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' ),
        verifyURL          = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueVerifyURL' ),
        sendURL            = PDFCatalogueLibrary.getTagTextContentById( 'pdfCatalogueSendURL' );
    PDFCatalogueLibrary.config =
    {
        documentList       : eval( '(' + documentList + ')' ),
        catalogueID        : catalogueID,
        downloadMode       : downloadMode,
        pdfFilename        : pdfFileName,
        noDocumentsWarning : noDocumentsWarning,
        generateURL        : generateURL,
        verifyURL          : verifyURL,
        sendURL            : sendURL,
        downloadURL        : downloadURL
    };
    PDFCatalogueLibrary.initialize();
}

if ( window.attachEvent )
{
    window.attachEvent( 'onload', PDFCatalogueLibrary.setupPDFCatalogue );
}
else if ( window.addEventListener )
{
    window.addEventListener( 'load', PDFCatalogueLibrary.setupPDFCatalogue, false );
}

