$(document).ready(function() {
  $('#dialog').dialog({
    autoOpen: false,
    show: 'blind',
    hide: 'explode',
    modal: true,
    width: 800,
    height: 500
  });
  $('a.ExchangeItemLink').click(loadItemInfo)
  $('a.DefaultLink').click(loadItemInfo);
});

function loadItemInfo() {
  var itemId = $(this).attr('href');
  $.getJSON('/base/structureUtils/GetStructure/' + itemId + '.aspx', function(data) {
    $('#dialog #title').html(data.Title);
    $('#dialog #description').html(data.Description);
    $('#dialog #bigPhoto').attr('src', data.Photos[0].Value);
    $('#dialog #thumbs img').remove();
    var thumbsContainer = $('#dialog #thumbs');
    for(var i=0; i<data.Photos.length; i++){
    $('<img />', {
      src: data.Photos[i].Key,
      alt: data.Photos[i].Value,
      click: changePhoto
    }).appendTo(thumbsContainer);
    }
    $('#dialog').dialog('open');
  });
  return false;
}
  
function changePhoto(){
   $('#dialog #bigPhoto').attr('src', $(this).attr('alt'));
}

function changePopupTarget(itemIdString){
  var liContainer = $('ul.exchangeItems li.' + itemIdString);
  if(liContainer.length > 0){
    $('#modalTemplate #popupImage').attr('src', liContainer .find('img').attr('src'));
    $('#modalTemplate #productName').html(liContainer .find('#productName').html());
    $('#modalTemplate #productDescription').html(liContainer .find('#description').html());
    var itemId = parseInt(itemIdString);
    $('#modalTemplate .LeftArrowLink').click(function(){changePopupTarget(itemId - 1);});
    $('#modalTemplate .RightArrowLink').click(function(){changePopupTarget(itemId +1);});
  }
}

