/**
 * Copyright (c) 2008 Yakabod, inc.
 * File: MicroProfile.inc
 *
 * $Id: microProfiles.js,v 1.60 2012/01/11 15:37:37 danderson Exp $
 * $Revision: 1.60 $
 * $Date: 2012/01/11 15:37:37 $
 * Last edited by: $Author: danderson $
 *
 * Stuff used by the MicroProfiles
 *
 */

function prepareToToggle( bDisplayInPanel, sMicroDiv )
{
  var $MicroDiv;
  if ( bDisplayInPanel )
  {
    $MicroDiv = $( '.ui-microprofile-viewer' );
    if ( sMicroDiv !== undefined && sMicroDiv.length > 0 )
    {
      $MicroDiv.attr('id', sMicroDiv);
    }
    else
    {
      $MicroDiv.attr('id', '');
    }
		
			var $ybxpanel = $( '#ybx-panel' ),
			$ybxpaneltrigger = $( '.ybx-panel-trigger' );
		
		
		  if( $.browser.msie )
				{
					$.fx.off = 'true'
				}
			
		if( $ybxpanel.is( ':visible' ) )
				{
					$ybxpaneltrigger.parent().effect( "slide", { direction:'right', distance:100 }, 00);
					$ybxpanel.effect( "slide", { direction:'right', distance:100 }, 400);
					$ybxpanel.effect( "slide", { direction:'left', distance:10 }, 200);
					$ybxpaneltrigger.parent().effect( "slide", { direction:'right', distance:100 }, 200);

				}
				else
				{
					$ybxpanel.show( "bounce", { direction:'left', times:2, distance:10 }, 400);
					$ybxpaneltrigger.find('span').removeClass('ui-icon-circle-triangle-w').addClass('ui-icon-circle-triangle-e');
					$( 'body' ).addClass( 'ui-yakabox-layout-flex ui-yakabox-layout-panel' );
					$ybxpaneltrigger.parent().show( "bounce", { direction:'left', times:2, distance:10 }, 400);

				}
			}
  else
  if ( sMicroDiv !== undefined && sMicroDiv.length > 0 )
  {
    $MicroDiv = $( '[id="' + sMicroDiv + '"]' );
    $MicroDiv
      .parent()
        .parent()
          .removeClass('ui-state-hover')
          .toggleClass('ui-state-active');

    show_hide( sMicroDiv );
  }

  return $MicroDiv;
}

function toggleMicroProfile( sObjectUrn, sMicroDiv, nObjectCommentId, bHideRankControl, sUserAlertURN, nTransactionId, bUserAlertRoadblocked )
{

  var $MicroDiv = prepareToToggle( false, sMicroDiv );

  $MicroDiv
    .filter( ':visible' )
      .each( function()
      {
        var href, url, params;

        href = '/microProfiles/viewMicroProfile.html';

        params = {
          urn: sObjectUrn,
          nObjectCommentId: nObjectCommentId,
          bHideRankControl: bHideRankControl,
          userAlertURN: sUserAlertURN,
          transactionId: nTransactionId,
          userAlertRoadblocked: ( bUserAlertRoadblocked ? '1' : '0' ),
          microDiv: sMicroDiv
        };

        url = href + '?' + $.param( params );

        bindMicroProfile( sMicroDiv, url, false );

        return false;
      } );
}

function toggleContentProfile( aToggleInfo, bDisplayInPanel, sMicroDiv )
{
  /* toggles open the content either in the panel viewer or the div specified */
  var $MicroDiv = prepareToToggle( bDisplayInPanel, sMicroDiv );
  $( '.ui-microprofile-viewer' ).data('atoggleinfo', aToggleInfo);

  $MicroDiv
    .filter( ':visible' )
      .each( function()
      {
        var href, url, params;

        href = '/microProfiles/viewMicroProfile.html';

        params = {};
        for (var sParam in aToggleInfo)
        {
          /* Only add the parameters that have been defined */
          if (aToggleInfo[sParam] !== 'undefined')
          {
            params[sParam] = aToggleInfo[sParam];
          }
        }
        params['microDiv'] = sMicroDiv;

        url = href + '?' + $.param( params );

        bindMicroProfile( sMicroDiv, url, bDisplayInPanel );

        return false;
      } );
}

