

var Panel = new Class({
  Implements:[Options,Events],
  contaienr:null,
  panel:null,
  wrapper:null,
  closer:null,
  remote:{},
  waiter:{},
  options:{
  	"closer":"<span>close</span>",
	"closerOffset":{x:22,y:-22},
  	"debug":false,
    "id":"DMTPanel",
    "classname":""
  },
  temps:{},
  initialize:function(options){
    this.setOptions(options);
	this.log("Panel.initialize()");
  },
  setup:function(parse){
    this.container = new Element('div',{
      "id":this.options.id,
      "class":"container "+this.options.classname,
      "styles":{
        "z-index":20000,
        "position":"absolute",
        "left":(window.getSize().x*.5)-100,
        "top":(window.getSize().y*.5)-100,
        "width":200,
        "height":200,
        "overflow":"hidden",
        "display":"none"
      }
    });

    this.panel = new Element("div",{
      "class":"panel"
    });
	
	
    this.closer = new Element("div",{
      "class":"closer",
	  "id":"PanelCloser",
	  "styles":{
        "z-index":20001,
	  	"visibility":"hidden",
		"position":"absolute",
		"cursor":"pointer"
	  }
    })
	this.closer.set("html",this.options.closer);
	this.closer.addEvent("click",this.close.bind(this));
	this.closer.addEvent("mouseenter",function(){
		this.addClass("over");
	});
	this.closer.addEvent("mouseleave",function(){
		this.removeClass("over");
	});
	
	
    this.container.inject(document.body);
    this.panel.inject(this.container);
    if(this.options.closer)this.closer.inject(document.body);

    this.waiter = new Waiter(this.container);

    this.request = new Request.HTML({
      "evalScripts":true,
      "urlEncoding":false,
      "onSuccess":this.onHTMLResponse.bind(this)
    });

    window.addEvent("resize",function(){
      $clear(this.resizeint);
      this.resizeint = this.resize.delay(500,this);
    }.bind(this));

    this.panelstyle = new Element('style',{
  		'media': 'screen',
  		'type': 'text/css'
  	}).inject(document.head);
	
	this.validators = new Array();
	if(parse)this.parseDOM();
	
	this.log("Panel.setup()");
  },
  get:function(url,post,options){
  	
	// define custom temporary (instance only) options for the coming display
	this.temps = (options != undefined) ? options : {};
	
    this.fireEvent("beforeGetHTML"); //this event is for limited but important purposes
    this.removeEvents("ready"); //remove panel specific events

    if($chk(this.panel))this.panel.destroy();
    this.container.setStyle("display","block");
    this.waiter.show();
	
	if (post == null) {
		post="publication_ID="+publication_ID+"&issue_ID="+issue_ID;
	}else{
		post+="&publication_ID="+publication_ID+"&issue_ID="+issue_ID;
	}
	
	// looks for querystr ing and overwrites the post argument if exists
    if(url.indexOf("?") > 0){
      var string = url.split("?");

      //create the query string
      var i = 1;
	  
      for(i;string[i];i++) post += (string[i] == null ? "":"&"+string[i]);
	  
      url = string[0];
    }
	
    this.request.post("/flashservices/json.php/DMTPanel.getHTML",JSON.encode({"url":url,"post":post}));
    this.fireEvent("getHTML");

    if(this.temps.resizable){
      this.resizer = new Element("div",{
        "class":"resizer",
        "styles" : {
          "width" : 10,
          "height" : 10,
          "position" : "absolute",
          "bottom" : 0,
          "right" : 0,
          "padding" : 0,
          "cursor": "se-resize"
        }
      }).inject(this.container);

      this.container.makeResizable({
          handle : this.resizer,
          onComplete : this.manualResizeComplete.bind(this),
          onDrag : this.manualResize.bind(this)
      });
    }

    this.active = true;
	
	this.log("Panel.get()");
  },
  setHTML:function(html,options){
  	
	// define custom temporary (instance only) options for the coming display
	this.temps = (options != undefined) ? options : {};
	
	this.fireEvent("beforeGetHTML"); //this event is for limited but important purposes
    this.removeEvents("ready"); //remove panel specific events

    if($chk(this.panel))this.panel.destroy();
    this.container.setStyle("display","block");
    this.waiter.show();
    this.fireEvent("getHTML");

    this.active = true;
  	this.onHTMLResponse(null,null,html,null);
	this.log("Panel.setHTML()");
  },
  onHTMLResponse:function(responseTree, responseElements, responseHTML, responseJavaScript){
  	Panel.cancelClose();
    this.panelHTML = responseHTML;
    this.fireEvent("response");
	
    this.panel = new Element("div",{
      "class":"panel",
      "styles":{
        "opacity":0,
        "float":"left"
      }
    }).inject(this.container,"top");
    
    this.wrapper = new Element("div",{
        "class":"wrapper"
      }).inject(this.panel,"top");
    
    this.wrapper.set("html",this.panelHTML);

    this.wrapper.getElements("a[target=panel]").each(function(el){
      el.addEvent("click",function(tag){
        this.get(tag.href);
        return false;
      }.bind(this,el));
    }.bind(this));

    this.wrapper.getElements("a[action],button[action]").each(function(el){
      el.addEvent("click",function(tag){
        this[tag.get('action')]();
        return false;
      }.bind(this,el));
    }.bind(this));

    this.panel.getElements("form").each(function(el){
		var validator = new Form.Validator(el, {
			serial:false,
		    onElementValidate : function(valid,field,error){
			}.bind(this),
			onFormValidate : function(valid,form,event){
				if(event)event.stop();
				if(valid){
					var post = form.toQueryString();
					this.get(form.getProperty('action'),post);
				}else{
					alert("Validation Failed: Please check for required fields");
				}
			}.bind(this)
		});
		
		this.validators.push(validator);

    }.bind(this));

    this.fireEvent("htmlinjected",this.panel);
    this.removeEvent("resize",this.ready);
    this.addEvent("resize",this.ready);
	
	if(this.options.closer)this.closer.setStyles({
		"visibility": "visible",
		"display": "none"
	});
	
    this.resize();
	this.log("Panel.onHTMLResponse()");
  },
  ready:function(){
    this.fireEvent("ready",this.panel);
    this.removeEvent("resize",this.ready);
	this.log("Panel.ready()");
  },
  close:function(){
    if(this.resizer)this.resizer.destroy();
	if(this.options.closer)this.closer.setStyle("visibility","hidden");
    this.fireEvent("beforeClose");
    this.panel.set('morph',{
      "onComplete":function(){
        this.panel.destroy();
        this.container.set("morph",{
          "onComplete":function(){
            this.active = false;
            this.fireEvent("closed");
            this.container.setStyle("display","none");
          }.bind(this)
        });
        this.container.morph({
          "width":200,
          "height":200,
          "left":(window.getSize().x*.5)-100,
          "top":(window.getSize().y*.5)-100
        });
      }.bind(this)
    });

    this.panel.morph({"opacity":0});
	this.log("Panel.close()");
  },
  closein:function(seconds){
    this.delay = this.close.delay(seconds*1000,this);
  },
  cancelClose:function(){
  	clearInterval(this.delay);
  },
  manualResizeStart:function(){
    this.fireEvent("manualResizeStart");
    this.container.setStyle("overflow","hidden");
  },
  manualResizeComplete:function(){
    this.container.setStyle("overflow","auto");
    this.fireEvent("manualResizeComplete",this.container.getCoordinates());
    this.resize();
  },
  
  manualResize:function(){
    this.fireEvent("manualResize",this.container.getCoordinates());

//    var width = this.container.getScrollSize().x;
//    var height = this.container.getSize().y;
//    this.container.setStyles({
//      "left":(window.getSize().x*.5)-(width*.5),
//      "top":(window.getSize().y*.5)-(height*.5)
//    });

  },
  resize:function(){
  	
    this.container.setStyle("padding-right",0);
	var overflow = (this.panel.getSize().y < window.getSize().y-((this.container.getStyle("border-width").toInt()*2)));
    var width = overflow ? this.panel.getScrollSize().x : this.panel.getScrollSize().x;
    var height = overflow ? this.panel.getSize().y : window.getSize().y-(Math.abs(this.options.closerOffset.y*2)+(this.container.getStyle("border-width").toInt()*2));
	
	if(this.options.closer)this.closer.setStyle("display","none");
	
    this.container.set("morph",{
      onComplete:function(){
        this.waiter.hide();
        this.container.setStyle("overflow","auto");
        
        if(this.container.getScrollSize().y > this.container.getSize().y){
			var pad = Math.abs(this.panel.getSize().x - this.container.getSize().x)+this.container.getStyle("border-right-width").toInt()
			var width = pad + this.container.getStyle("width").toInt();
			this.container.setStyle("padding-right",pad);
			
			this.container.set("morph",{onComplete: function(){
				this.setCloser();
			}.bind(this)});
			this.container.morph({
		      "width":width,
		      "left":(window.getSize().x*.5)-(width*.5)
		    });
        }
			
		this.setCloser();
		
        this.panel.set("morph",{
          onComplete:function(){
            this.fireEvent("resize");
          }.bind(this)
        });
        this.panel.morph({"opacity":1});
      }.bind(this)
    });

    this.container.setStyle("overflow","hidden");
    this.container.morph({
      "width":width,
      "height":height,
      "left":(window.getSize().x*.5)-(width*.5),
      "top":(window.getSize().y*.5)-(height*.5)
    });
  },
  setCloser:function(){
  	if ((this.options.closer&&this.temps.closer!=false)|| this.temps.closer==true) {
		this.closer.setStyle("display","block");
				
		this.closer.setStyles({
			"top": this.container.getCoordinates().top + this.options.closerOffset.y,
			"left": this.container.getCoordinates().right - this.closer.getSize().x + this.options.closerOffset.x
		});
	}
  },
  parseDOM:function(){
  	$(document.body).getElements("a[target=panel]").each(function(el){
		el.addEvent("click",function(tag){
        this.get(tag.href);
        return false;
      }.bind(this,el));
	}.bind(this));	
  },
  log:function(log){
  	if(this.options.debug){
		console.log(log);
	}
  }

});

var Waiter = new Class({
  Implements:[Options,Events],
  el:{},
  number:0,
  id:"",
  target:{},
  initialize:function(target,content){
    this.target = $(target);
    this.number = $$(".waiter").length;

    this.el = new Element("div",{
      "id":this.id = "waiter_"+this.number,
      "class":"waiter",
      "styles":{
        "position":"absolute",
        "z-index":90000+this.number,
        "display":"none"
      }
    }).inject(document.body);

    this.setContent(content);
  },
  show:function(){
    var bounds = this.target.getCoordinates();
    this.el.setStyle("display","block");
    this.el.setStyles({
      "left":bounds.left+(bounds.width*.5)-(this.el.getSize().x*.5),
      "top":bounds.top+(bounds.height*.5)-(this.el.getSize().y*.5)
    });
  },
  hide:function(){
    this.el.setStyle("display","none");
  },
  setContent:function(content){
    this.el.set("html",this.content);
  }
});