$(document).ready(function(){
  $('[class*=open-dialog]').click(openDialog);
  $('[class*=open-static-dialog]').click(openStaticDialog);
});

var myDialog = $('<div class="dialog-simple clearfix"><div class="loader-large"></div></div>');

function openDialog(){
  myDialog.dialog({
    'closeText': 'Aizvērt',
    'maxWidth': 828,
    'maxHeight': 828,
    'modal': true,
    'resizable': false,
    'draggable': false,
    'width': 'auto',
    'close': function(){
      // setTimeout used to prevent weird behaviour in IE
      setTimeout(
        function(){
          myDialog.remove();
          myDialog = $('<div class="dialog-simple clearfix"><div class="loader-large"></div></div>');
        },
        100
      )
    }
  });

  return loadDialogContent($(this));
}

function openStaticDialog(){
  $('#dialog-' + $(this).attr('id')).dialog({
    'closeText': 'Aizvērt',
    'maxWidth': 828,
    'maxHeight': 828,
    'modal': true,
    'resizable': false,
    'draggable': false,
    'width': 'auto'
  });

  return false;
}

function loadDialogContent(link){
  var properties = link.attr('id').split('-');
  var type = properties[0];

  $('.dialog-link-prev').remove();
  $('.dialog-link-next').remove();

  switch(type){
    case 'gallery':
      var previous_content = myDialog.html();

      myDialog.load(link.attr('href'), function(new_content){
        myDialog.html(previous_content);

        var temp_wrapper = document.createElement('div');
        $(temp_wrapper).css('position', 'absolute');
        $(temp_wrapper).css('top', '0');
        $(temp_wrapper).css('left', '0');
        $(temp_wrapper).css('visibility', 'hidden');
        $(temp_wrapper).html($(new_content));
        $('body').append($(temp_wrapper));

        $(temp_wrapper).onImagesLoad({
          selectorCallback: function(){
            myDialog.html($(temp_wrapper).html());
            $(temp_wrapper).remove();
            myDialog.dialog('option', 'position', 'center');

            $('.dialog-link-prev').click(function(){return loadDialogContent($(this))});
            $('.dialog-link-next').click(function(){return loadDialogContent($(this))});
          }
        });
      });

      break;

    case 'img':
      var img = $('<img class="dialog-content-image" src="' + link.attr('href') + '" alt="' + link.children('img').attr('alt') + '" title="' +  link.children('img').attr('title') + '" />');

      img.onImagesLoad({
          selectorCallback: function(){
          myDialog.html(img);
          myDialog.dialog('option', 'position', 'center');
        }
      });

      break;

    default:;
      myDialog.load(link.attr('href'), function(){
        myDialog.dialog('option', 'position', 'center');
      });
  }

  return false;
}
