/* 
 * @author Denis N. Ragozin <ragozin@artsofte.ru>
 * @version SVN: $Id$
 * @revision SVN: $Revision$
 */
(function($, undefined){
  $.widget("ui.dialog_layer", {
    options: {
      url: false
    },
    _create: function(){
      var self = this;
      self.wrapper = self.element.wrap("<div class=\"ui-dialog-layer faq_layer layer-shadow\" style=\"display:none;\" />").parent();
      self.element.show();
      self.wrapper.append("<div class=\"shadow-r\"></div><div class=\"shadow-b\"></div><div class=\"shadow-c\"></div>")
      self.close_button = $("<div class=\"close-img\"><a href=\"#\" title=\"Закрыть\"></a></div>");
      self.wrapper.append(self.close_button);
      self.close_button.click(function(e){
        e.preventDefault();
        self.hide();
      })
    },
    _fixPosition: function(rel){
      var offset = $(rel).offset();
      this.wrapper.css('top', (offset.top + $(rel).outerHeight(true) + 5) + 'px');

     if(offset.left + this.wrapper.width() > $('body').width()) 
       this.wrapper.css('left', $('body').width() - this.wrapper.width() - 45 + 'px');  
     else
       this.wrapper.css('left', offset.left + 'px');
     

    },
    _show: function(rel){
      if (rel !== undefined)
        this._fixPosition(rel);
      $(".ui-dialog-layer").hide();
      this.wrapper.show();
    },
    show: function(rel){
      var self = this;
      if (this.options.url){
        $.get(this.options.url, function(r){
          self.element.html(r);
          self._show(rel);
          self._initForm();
        });
      } else this._show(rel);     
    },
    hide: function(){
      this.wrapper.hide();
    },
    toggle: function(rel){
      if (!this.wrapper.is(":visible"))
        this.show(rel);
      else
        this.hide();
    },
    _initForm: function(){
      this.form = this.element.find("form");
      var self = this;
      this.form.submit(function(e){
        e.preventDefault();
        $.ajax({
           url: self.form.attr("action"),
           type: self.form.attr("method").toLowerCase(),
           data: self.form.serialize(),
           success: function(r){
             self.element.html(r);
             self._initForm();
           }
         });        
      });
    }
  });
})(jQuery)

$(function(){
  $(document).click(function(e){                 
     var target = $(e.target);    
     if (!target.hasClass("ui-dialog-layer") && !target.parents(".ui-datepicker-div").length == 0 && target.parents(".ui-dialog-layer").length == 0)
      $(".ui-dialog-layer").hide();
   });  
})
