var Popin = {
  params:{},
  alert:function(text, options){
    var options = options || {};
    options.show_loading = false;
    this.show(options);
    this.popin.down('.popin_content').update(text);
  },
  load:function(path,options){
    var options = options || {};
    options.show_loading = true;
    this.show(options);
    this.popin.down('.popin_content').update('');
    
    new Ajax.Updater(this.popin.down('.popin_content'), path, {     
      method:'get',
      evalScripts:true,
      parameters: {popin:true},
      onComplete:this.init.bind(this)
    });
  },
  init:function(options){
    Object.extend(this.options, options || {});
    this.popin.down('.popin_loading').hide();        
    this.popin.setStyle({top: (this.popin.cumulativeScrollOffset().top + 50).toString()+'px'});
    
    Event.observe(document, 'keyup', this.clickObserver.bind(this));    
    
    this.initForm();
  },
  
  initForm:function(){
    var form;
    
    if(form = this.popin.down('form')) {
      if(form.hasClassName('no_form_init')) return;
      
      // init formWatch
      this.formWatch = new FormWatch(form);
      this.options.do_not_hide = true;
      
      // create iframe for submit target
      if(!this.form_target){
        
        this.form_target = new Element('iframe', {style:'width:0; height:0', src:'javascript://', name:'popin_form_target'});
        $('popin_content').insert({'after':this.form_target});
        
        this.form_target.observe('load', (function(){          
          window.iFrameAfterLoad = null;

          var idoc= this.form_target.contentDocument || this.form_target.contentWindow.document;
          
          $('popin_content').update(idoc.body.innerHTML);

          (function(){try{iFrameAfterLoad()}catch(e){}}).defer();
        
          this.initForm();
        }).bind(this));
      }
      
      form.writeAttribute('target','popin_form_target');
      
      // setup feedback
      this.form_submit_button = form.down('input[type="submit"]');
      form.observe('submit',(function(){
        try{
          this.form_submit_button.disabled = 'disabled';
          this.form_submit_button.value = "Please wait...";
        }catch(e){}
      }).bind(this));
      
    } else {
      this.formWatch = null;
      this.options.do_not_hide = false;
      window.onbeforeunload = null;
    }
    
  },
    
  clickObserver:function(e){
    if(e.keyCode == Event.KEY_ESC) this.hide();
  },
  
  show:function(options_or_id){
    this.options = {};
    if(typeof options_or_id == "string") this.options.id = options_or_id;
    else this.options = options_or_id;

    this.popin = this.options.id ? $(this.options.id) : $('popin_'+(this.options.style || "sixeighty"));

    $$('.popup_overlay').invoke('show');
    this.popin.appear({duration:0.3});
    
    if(this.options.show_loading) this.popin.down('.popin_loading').show();
    else try{this.popin.down('.popin_loading').hide();}catch(e){}
    
  },

  load_element:function(id){
    this.show($(id).innerHTML);
  },

  overlay_clicked:function(){
    if(!this.options.do_not_hide) this.hide();
  },

  hide:function(force){
    if(!force){
      if(this.options.confirm_close && !confirm("Close Window?")) return; 
      if(this.formWatch && !this.formWatch.confirmClose()) return;
    }
    
    if(this.options.on_hide) this.options.on_hide();
    
    if(this.formWatch) this.formWatch.cancel();
    
    $$('.popup_overlay').invoke('hide');
    $$('.popin').each((function(el){Effect.Fade(el, {duration:.3})}));    
  },

  update:function(new_content){
    this.popin.down('.popin_content').update(new_content);
  },

  size_popin_contents:function(target, source){
    if( !($(target).up('.popin').identify() == 'popin_sixeighty') ){
      var height = $(source).getDimensions().height;

      $(target).setStyle({
        height: height.toString()+'px'
      });          
    }
  },
  
  resize_popin_contents:function(target, source){
    if( !($(target).up('.popin').identify() == 'popin_sixeighty') ){
      var height = $(source).getDimensions().height;

      new Effect.Morph($(target), {
        style: {
          height: height.toString()+'px'
        },
        afterFinish: (function(){ 
          $(target).setStyle({height:'auto'});         
        }).bind(this)
      })
    }
  }
}

var FormWatch = Class.create();
  FormWatch.prototype = {
     initialize : function(form, options) {
        this.submitted = false;
        this.form = $(form);
        // Let's serialize this.form and store it...
        this.formcontents = $(form).serialize();
        // Observe beforeunload event...
        this.form.observe('submit', function() {this.submitted = true; }.bind(this));
        window.onbeforeunload = this.confirmLeavePage.bind(this);        
     },
     confirmLeavePage : function(ev) {
       if(this.changed()) return "You have unsaved information.";
     },
     confirmClose:function(){
       if(this.changed()) return confirm("You have unsaved information, close anyway?");
       else return true;
     },
     changed:function(){
       return ((this.formcontents != this.form.serialize()) && !this.submitted) || !!this.block;
     },
     cancel:function(){
       window.onbeforeunload = null;
     }
  }