function bindMicroProfile( sMicroDiv, sUrl, bDisplayInPanel )
{
  var $MicroDiv;
  if ( bDisplayInPanel === true)
  {
    $MicroDiv = $( '.ui-microprofile-viewer' );
  }
  else
  {
    $MicroDiv = $( '[id="' + sMicroDiv + '"]' );
  }

  $MicroDiv
    .html( '&nbsp;<img src="/images/loading.gif" align="absmiddle">&nbsp;Loading Info...' )
    .each( function()
    {
      $.ajax( {
        url: sUrl,
        dataType: 'json',
        success: function( data )
        {
          $MicroDiv.html( data.page_data );
          $LAB.executeQueue();
        },
        error: function( XMLHttpRequest, textStatus, errorThrown )
        {
          alert( 'Error loading micro profile:' + errorThrown );
        }
      } );

      return false;
    } );
}

function toggleUserFavoriteProfile( sObjectUrn, sMicroDiv, sObjectType, nUserFavoriteId )
{
  var $MicroDiv = prepareToToggle( true, sMicroDiv );

  $MicroDiv
    .filter( ':visible' )
    .each( function()
    {
      var params, href, url;

      params = {
        urn: sObjectUrn
      };

      switch( sObjectType )
      {
        case 'OBJECTPREFERENCE':
          href = '/userFavorite/objectPreferenceFavoriteProfile.html';
          params.nUserFavoriteId = nUserFavoriteId;
          break;

        case 'OFFERING':
          href = '/offering/OfferingProfile.html';
          params.nUserFavoriteId = nUserFavoriteId;
          params.bHideRankControl = true;
          break;

        default:
          href = '/microProfiles/viewMicroProfile.html';
          params.nObjectCommentId = '';
          params.bHideRankControl = true;
          break;
      }

      url = href + '?' + $.param( params );

      bindMicroProfile( sMicroDiv, url, true );

      return false;
    } );
}

function toggleItineraryEvent( aToggleInfo, nUserItineraryId, sMicroDiv )
{
  var $MicroDiv = prepareToToggle( true, sMicroDiv );

  $MicroDiv
    .filter( ':visible' )
      .each( function()
      {
        var href, url, params;

        href = '/microProfiles/viewMicroProfile.html';

        params = {
          urn: aToggleInfo.urn,
          tUpcomingStart: aToggleInfo.tStartDate,
          nUserItineraryId: nUserItineraryId
        };

        url = href + '?' + $.param( params );

        bindMicroProfile( sMicroDiv, url, true );

        return false;
      } );
}

function markMessageRead( sDivId, sUnreadId, bShowLink )
{
  /* Note - we are just decrementing the count on the window,
   * which is currently not updated by the polling.  Don't let it go negative!
   */

  var sMPDivId = 'microProfileDiv' + sDivId,
      $IconDiv = $( '#' + sMPDivId + 'IconClass' );

  if( $IconDiv.hasClass( 'ybx-unread' ) === true )
  {
    $( '#' + sMPDivId )
      .removeClass( 'ui-widget-content' )
      .addClass( 'ui-state-default' );

    $IconDiv
      .removeClass( 'ybx-unread ui-icon-ybx-unread' )
      .addClass( 'ybx-read ui-state-default' )
      .attr( 'title', '' );
  }
}

function updateUnreadMessageCount(nCount, sUnreadId, bShowLink)
{
  var liMessages = $( '#' + sUnreadId ).find('.ybx-unreadCount');
  var sTitle = nCount;
  var sHtml;

  if (liMessages.length !== 0)
  {
    if (bShowLink)
    {
      sHtml = '<a href="/message/" target="_blank" class="ui-yakabox-icon-link" style="background-image:url(/images/icon_message.png)" title="' +  sTitle + '"><strong>Messages</strong><span class="ui-state-highlight ui-corner-all">' + nCount + '</span></a>';
    }
    else
    {
      sHtml = sTitle;
    }

    liMessages.html(sHtml);
  }
}

