$(document).ready(function() {
  /* keeping a copy of the returned hash object, as we'll only close this modal _after_ the form submit has successfully happened */
  var lastModalHash;

  $('#imageListForm').ajaxForm({dataType: 'json', success: _imageListForm});

  function _imageListForm(res) {
    // special case for "create" button
    if (lastModalHash.w.attr('id') == 'createWindow') {
      window.location.href = res.data.url;
      return false;
    }

    if (lastModalHash) {
      lastModalHash.o.fadeOut();lastModalHash.w.hide();
      lastModalHash.w.css('top', '');
      lastModalHash.w.css('left', '');
      lastModalHash=null;
    }
    if (res.code == "denied") {
      window.location.href = res.data.authUrl + "?redirect=" + window.location.href;
    } else if (res.code == "reload") {
      $('#reloadWindow .reloadMessage').html(res.message);
      $('#reloadWindow').jqmShow();
      window.location.reload(true);
    } else if (res.code == "redirect") {
      $('#reloadWindow .reloadMessage').html(res.message);
      $('#reloadWindow').jqmShow();
      window.location.href = res.data.url;
    } else {
      $('.selectPool-message').hide();
      $('.messages').html(res.message).fadeIn(1000);
    }
  }

  /* Preloading the product selection modal */
  if ($('#selectProductModalLink').attr('href')) {
    $.ajax({
      url: $('#selectProductModalLink').attr('href'),
      success: function(data) {$('#selectProductWindow').html(data);}
    });
  }

  /*
  **************************************
  * Setting up the selectProduct modal *
  **************************************
  */
  $('#selectProductWindow').jqm({onShow: _showSelectProductWindow, onHide: _closeSelectProductWindow, resetOnClose: false});
  /*
  the callback passes an object with the following properties
    * w: (jQuery object) The dialog element
    * c: (object) The config object (dialog's parameters)
    * o: (jQuery object) The overlay
    * t: (DOM object) The triggering element
    * cl: the closing DOM element (only in case of close event)
  */
  /*
  _showSelectProductWindow handles the logic for showing up the modal dialogue.
  if the selectProductWindow div already has the content loaded (via lazy loading or because of a previous modal load)
  then we simply show the modal window
  Otherwise an ajax request is fired to fetch the modal window data. on success of the ajax request, the modal is shown
  */
  function _showSelectProductWindow(hash) {
    $('.psm-messageId').hide();
    // make another ajax call only if the modal has not been already rendered on the page yet.
    if (hash.w.find('.psm-selectProductButton').length > 0) {
      hash.w.show();
      hash.w.jqDrag('.jqDrag');
    } else {
      hash.w.show();
      $.ajax({
        url: $('#selectProductModalLink').attr('href'),
        success: function(data) {
          // once again check to see that if the previous ajax call has already succeeded and
          // a modal has been rendered, no need to render again.
          if (hash.w.find('.psm-selectProductButton').length == 0) {
            hash.w.html(data);
            hash.w.jqDrag('.jqDrag');
          }
        }
      });
    }
  }
  function _closeSelectProductWindow(hash) {
    if ($(hash.cl).hasClass('psm-selectProductButton')) {
      /* the submit link has been clicked */
      $('#productScaffoldId').val($('.psm-scaffoldId').val());
      if (hash.w.hasClass('waitFlickr')) {
        $('.psm-messageId').html("Adding photos to cart. <br/>Data is being pulled from flickr and it may take a few moments. Please wait..").show();
      } else if (hash.w.hasClass('waitPicasa')) {
        $('.psm-messageId').html("Adding photos to cart. <br/>Data is being pulled from picasa and it may take a few moments. Please wait..").show();
      } else {
        $('.psm-messageId').html("Adding photos to cart. Please wait..").show();
      }
      $('#imageListForm').attr('action',$('#submitCartLink').attr('href')).submit();
      /* the modal will be closed later when the imageForm submit response has been received */
      lastModalHash = hash;
    } else {
      /* just close the modal */
      hash.o.fadeOut();hash.w.hide();
      hash.w.css('top', '');
      hash.w.css('left', '');
    }
  }

  /*
  **************************************
  *   Setting up the selectPool modal  *
  **************************************
  */
  /*
  Default zIndex is set to 2999. the zIndex property is used for overriding this default.
  It is only useful to do so in case of modal-in-modal. In this case the second modal will
  now overlay over the existing modal
  */
  $('#selectPoolWindow').jqm({ajax: $('#selectPoolModalLink').attr('href'), zIndex: 1000, onHide: _closeSelectPoolWindow, resetOnClose: false});
  function _closeSelectPoolWindow(hash) {
    if ($(hash.cl).hasClass('selectPool-selectButton') || $(hash.cl).hasClass('selectPool-createSuccess')) {
      /* the user has selected a pool from the given list, proceed to add images to this pool */
      $('#poolId').val($('.selectPool-poolId').val());
      $('.selectPool-message').html("Adding photos to pool. Please wait..").show();
      $('#imageListForm').attr('action',$('#submitPoolLink').attr('href')).submit();
      lastModalHash = hash;
    } else if($(hash.cl).hasClass('userHandle-success')) {
      /*
      the user just selected a user handle i.e.
      he/she was using sharing for the first time and were redirected to the user handle modal

      now we can close this modal and make a request to open it again (this will open the pool modal now)
      */
      hash.o.fadeOut();hash.w.hide();
      hash.w.css('top', '');
      hash.w.css('left', '');
      $('#selectPoolWindow').jqmShow();
    } else {
      /* just close the modal */
      hash.o.fadeOut();hash.w.hide();
      hash.w.css('top', '');
      hash.w.css('left', '');
    }
  }

  /*
  **************************************
  *   Setting up the selectAlbum modal *
  **************************************
  */
  /*
  similar to the selectPool modal above. z-index will come into play here as well
  */
  $('#selectAlbumWindow').jqm({ajax: $('#selectAlbumModalLink').attr('href'), zIndex: 1000, onHide: _closeSelectAlbumWindow, resetOnClose: false});
  function _closeSelectAlbumWindow(hash) {
    if ($(hash.cl).hasClass('selectAlbum-selectButton')) {
      /* the user has selected an album from the given list, proceed to move images to this album */
      $('#albumId').val($('.selectAlbum-albumId').val());
      $('.selectAlbum-message').html("Moving photos to album. Please wait..");
      $('#imageListForm').attr('action',$('#submitAlbumLink').attr('href')).submit();
      lastModalHash = hash;
    } else {
      /* just close the modal */
      hash.o.fadeOut();hash.w.hide();
      hash.w.css('top', '');
      hash.w.css('left', '');
    }
  }

  /*
  **********************************************
  *   Setting up the delete confiramtion modal *
  **********************************************
  */
  $('#deleteConfirmWindow').jqm({onHide: _closeDeleteConfirmWindow, resetOnClose: false});
  function _closeDeleteConfirmWindow(hash) {
    if ($(hash.cl).hasClass('deleteYes')) {
      /* the user has confirmed delete */
      $('.deleteConfirm-message').show();
      $('#imageListForm').attr('action',$('#submitDeleteLink').attr('href')).submit();
      lastModalHash = hash;
    } else {
      /* just close the modal */
      hash.o.fadeOut();hash.w.hide();
      hash.w.css('top', '');
      hash.w.css('left', '');
    }
  }

  $('#createWindow').jqm({onShow: _proceedToCreate});
  function _proceedToCreate(hash) {
    hash.w.show();
    hash.w.jqDrag('.jqDrag');
    lastModalHash = hash;
    $('#imageListForm').attr('action',$('#submitCreateLink').attr('href')).submit();
  }

  /*
  the reload alert window
   */
  $('#reloadWindow').jqm();
});

