/**
 * Dialog plugin 1.0
 *
 * Copyright (c) 2008 Blit, Inc (http://blit.com/)
 * MIT license (blit.com/licenses/mit.html)
 */
 
jQuery.fn.openDialog = function(url) {
  if (url) {
    $(this).load(url,null,function(){$(this).openDialog()});
    return this;
  }
  
 $this = jQuery(this[0]);
  
  var $background = jQuery('#dialog_background');
  if ($background.length<1) {
    $background = jQuery('<div id="dialog_background" style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 10000; opacity: 0.25; background-color: black; filter:alpha(opacity=25);"/>');
    jQuery('body').append($background);
  }
  $background.closeDialog();
  $background.show();
  
  position($this.wrap('<div style="position: absolute; z-index: 10001;"></div>'));
  $background.data('dialog',$this.show());
  
  jQuery(window).bind('resize.dialog',$this,function(event){position(event.data);});
  jQuery(window).bind('scroll.dialog',$this,function(event){position(event.data);});
  
  return $this;
  
  // Helper functions
  function position($dialog) {
    jQuery('#dialog_background').css('top',jQuery(window).scrollTop().toString() + 'px');
    jQuery('#dialog_background').css('left',jQuery(window).scrollLeft().toString() + 'px');
    $wrapper = $dialog.parent();
    var height = $dialog.outerHeight();
    var width =  $dialog.outerWidth();
    var top = ((jQuery(window).height() - height)/2) + (jQuery(window).scrollTop());
    var left = ((jQuery(window).width() - width)/2) + (jQuery(window).scrollLeft());
    $wrapper.width = height;
    $wrapper.height = width;
    $wrapper.css('top',top.toString() + 'px');
    $wrapper.css('left',left.toString() + 'px');
  }
}

jQuery.fn.closeDialog = function() {
  var $background = jQuery('#dialog_background').hide();
  var $dialog = $background.data('dialog');
  if ($dialog) {
    $dialog.hide().parent().remove();
    $background.removeData('dialog');
    jQuery(window).unbind('resize.dialog');
    jQuery(window).unbind('scroll.dialog');
  }
  return this;
}

var Dialog = {
  open: function(url) {
    var dialog = $('<div class="dialog" style="display:none"></div>');
    $('body').append(dialog);
    dialog.openDialog(url);
    return false;
  },
  close: function() {
    $(window).closeDialog();
    return false;
  },
  ar_error: function(errors) {
    html = '';
    jQuery.each(errors,function(){
      html += '<li>' + this[0] + ' ' + this[1] + '</li>';
    });
    var $container = $('div.dialog:visible ul.errors');
    if ($container.length>0) $container.html(html).show();
    else $('div.dialog:visible div.content:first').prepend('<ul class="errors">' + html + '</ul>');
  }
};

