/**
 * Copyright (c) 2008 Yakabod, inc.
 * File: MicroProfile.inc
 *
 * $Id: microProfiles.js,v 1.43 2010/01/06 14:48:45 yli Exp $
 * $Revision: 1.43 $
 * $Date: 2010/01/06 14:48:45 $
 * Last edited by: $Author: yli $
 *
 * Stuff used by the MicroProfiles
 *
 */

function toggleMicroProfile(sObjectUrn, sMicroDiv, nObjectCommentId, bHideRankControl, sUserAlertURN, nTransactionId, bUserAlertRoadblocked)
{
  //show_hideObjectInfo(sMicroDiv);
  show_hide(sMicroDiv);
  var object = document.getElementById(sMicroDiv);

  if((!object) || (object.style.display == "none"))
  {
    return;
  }
  else
  {
    var url = "/microProfiles/viewMicroProfile.html?urn="
        + sObjectUrn
        + "&nObjectCommentId="
        + nObjectCommentId
        + "&bHideRankControl="
        + bHideRankControl
        + "&userAlertURN="
        + escape(sUserAlertURN)
        + "&transactionId="
        + escape(nTransactionId)
        + "&userAlertRoadblocked="
        + (bUserAlertRoadblocked?'1':'0')
        + "&microDiv="
        + sMicroDiv;

    bindMicroProfile(sMicroDiv, url);
  }
}

function bindMicroProfile(sMicroDiv, sUrl)
{
  childdiv = $('[id="'+sMicroDiv+'"]')[0];
  if(( typeof childdiv !== 'undefined' ) && ( childdiv != null ))
  {
    childdiv.innerHTML = '&nbsp;<img src="/images/loading.gif" align="absmiddle">&nbsp;Loading Info...';

    $.ajax({ url      : sUrl,
             dataType : 'json',
             success  : function( data, textStatus )
                        {
                          processInfoReceived(sMicroDiv, data);
                        },
             error    : function( XMLHttpRequest, textStatus, errorThrown )
                        {
                          alert('Error loading micro profile:' + errorThrown);
                        }
           });
  }
}

function toggleUserFavoriteProfile(sObjectUrn, sMicroDiv, sObjectType, nUserFavoriteId)
{
  //show_hideObjectInfo(sMicroDiv);
  show_hide(sMicroDiv);
  var object = document.getElementById(sMicroDiv);

  if((!object) || (object.style.display == "none"))
  {
    return;
  }
  else
  {
    if (sObjectType == 'OBJECTPREFERENCE')
    {
      var url = "/userFavorite/objectPreferenceFavoriteProfile.html?urn=" + sObjectUrn + "&nUserFavoriteId=" + nUserFavoriteId;
    }
    else
    {
      var url = "/microProfiles/viewMicroProfile.html?urn=" + sObjectUrn + "&nObjectCommentId=''" + "&bHideRankControl=" + true;
    }

    bindMicroProfile(sMicroDiv, url);
  }
}

function processInfoReceived(divId, serverResponse)
{
  try
  {
    $('[id="'+divId+'"]').html( serverResponse.data );
    vneOnload.trigger();
  }
  catch (e)
  {
    alert('e:' + e.toSource() + '\n\n Data received for profile:\n' + serverResponse);
  }
}


