﻿function ViewItemPopup()
{
  if (this.active == true)
  {
    $('#ItemRow > td > .ViewItem').slideUp("fast", function () { $('#ItemRow').remove(); });
    this.active = null;
    return;
  }
  
  if ($('#ItemRow').length > 0)
  {
    $('#ItemRow > td > .ViewItem').slideUp("fast", ViewItemPopup_getdata.bind(this));
    return;
  }
  
  this.ViewItemPopup_getdata();
}

function ViewItemPopup_getdata()
{
  var guid = this.getAttribute('href').substr(this.getAttribute('href').indexOf('ViewItem/')+9);

  // Get the popup data.
  getPopup('GetItemView', '{"itemId": "' + guid + '"}', ViewItemPopup_callback.bind(this));
}

function ViewItemPopup_callback(res)
{
  if (res.error != null)
  {
    alert(res.error.Message);
    return;
  } 
  else {
    // Remove the item
    $('#ItemRow').remove();
    
    // Set all items to be inactive
    $(this).parent().parent().parent().find('a').each(function () {
        this.active = null;
      });
    
    // Set this link as active
    this.active = true;
      
    // Add the item.
    $(this).parent().parent().after("<tr id=\"ItemRow\"><td colspan=\"4\">" + res.value + "</td></tr>");
    
    if ($(this).parent().parent().hasClass('Alt'))
    {
      $('#ItemRow').addClass('Alt');
    }
      
    // Show the item with a sliding scrollbar to show it fully.
    $('#ItemRow > td > .ViewItem').hide().slideDown("medium", function() { 
      $.scrollTo($('#ItemRow').scrollTop()+$('#ItemRow').offset().top, 400)
    });
    
    // Update the login links for this container.
    updateLoginLinks($('#ItemRow'));
  }
}

function InitPage()
{
  $('table > tbody > tr > td > a.AutoDetails').click(function() {
      this.ViewItemPopup();
      return false;
    });
  
  $('table > tbody > tr > td > a.AutoDetails').each(function(i) {
      if (this.getAttribute('href') != null)
      {
        this.ViewItemPopup = ViewItemPopup;
        this.ViewItemPopup_getdata = ViewItemPopup_getdata;
        this.ViewItemPopup_callback = ViewItemPopup_callback;
      }
      
      return true;
    });
}

$(document).ready(function() {
    if (!isFacebookCall)
      InitPage();
  });