function processInfoReceived(sMicroDiv, serverResponse)
{
  try
  {
    var $MicroDiv;
    if ( sMicroDiv !== undefined && sMicroDiv.length > 0 )
    {
      $MicroDiv = $( '[id="' + sMicroDiv + '"]' );
    }
    else
    {
      $MicroDiv = $( '.ui-microprofile-viewer' );
    }

    $MicroDiv.html( serverResponse.page_data );
    $LAB.executeQueue();
  }
  catch (e)
  {
    alert( 'e:' + e.toSource() + '\n\n Data received for profile:\n' + serverResponse );
  }
}

function votePoll( sUrn, nPollId, nResponseId, sRoadblock, sEmbeddedPollTemplate, bExportEvent )
{
  var sPollDiv = 'embeddedPoll' + sUrn;

  $( '[id="' + sPollDiv + '"]' )
    .each( function()
    {
      $( this ).html( '&nbsp;<img src="/images/loading.gif" align="absmiddle">&nbsp;Submitting...' );

      $.ajax( {
        url: '/microProfiles/viewMicroProfile.html',
        type: 'GET',
        data: {
          urn: sUrn,
          pollId: nPollId,
          response: nResponseId,
          roadblock: sRoadblock,
          sEmbeddedPollTemplate: sEmbeddedPollTemplate
        },
        dataType: 'json',
        success: function( data, textStatus )
        {
          var $PollDiv = $( '[id="' + sPollDiv + '"]' )
                           .html( data.page_data );

          var childdiv = $PollDiv[0],
              divMicroProfile = findMicroProfileDiv( childdiv );
          
          if ( sRoadblock === 'Y' && divMicroProfile )
          {
            toggleRoadblockStyle( divMicroProfile, false );
            $PollDiv.find('.ui-widget-roadblock').removeClass('ui-widget-roadblock');
          }

          /* If we are not exporting the event and it is living on the Itinerary page,
           * then just remove it from the DOM, otherwise stuff the new data into the div.
           * NOTE: if we make the auto-export optional on acceptance, we will have to pass
           * some other variable to indicate that the user has declined and we should remove it.
           */
          if (!bExportEvent && divMicroProfile && divMicroProfile.hasClass('ybx-Itinerary'))
          {
            divMicroProfile.remove();
          }

          if (bExportEvent)
          {
            window.location.href = '/events/exportEvent.html?urn=' + escape(sUrn) + '&popup=true';
          }
        },
        error: function( XMLHttpRequest, textStatus, errorThrown )
        {
          alert( 'Error Voting:' + errorThrown );
        }
      } );

      return false;
    } );
}

function toggleRoadblock( oEvent, optForcedState )
{
  /**
   * Make sure we have the event object
   **/
  if ( !oEvent )
  {
    oEvent = null;
    if ( window.event )
    {
      oEvent = window.event;
    }
  }

  if ( typeof oEvent == 'object' && oEvent !== null )
  {
    var oTarget = null;
    if( typeof oEvent.srcElement == 'object' )
    {
      oTarget = oEvent.srcElement;
    }
    else if( typeof oEvent.target == 'object' )
    {
      oTarget = oEvent.target;
    }

    if( oTarget !== null && typeof oTarget == 'object' && typeof oTarget.parentNode == 'object' )
    {
      var oParentNode = oTarget.parentNode;
      if( oParentNode )
      {
        var oProfileContainer = findMicroProfileDiv(oParentNode);
        if (oProfileContainer)
        {
          toggleRoadblockStyle(oProfileContainer, optForcedState);
        }
      }
    }
  }
}

function findMicroProfileDiv(divParent)
{
  /* Finds the Microprofile div */
  var $oDivMicroprofile = null;
  var sWorkingId  = null;

  /* See if it's living in the ui-microprofile-viewer */
  var $MicroViewerDiv = $( divParent ).closest('.ui-microprofile-viewer');
  if ($MicroViewerDiv.length)
  {
    var sDivId = $MicroViewerDiv.attr("id");
    if (sDivId)
    {
      sWorkingId = "microProfileDiv" + $MicroViewerDiv.attr("id");
      $oDivMicroprofile = $( '[id="' + sWorkingId + '"]' );
    }
  }
  else
  {
    while(divParent && (divParent != document ))
    {
      sWorkingId = divParent.id;
      if (sWorkingId && sWorkingId.match(/^microProfileDiv/))
      {
        $oDivMicroprofile = $( '[id="' + divParent.id + '"]' );
        break;
      }
      divParent = divParent.parentNode;
    }
  }

  return $oDivMicroprofile;
}