function votePoll(sUrn, nPollId, nResponseId, sRoadblock, sEmbeddedPollTemplate)
{
  sPollDiv = 'embeddedPoll' + sUrn;
  childdiv = $('[id="'+sPollDiv+'"]')[0];
  if(( typeof childdiv !== 'undefined' ) && ( childdiv != null ))
  {
    var sUrl = "/microProfiles/viewMicroProfile.html?urn=" + sUrn + "&pollId=" + nPollId +
               "&response=" + nResponseId + "&roadblock=" + sRoadblock + "&sEmbeddedPollTemplate=" + sEmbeddedPollTemplate;

    childdiv.innerHTML = '&nbsp;<img src="/images/loading.gif" align="absmiddle">&nbsp;Submitting...';

    $.ajax({ url      : sUrl,
             dataType : 'json',
             success  : function( data, textStatus )
                        {
                          if (sRoadblock == 'Y')
                          {
                            var divMicroProfile = findMicroProfileDiv(childdiv);
                            if (divMicroProfile)
                            {
                              toggleRoadblockStyle(divMicroProfile, false);
                            }
                          }
                          processVote(sPollDiv, data);
                        },
             error    : function( XMLHttpRequest, textStatus, errorThrown )
                        {
                          alert('Error Voting:' + errorThrown);
                        }
           });
  }
}

function processVote(sPollDiv, serverResponse)
{
  try
  {
    var childDiv = ($('[id="'+sPollDiv+'"]').html( serverResponse.data ))[0];
  }
  catch (e)
  {
    alert('e:' + e.toSource() + '\n\n Data received for profile:\n' + data);
  }
}

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 divMicroprofile = null;
  var sWorkingId  = null

  while(divParent && (divParent != document ))
  {
    sWorkingId = divParent.id;
    if (sWorkingId && sWorkingId.match(/^microProfileDiv/))
    {
      divMicroprofile = divParent;
      break;
    }
    divParent = divParent.parentNode;
  }

  return divMicroprofile;
}

function toggleRoadblockStyle(oProfileContainer, optForcedState)
{
  // Toggles the roadblock style (or, optionally, forces it on or off)
  var oTrashBin = document.getElementById( oProfileContainer.id + 'TrashBin' );
  var oPin = document.getElementById( oProfileContainer.id + 'Pin' );
  var oRBButton = document.getElementById( oProfileContainer.id + 'RBButton' );

  var oArrow = null;
  var aImgs  = oProfileContainer.getElementsByTagName( '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 finalState = '';
  if (optForcedState != undefined)
  {
    if (optForcedState)
    {
      finalState = 'avroadblock';
    }
    else
    {
      finalState = 'avover';
    }
  }
  else
  {
    if (oProfileContainer.className == 'avover')
    {
      finalState = 'avroadblock';
    }
    else
    {
      finalState = 'avover';
    }
  }

  if ( finalState == 'avroadblock' )
  {
    oProfileContainer.className = 'avroadblock';
    if ( oTrashBin )
    {
      oTrashBin.style.display = 'none';
    oPin.style.display = 'none';

    }
    if ( oRBButton )
    {
      oRBButton.style.display = 'block';
      oRBButton.style.visibility = 'visible';
    }
    if ( oArrow )
    {
      if ( oArrow.parentNode )
      {
        if ( oRBButton )
        {
          oArrow.parentNode.style.display = 'none'; /* We only hide the arrow if there's a View Roadblock button now showing */
        }
        else
        {
          oArrow.parentNode.style.display = 'block';
        }
      }
    }
  }
  else
  {
    oProfileContainer.className = 'avover';
    if ( oTrashBin )
    {
      oTrashBin.style.display = 'inline';
    oPin.style.display = 'inline';

    }
    if ( oRBButton )
    {
      oRBButton.style.display = 'none';
      oRBButton.style.visibility = 'hidden';
    }
    if ( oArrow )
    {
      if ( oArrow.parentNode )
      {
        oArrow.parentNode.style.display = 'block';
      }
    }
  }
}

function serverCompleteRoadblock(oButtonEl, oEvent, sUserAlertURN, fCallback)
{
  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);
          
          /* Get rid of the button, as we no longer need it */
          oLoadingTextEl = document.createTextNode('');
          oButtonEl.parentNode.replaceChild(oLoadingTextEl,oButtonEl);          
        }

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

        if(aResponseData.bRedirect && aResponseData.sRedirectURL.length > 0)
        {
          window.location.href = aResponseData.sRedirectURL;
        }
      }
    );
}
