/**
 * seeAlsoDisplay.js
 *
 * $Revision: 1.21 $
 * $Date: 2012/01/11 15:37:37 $
 * Last edited by: $Author: danderson $
 */

if( typeof SeeAlsoDisplay === 'undefined' )
{
  var SeeAlsoDisplay = function( sInstancePrefix, sInstanceId, sSeeAlsoInfo, iContextDisplayLimit, sObjectURN, bCanEdit )
  {
    this.sInstancePrefix = sInstancePrefix;
    this.sInstanceId = sInstanceId;
    this.sSeeAlsoInfo = sSeeAlsoInfo;
    this.iContextDisplayLimit = iContextDisplayLimit;
    this.sObjectURN = sObjectURN;
    this.bCanEdit = bCanEdit;
    this.sInstanceName = this.sInstancePrefix + '_' + this.sInstanceId;
    this.oSeeAlsoDisplayContainer = null;
    this.sSeeAlsoDisplayHeader = 'See Also';
    this.oSeeAlsoForm = null;
    this.oOfferingTargetLookup = null;
    this.oMessageArea = null;
    this.oDataField = null;
    this.sUndefinedContextLabelText = 'Other';
    this.sNoSeeAlsosMessage = "None";


    this.init = function()
    {
      this.validate();
      this.oSeeAlsoDisplayContainer = document.getElementById( 'seeAlsoDisplay_' + this.sInstanceId );
      this.drawDataForm();
      this.drawHeader();

      if ( this.bCanEdit )
      {
        this.drawMessageArea();
      }

      this.buildList();

    };

    this.validate = function ()
    {
      if ( this.iContextDisplayLimit === null || isNaN( this.iContextDisplayLimit ) )
      {
        this.iContextDisplayLimit = 0;
      }
    };

    this.drawHeader = function ()
    {
      this.drawAddNewButton();
      /* Display Header - eg See Also */
      var oHeader = document.createElement( 'h4' );
      var oHeaderSpan = document.createElement( 'span' );
      oHeaderSpan.setAttribute('className', 'ui-yakabox-icon-link fltlft');
      oHeaderSpan.setAttribute('class', 'ui-yakabox-icon-link');
      oHeaderSpan.style.backgroundImage='url(/images/icon_seealso.png)';
      var oText = document.createTextNode( this.sSeeAlsoDisplayHeader );
      oHeaderSpan.appendChild( oText );
      oHeader.appendChild( oHeaderSpan );
      this.oSeeAlsoDisplayContainer.appendChild( oHeader );
    };

    this.drawMessageArea = function ()
    {
      /* Create Message Area - loading messages, etc ... */
      this.oMessageArea = document.createElement( 'div' );
      this.oMessageArea.id = 'seeAlsoMessageArea_' + this.sInstanceId;
      this.oMessageArea.className = 'ui-widget';
      this.oSeeAlsoDisplayContainer.appendChild( this.oMessageArea );
    };

    this.drawAddNewButton = function ()
    {
      /* Create Button for adding existing items as See Alsos */

      var seeAlsoButton = null;
      seeAlsoButton = document.getElementById("addnewSeeAlsoButton");
      if (typeof(seeAlsoButton) !== 'undefined' &&  seeAlsoButton !== null)
      {
        seeAlsoButton.style.display = 'inline';
        seeAlsoButton.onclick = this.openAddSeeAlsoWindow();
      }
      else
      {
        var oAddNewSeeAlsoButton = document.createElement( 'button' );
        /* oAddNewSeeAlsoButton.type = 'button'; */
        oAddNewSeeAlsoButton.title = 'Add a See Also';
        oAddNewSeeAlsoButton.setAttribute( 'type', 'button' );
        $( oAddNewSeeAlsoButton ).addClass( 'ui-button ui-button-text-only fltrt' );
        oAddNewSeeAlsoButton.onclick = this.openAddSeeAlsoWindow();

        var oAddNewSeeAlsoText = document.createElement( 'span' );
            oAddNewSeeAlsoText.className = 'ui-button-text';
            oAddNewSeeAlsoText.innerHTML = "Add a See Also";

        oAddNewSeeAlsoButton.appendChild( oAddNewSeeAlsoText );

        this.oSeeAlsoDisplayContainer.appendChild( oAddNewSeeAlsoButton );
      }
    };

    this.drawDataForm = function ()
    {
      /* Create the form that stores See Also data from load and the Interactive Workflow */
      this.oSeeAlsoForm = document.createElement( 'form' );
      this.oSeeAlsoForm.name = "seeAlsoForm_" + this.sInstanceId;
      var oInput = null;

      this.oSeeAlsoForm.target = '_blank';
      this.oSeeAlsoForm.id = "seeAlsoDisplay_" + this.sInstanceId + "_form";
      this.oSeeAlsoForm.method = 'post';
      this.oSeeAlsoForm.action = '/post.html';

      oInput = document.createElement( 'input' );
      oInput.value = '/workflow/setupSeeAlsoInteractiveWorkflow.html';
      oInput.name = 'TargetPage';
      oInput.type = 'hidden';
      this.oSeeAlsoForm.appendChild( oInput );

      oInput = document.createElement( 'input' );
      oInput.name = 'sCallBackFunction';
      oInput.type = 'hidden';
      oInput.value = this.sInstanceName + '.updateCallback';
      this.oSeeAlsoForm.appendChild( oInput );

      oInput = document.createElement( 'input' );
      oInput.name = 'urn';
      oInput.value = this.sObjectURN;
      oInput.type = 'hidden';
      this.oSeeAlsoForm.appendChild( oInput );

      oInput = document.createElement( 'input' );
      oInput.name = 'attachOnSave';
      oInput.value = 'yes';
      oInput.type = 'hidden';
      this.oSeeAlsoForm.appendChild( oInput );

      oInput = document.createElement( 'input' );
      oInput.name = 'sChooserForm';
      /* oInput.value = 'seeAlsoForm_' + this.sInstanceId; */
      oInput.value = '';
      oInput.type = 'hidden';
      this.oSeeAlsoForm.appendChild( oInput );

      oInput = document.createElement( 'input' );
      oInput.name = 'sChooserField';
      oInput.value = 'seeAlsoInfo_' + this.sInstanceId;
      oInput.type = 'hidden';
      this.oSeeAlsoForm.appendChild( oInput );

      oInput = document.createElement( 'input' );
      oInput.name = 'seeAlsoInfo';
      oInput.id = 'seeAlsoInfo_' + this.sInstanceId;
      oInput.value = this.sSeeAlsoInfo;
      oInput.type = 'hidden';
      this.oDataField = oInput;
      this.oSeeAlsoForm.appendChild( oInput );

      $( 'body' ).append( this.oSeeAlsoForm );
    };

    this.buildList = function ()
    {
      var oContainer = null;
      if ( document.getElementById( 'seeAlsoDisplayDataContainer_' + this.sInstanceId ) == null )
      {
        oContainer = document.createElement( 'div' );
        oContainer.id = 'seeAlsoDisplayDataContainer_' + this.sInstanceId;
        this.oSeeAlsoDisplayContainer.appendChild( oContainer );
      }
      else
      {
        oContainer = document.getElementById( 'seeAlsoDisplayDataContainer_' + this.sInstanceId );
        this.clearList();
      }

      var aSeeAlsoInfo = JSON.parse( this.oDataField.value );
      if ( aSeeAlsoInfo.length === 0 )
      {
        return;
      }
      else
      {
        this.clearMessageArea();
      }
      var oTempOfferingTargetLookup = new Object();
      var aChanges = new Array();
      var aRemoveQueue = new Array();

      var oUl = new Object(); /* Array of our lists */
      var oContextContainers = new Object();
      var oContextHeaders = new Object();
      var oSubUl = new Object();
      var bHasUndefinedOffering = false,
        nOfferingCount = 0;

      for( var index = 0; index < aSeeAlsoInfo.length; index++ )
      {
        var sOfferingId = aSeeAlsoInfo[ index ][ 'offeringId' ];
        var sOfferingName = aSeeAlsoInfo[ index ][ 'offeringName' ];

        var sObjectId = aSeeAlsoInfo[ index ][ 'id' ];
        var sObjectName = aSeeAlsoInfo[ index ][ 'name' ];
        var sObjectType = aSeeAlsoInfo[ index][ 'type' ];
        var sImageURL = aSeeAlsoInfo[ index ][ 'image' ];
        var sLinkURL = aSeeAlsoInfo[ index ][ 'link' ];
        var sIdentifier = aSeeAlsoInfo[ index ][ 'type' ] + ':' + aSeeAlsoInfo[ index ][ 'id' ];
        var sRecordType = aSeeAlsoInfo[ index ][ 'recordType' ];

        if ( sOfferingName === 'undefined' || sOfferingName === '')
        {
          bHasUndefinedOffering = true;
          sOfferingName = this.sUndefinedContextLabelText;
        }
       /* If the UL for this Context doesn't exist, create it */
        if ( typeof oUl[ sOfferingName ] === 'undefined' )
        {
          nOfferingCount++;
          /* Make Entry In Lookup */
          oTempOfferingTargetLookup[ sOfferingName ] = new Object();

          /* Create UL */
          oUl[ sOfferingName ] = new Object();
          oUl[ sOfferingName ][ 'count' ] = 0;

          /* Create Header with Context Name and Quick Add Link */
          oUl[ sOfferingName ][ 'html' ] = document.createElement( 'ul' );
          oUl[ sOfferingName ][ 'html' ].className = 'ui-yakawidget-list-horizontal';

          oContextHeaders[ sOfferingName ] = document.createElement( 'h4' );
          oContextHeaders[ sOfferingName ].id = 'contextListItem_' + sOfferingName + '_' + this.sInstanceId;

          /* Icon for Context Name */
          var oIcon = document.createElement('span');
          oIcon.className = 'ui-yakabox-icon ui-yakabox-icon-seealso';

          /* Label for Context Name */
          var oSpan = document.createElement('span');
          oSpan.className = 'ui-widget-title';

          var oHeaderLabel = document.createTextNode( sOfferingName );

          oContextHeaders[ sOfferingName ].appendChild( oIcon );
          oContextHeaders[ sOfferingName ].appendChild( oSpan );
          oSpan.appendChild( oHeaderLabel );

          /* Link for QuickAdd */
          if ( this.bCanEdit )
          {
            var oQuickAddLink = document.createElement( 'span' );
            oQuickAddLink.title = 'Add Document';
            oQuickAddLink.className = 'ui-icon ui-icon-plusthick';
            oQuickAddLink.target = '';
            oQuickAddLink.onclick = this.openAddSeeAlsoWindow();
            oContextHeaders[ sOfferingName ].appendChild( oQuickAddLink );
          }



        }
        oTempOfferingTargetLookup[ sOfferingName ][ sIdentifier ] = new Object();

        /* Set the Delete Container ID */
        var sDeleteContainerId  ='SeeAlsoDisplay_' + this.sInstanceId + '_deleteIcon_' + sOfferingName + '_' + oUl[ sOfferingName ][ 'count' ];
        if ( this.bCanEdit )
        {
          /* Create the link for delete */
          var oDeleteLink = document.createElement( 'button' );
          oDeleteLink.onclick = this.removeItem( sObjectId, sObjectType, sRecordType );
          $(oDeleteLink).addClass('ui-button ui-state-default ui-corner-all');

          /* Create the Trash Can */
          var oIcon = document.createElement( 'span' );
          oIcon.title = 'Remove Item';
          oIcon.className = 'ui-icon ui-icon-trash';

          /* Add the image to the link */
          oDeleteLink.appendChild( oIcon );
          /* oDeleteSpan.appendChild( oLink ); */
          /* Add the Link to the LI */
        }

        /* Create Link to the Target */
        var oLink = document.createElement( 'a' );
        $(oLink).addClass('ui-yakabox-icon-link');
        $(oLink).css('backgroundImage','url(' + sImageURL +')');
        $(oLink).css('display', 'block');
        $(oLink).attr('href', sLinkURL);

        /* Create the Label LI */
        var oReasonLi = document.createElement( 'li' );
        $(oReasonLi).addClass('ui-helper-clearfix ui-state-default ui-corner-all ui-border-none');

        if ( this.bCanEdit && this.oOfferingTargetLookup !== null  && ( typeof this.oOfferingTargetLookup[ sOfferingName ] !== 'object' || typeof this.oOfferingTargetLookup[ sOfferingName ][ sIdentifier ] !== 'object' ) )
        {
          aChanges.push( oReasonLi );
        }

        /* Create Link to the Target */
        var oLink = document.createElement( 'a' );
        $(oLink).addClass('ui-yakabox-icon-link');
        $(oLink).css('backgroundImage','url(' + sImageURL +')');
        $(oLink).attr('href', sLinkURL);

        /* Create the Label */
        /* var oTextNode = document.createTextNode( sObjectName ); */
        /* Add the Label to the Link */
        $(oLink).append( sObjectName );
        /* Add the Link to the LI */
        oReasonLi.appendChild( oLink );

        if( oUl[ sOfferingName ][ 'count' ] >= this.iContextDisplayLimit )
        {
          if ( typeof oSubUl[ sOfferingName ] === 'undefined' )
          {
            /* Create the sub UL for hidden contexts */
            oSubUl[ sOfferingName ] = $( '<span id="moreContextArea_' + sOfferingName + '_' + this.sInstanceId + '" />' ).hide()[ 0 ];
          }

          if ( this.bCanEdit )
          {
            $(oDeleteLink).appendTo(oReasonLi);
          /* oLink.appendChild( oDeleteLink ); */
          }

        /* oSubUl[ sOfferingName ].appendChild( oIconLi ); */
          oSubUl[ sOfferingName ].appendChild( oReasonLi );
        }
        else
        {
          if ( this.bCanEdit )
          {
            $(oDeleteLink).appendTo(oReasonLi);
          }
          oUl[ sOfferingName ][ 'html' ].appendChild( oReasonLi );
        }
        oUl[ sOfferingName ][ 'count' ]++;
      }

      /* Copy the See Also Info to the Member Variable */
      this.oOfferingTargetLookup = oTempOfferingTargetLookup;

      for( var sOfferingName in oUl )
      {
        if( Object.prototype.hasOwnProperty.call( oUl, sOfferingName ) )
        {
          var oWidgetWrapper = $( '<div class="ui-widget" />' )[ 0 ];

          oContainer.appendChild( oWidgetWrapper );

          /*  if we only have the undefined offering, then don't show the header  */
          if( !bHasUndefinedOffering || nOfferingCount != 1 )
          {
            oWidgetWrapper.appendChild( oContextHeaders[ sOfferingName ] );
          }


          if ( typeof oSubUl[ sOfferingName ] != 'undefined' )
          {

            var oLi = $( '<li class="ui-state-default ui-border-none ui-corner-all ui-yakabox-link"><span class="ui-icon ui-icon-circle-triangle-s ybx-icon"></span> <a class="ui-yakabox-link ybx-label">More</a></li>' ).
              click( function()
              {
                var bIsVisible = $( this ).prev().is( ':visible' ),
                  text = 'More';

                if( !bIsVisible )
                {
                  text = 'Less';
                }

                $( this )
                  .find( '.ybx-icon' )
                    .toggleClass( 'ui-icon-circle-triangle-n', !bIsVisible )
                    .toggleClass( 'ui-icon-circle-triangle-s', bIsVisible )
                    .end()
                  .find( 'a.ybx-label' )
                    .text( text )
                    .end()
                  .prev()
                    .toggle( !bIsVisible );
              } )[ 0 ];


            oUl[ sOfferingName ][ 'html' ].appendChild( oSubUl[ sOfferingName ] );
            oUl[ sOfferingName ][ 'html' ].appendChild( oLi );
          }

          oWidgetWrapper.appendChild( oUl[ sOfferingName ][ 'html' ] );
          initWidgetUI(oWidgetWrapper);
        }
      }

      if ( this.bCanEdit )
      {
        for( var i = 0; i < aChanges.length; i++ )
        {
          highlight( aChanges[ i ] );
        }
      }
    };

    this.removeItem = function ( sId, sType, sRecordType )
    {
      var oThis = this;
      return function()
      {
        /* Show Processing Message and Spinny */
        /* oThis.displayMessage( 'Processing...', true ); */

        $( this ).find( '.ui-icon' ).removeClass( 'ui-icon ui-icon-trash' ).addClass( 'ui-yakabox-icon ui-yakabox-icon-loading' );

        $.ajax( {
          url: '/removeseealso.html',
          dataType: 'json',
          data: {
            sURN: oThis.sObjectURN,
            sObjectId: sId,
            sObjectType: sType,
            sRecordType: sRecordType
          },
          success: function( oResult )
          {
            if ( oResult[ 'success' ] == 'TRUE' )
            {
              /* Edit the form field */
              var sFieldData = oThis.oDataField.value;
              var aData = JSON.parse( sFieldData );
              var aNewData = new Array();
              for( var index = 0; index < aData.length; index++ )
              {
                if ( ( aData[ index ].id != sId ) || ( aData[ index ].type != sType ) )
                {
                  aNewData.push( aData[ index ] );
                }
              }
              oThis.oDataField.value = JSON.stringify( aNewData );
              oThis.clearMessageArea();
              oThis.buildList();
            }
            else
            {
              oThis.displayMessage( 'An Error Occurred' );
            }
          },
          error: function()
          {
            oThis.displayMessage( 'An Error Occurred' );
          },
          timeout: 30000
        } );

        return false;
      };
    };

    this.openAddSeeAlsoWindow = function ()
    {
      var oForm = this.oSeeAlsoForm;
      return ( function() {
                 oForm.submit();
              });
      return false;
    };

    this.showDeleteIcon = function ( oObject )
    {
      return ( function(){ oObject.style.visibility = 'visible'; return true; });
    };

    this.hideDeleteIcon = function ( oObject )
    {
      return ( function(){ oObject.style.visibility = 'hidden'; return true; });
    };

    this.toggleDisplayMoreItems  = function ( sOfferingName, sInstanceId )
    {
      return ( function()
               {
                 show_hide( 'moreContextArea_' + sOfferingName + '_' + sInstanceId );
                 openClose( '_moreContextArrow_' + sOfferingName + '_' + sInstanceId );
                 return false;
               });
    };

    this.clearList = function ()
    {
      if ( document.getElementById( 'seeAlsoDisplayDataContainer_' + this.sInstanceId ) != null )
      {
        var oContainer = document.getElementById( 'seeAlsoDisplayDataContainer_' + this.sInstanceId );

        /* delete all child objects */
        if(oContainer.hasChildNodes())
        {
          while(oContainer.childNodes.length >= 1 )
          {
            oContainer.removeChild(oContainer.firstChild);
          }
        }
      }
    };

    this.updateCallback = function ()
    {
      this.buildList();
    };

    this.displayMessage = function( sText, bShowImage )
    {
      if ( this.bCanEdit)
      {
        this.clearMessageArea();
        if ( bShowImage)
        {
          var oLoadingImage = document.createElement( 'img' );
          oLoadingImage.src = '/images/loading.gif';
          this.oMessageArea.appendChild( oLoadingImage );
        }

        var oText = document.createTextNode( sText );
        this.oMessageArea.className = 'ui-widget';
        this.oMessageArea.appendChild( oText );
      }
    };

    this.clearMessageArea = function()
    {
      if (this.oMessageArea !== null && typeof this.oMessageArea !== 'undefined')
      {
        this.oMessageArea.innerHTML = '';
        this.oMessageArea.className = '';
      }
    };
    this.init();

  };
}