function toggleRoadblockStyle( $oProfileContainer, optForcedState)
{
  // Toggles the roadblock style (or, optionally, forces it on or off)

  var sDiv = $oProfileContainer.attr("id");
  var $oTrashBin = $( '[id="' + sDiv + 'TrashBin"]' );
  var $oPin = $( '[id="' + sDiv + 'Pin"]' );
  var $oRBButton = $( '[id="' + sDiv + 'RBButton"]' );
  var $oArrow = null;

  var aImgs = $oProfileContainer.find('img');
  if ( aImgs && ( aImgs.length > 0 ) )
  {
    for( var i = 0; i < aImgs.length; i++ )
    {
      if( aImgs[i].id.match(/^arrowmicroView/) )
      {
        $oArrow = aImgs[i];
        break;
      }
    }
  }
  var bAddRoadBlock = false;
  if (optForcedState !== undefined)
  {
    bAddRoadBlock = optForcedState;
  }
  else
  {
    bAddRoadBlock = $oProfileContainer.hasClass('ui-widget-roadblock');
  }

  if ( bAddRoadBlock )
  {
    $oProfileContainer.addClass('ui-widget-roadblock');
    $oTrashBin.hide();
    $oPin.hide();
    $oRBButton.show();
    if ( $oArrow !== null && $oArrow.length > 0 )
    {
      if ( $oRBButton.length > 0 )
      {
        /* We only hide the arrow if there's a View Roadblock button now showing */
        $oArrow.parent().hide();
      }
      else
      {
        $oArrow.parent().show();
      }
    }
  }
  else
  {
    $oProfileContainer.removeClass('ui-widget-roadblock');
    $oTrashBin.show();
    $oPin.show();
    $oRBButton.hide();
    if ( $oArrow !== null && $oArrow.length > 0 )
    {
      $oArrow.parent().show();
    }
  }
}

function serverCompleteRoadblock(oButtonEl, oEvent, sUserAlertURN, fCallback, bRemoveButton)
{
  var oSpinner = document.createElement('img');
  oSpinner.id = 'spinner_'+ oButtonEl.id;
  oSpinner.src = '/images/loading.gif';
  oSpinner.align = 'absbottom';
  oButtonEl.parentNode.replaceChild(oSpinner, oButtonEl);

  /**
   * Making a copy of the event object for use in the getJSON
   * callback.  This is because IE is really friggin retarded
   * and doesn't deal with passing the events around very well.
   */
  var oTmpEvent = {};
  for( var sKey in oEvent )
  {
    oTmpEvent[sKey] = oEvent[sKey];
  }

  $.getJSON(
      '/alerts/clearRoadblock.html',
      {urn: sUserAlertURN},
      function(aResponseData)
      {
        /* add the button back or we won't find the div to toggle */
        oSpinner.parentNode.replaceChild(oButtonEl, oSpinner);

        if(aResponseData.bSuccess)
        {
          toggleRoadblock(oTmpEvent, false);

          /*  this is an optional parameter */
          if( typeof bRemoveButton === 'undefined' || bRemoveButton === null || bRemoveButton === true )
          {
            /* Get rid of the button, as we no longer need it */
            var oLoadingTextEl = document.createTextNode('');
            oButtonEl.parentNode.replaceChild(oLoadingTextEl,oButtonEl);
          }
        }

        if(typeof(fCallback) == 'function')
        {
          fCallback();
        }

        if(aResponseData.bRedirect && aResponseData.sRedirectURL !== null && aResponseData.sRedirectURL.length > 0)
        {
          window.open( aResponseData.sRedirectURL );
        }
      }
    );
}

/**
 * Hover and mouse over effects
 */
function highlighter( ele )
{
  var $;

  $ = window.jQuery;

  if( typeof ele !== 'undefined' && ele !== null )
  {
    if( typeof ele === 'object' && ! ( ele instanceof $ ) )
    {
      ele = $( ele );
    }
    else if( typeof ele === 'string' )
    {
      ele = $( '#' + ele );
    }

    if( ele instanceof $ )
    {
      ele
        .filter( ':not(.ui-state-hover, .ui-state-active)' )
          .addClass( 'ui-state-hover' );
    }
  }
}

function lowlighter( ele )
{
  var $;

  $ = window.jQuery;

  if( typeof ele !== 'undefined' && ele !== null )
  {
    if( typeof ele === 'object' && ! ( ele instanceof $ ) )
    {
      ele = $( ele );
    }
    else if( typeof ele === 'string' )
    {
      ele = $( '#' + ele );
    }

    if( ele instanceof $ )
    {
      ele
        .filter( ':not(.ui-state-highlight, .ui-state-active)' )
          .removeClass( 'ui-state-hover' );
    }
  }
}

function initMicroProfileButtons( sInstanceIdentifier, urn, userAlertURN, sTitle, sHost, objectId, icon )
{
  /* Connect up common functionality for MicroProifles  */

  "use strict";

  var $ = window.jQuery,
      ContentAddModuleController = window.ContentAddModuleController,
      ContentAddSettings_VLogEntry = window.ContentAddSettings_VLogEntry;

  $('#btnHistory' + sInstanceIdentifier)
    .click( function( e )
    {
      window.open( '/common/getObjectHistory.html?urn=' + escape( urn ) );
      e.preventDefault();
    } );

  $('#ybx-ClearRoadblock' + sInstanceIdentifier)
    .click( function( e )
    {
      serverCompleteRoadblock(this, e, userAlertURN);
      e.preventDefault();
    } );

    $('#ybx-blog-it' + sInstanceIdentifier).click( function( e )
    {
      var sBody = 'I published <a class="url" href=https://' + sHost + '/common/getObject.html?urn=' + urn + '>' + sTitle + '</a>';
      var oSeeAlso = [{ id: objectId,
                        name: sTitle,
                        type: 'calendar',
                        urn: urn,
                        image: icon
      }];

      var oContentAddModuleController = new ContentAddModuleController( ( new ContentAddSettings_VLogEntry() )
                                                                                .addObjectPreference( 'Summary', sBody )
                                                                                  .setSeeAlso( oSeeAlso )
                                                                                    .getFullSettings());

      e.preventDefault();
      return oContentAddModuleController;
    } );

  $('#ybx-set-status' + sInstanceIdentifier)
    .bind('click', {urn: urn, sTitle: sTitle, sHost: sHost}, function(e)
    {
      var sBody = 'published <a class="urn" href=https://' + e.data.sHost + '/common/getObject.html?urn=' + e.data.urn + '>' + e.data.sTitle + '</a>';

    $.ajax( {
      url: '/statusUpdater.html',
      type: 'POST',
      data: {
        Title: sBody,
        seeAlsoUrn: urn
      },

      success: function( serverResponse )
      {
        var $MyStatusDisplay = $( '#viewStatus' );
        if ( $MyStatusDisplay.length > 0 )
        {
          var sUpdatedStatus = $( '<div>' + sBody + '</div>' ).text();
          $MyStatusDisplay.text( sUpdatedStatus );
          $( '#Title' ).val( sBody );
        }
      },
      error: function( oXHR, sTextStatus )
      {
      },
      timeout: 30000
    } );

      e.preventDefault();
    } );
}

function refreshContentPanel(oEvent, oData)
{
  var $MicroViewerDiv = $( '.ui-microprofile-viewer' );

  if ($MicroViewerDiv.length > 0)
  {
    var aToggleInfo = $MicroViewerDiv.data('atoggleinfo');
    var sDivId = $MicroViewerDiv.attr("id");

    if (aToggleInfo !== undefined && sDivId !== undefined)
    {
      if (String(oData.object.sURN) === String(aToggleInfo.urn))
      {
        toggleContentProfile( aToggleInfo, true, sDivId );
      }
    }
  }
}

$( document ).bind( ContentAddModuleController.callbacks.defaultEvents.success, refreshContentPanel );
