/** 
 * @class Dialog
 * This class creates custome dialog
 * 
 * @param {Object} item
 * @param {Object} config
 *   top:  
 *   left:
 *   width: 
 *   height:
 *   center: boolean. This positions dialog to center when it's true
 *   cls: string. The class name for the container for main body item
 *   containerCls: string. The class name for the container of this dialog
 *   modal: boolean. Dialog creates the dark background when thsi is true
 *   killOnHide: bool. The dialog gets removed from body when the dialog calls hide() method if this is set to true
 *   header: Object.  This creates header for dialog
 *   -  cls: string. The class name for the header item
 *   -  text: string. The text to insert to the header
 *   -  btns: Object.  This addes buttons for header
 *      -  cls: string. The class name for buttuon container
 *      -  items: Array.  This is the array of button configurations
 *         -  cls: string. The class name for the button
 *         -  label. string. The label for the button
 *         -  events. Array. The array of events for the button
 *            -  type. string. The type of event  
 *            -  func. Function. The function to run when the even is fired
 *   footer: Object.  This creates footer for dialog
 *   -  cls: string. The class name for the footer item
 *   -  text: string. The text to insert to the footer
 *   -  btns: Object.  This addes buttons for footer
 *      -  cls: string. The class name for buttuon container
 *      -  items: Array.  This is the array of button configurations
 *         -  cls: string. The class name for the button
 *         -  label. string. The label for the button
 *         -  events. Array. The array of events for the button
 *            -  type. string. The type of event  
 *            -  func. Function. The function to run when the even is fired
 */
  
  meltmedia.Dialog = Class.create({
    initialize: function(item,config) { 
      this.item = this.getItem(item);
      this.config = config;
      this.parentEl;
      this.bgImg;
      this.container;
      this.zIndex = (typeof config.zIndex!="undefined")? config.zIndex : 10;
       // this is for IE6 fixed item bug
      window.manualFixItems = (typeof window.manualFixItems!="undefined")? window.manualFixItems : []; 
      this.manualFixItems = window.manualFixItems;
      
    },
    
    init: function(){
      this.renderItem();
      this.initEvents();
    },
    
    getItem: function(item){ 
      if(typeof item == "string"){
        return $(item);
      }else{
        return item;
      }
    },
    
    initEvents: function(){
      var cfg = this.config;
      if(typeof cfg.onHide!="undefined")this.container.observe("dialog:hide", cfg.onHide);
    },
    
    /** render background for modal */
    renderBg: function(){ 
      var isFF = (Prototype.Browser.Gecko)
      this.bgImg = new Element('div',{'class':'modal-background'}); 
      this.bgImg.setStyle({
        opacity: isFF? 1: 0.5,
        width: isFF? "100%" : screen.width+"px",
        height: screen.height+"px",
        position: (this.isIe6())?"absolute":"fixed",
        top: 0,
        right: 0
      });
      
      if(isFF)this.bgImg.addClassName("ffSwfFix");
            
      if(this.isIe6()){
        this.manualFixItems.push(this.bgImg);
        this.fixPosition();
      }
      
      document.body.appendChild(this.bgImg); 
    },
    
    /** render the main contents */
    renderItem: function(){ 
      var cfg = this.config;
      
      /*rendering the background shadow image for modal */
      if(cfg.modal)this.renderBg();
      
      
      /** creating container */
      this.container = new Element('div',{'class':'dialog-element'+((cfg.containerCls)?" "+cfg.containerCls:"")});
      
      this.parentEl = (typeof cfg.targetElementId!="undefined")? $(cfg.targetElementId) : document.body;
      this.parentEl.appendChild(this.container);
      /** render header*/
      if(typeof cfg.header!="undefined")this.renderExtraItem("header");
      
      /** render body */
      var bodyContainer = new Element('div',{'class':'dialog-element-body'+((cfg.cls)?" "+cfg.cls:"")});
      bodyContainer.appendChild(this.item);
      this.container.appendChild(bodyContainer);
      
      /** render footer */
      if(typeof cfg.footer!="undefined")this.renderExtraItem("footer");
      
      /** setting size, position and zIndex of dialog */
      this.setSize(); 
      this.setPosition();
      this.setZIndex(this.zIndex);
     
      
      /** create the close btn based on the class */
      if(cfg.closeBtnCls) this.setCloseBtn(cfg.closeBtnCls);
      
      /* hide or show */
       if(this.config.visible==false) this.hide();
    },
    
    setCloseBtn: function(clsName){ 
      $$("."+clsName).each(function(el){
        el.observe("click",this.hide.bindAsEventListener(this));
      }.bind(this));
    },
    
    /** rendering header or footer */
    renderExtraItem: function(extraItemName){
      
      var cfg = this.config[extraItemName];
      var item = new Element('div',{'class':'dialog-element-'+extraItemName+((cfg.cls)?" "+cfg.cls:"")}).update((cfg.text)?cfg.text:"");
      
      if(cfg.btns){
        
        var btnCfg = cfg.btns;
        var btnsContainer = new Element("div",{"class":"dialog-element-btn-container"+((btnCfg.cls)?" "+btnCfg.cls:"")});
        
        btnCfg.items.each(function(bCfg){
          
          var btn = new Element('input',{"type":"Button","value":((bCfg.label)?""+bCfg.label:""),"class":"dialog-element-btn"+((bCfg.cls)?" "+bCfg.cls:"")});
     
          bCfg.events.each(function(ev){
            btn.observe(ev.type,ev.func);
          });
          
          btnsContainer.appendChild(btn);
          
        });
        
        item.appendChild(btnsContainer);
      }
      this.container.appendChild(item);
    },
    
    setSize: function(){
      var cfg = this.config; 
      var width = parseInt(cfg.width);
      var height = parseInt(cfg.height);
      this.container.setStyle({
        width: (width>0)?width+"px": "auto",
        height: (height>0)?height+"px": "auto"
      }); 
    },
    
    setZIndex: function(z){
      this.container.setStyle({zIndex: z + 1}); 
      if(typeof this.bgImg!="undefined")this.bgImg.setStyle({zIndex: z});
    },
    
    bringToTop: function(){
      var zIndex = parseInt(this.container.style.zIndex);
      $$(".dialog-element").each(function(item){
        var tgZIndex = parseInt(item.style.zIndex);
        if(zIndex<tgZIndex)zIndex = tgZIndex+2;
      });
      
      this.setZIndex(zIndex);
    },
    
    setPosition: function(){
      var cfg = this.config; 
      var pTop = 0;
      var pLeft = 0;
      if(cfg.center){
        var scrollPosition = this.getScrollPosition();
        
        /** getting width and height of avirable area in different browsers */
        var cWidth,cHeight;
        if(window.innerHeight) {
          cWidth = window.innerWidth;
          cHeight = window.innerHeight;
        } else if( document.documentElement && document.documentElement.clientHeight ) {
          cWidth = document.documentElement.clientWidth;
          cHeight = document.documentElement.clientHeight;
        } else if( document.body ) {
          cWidth = document.body.clientWidth;
          cHeight = document.body.clientHeight;
        };
       
        pTop = (cHeight > this.container.getHeight())?scrollPosition[1]+(cHeight - this.container.getHeight())/2 : scrollPosition[1];
        pLeft = (cWidth > this.container.getWidth())?scrollPosition[0]+(cWidth - this.container.getWidth())/2 : scrollPosition[0];
        
      }else{
        
        if(typeof cfg.top!="undefined")pTop=parseInt(cfg.top);
        if(typeof cfg.left!="undefined")pLeft=parseInt(cfg.left);
        
      };
     
      this.container.setStyle({
        top: pTop+"px",
        left: pLeft+"px",
        position: (cfg.fixedPosition)? "fixed":"absolute"
      });
       /** setting bg image position to the current scrolling position */
      if(this.isIe6() && cfg.modal){
        this.bgImg.setStyle({
          top: scrollPosition[1]-200,
          left: scrollPosition[0],
          height: screen.height+400+"px"
        });
      }
     
    },
    
    /** this is used to replace the css positon:fixed for ie6  */
    fixPosition: function(){
      
      var _this = this;
      var scrollPos = _this.getScrollPosition();
      var prevPosX = scrollPos[0];
      var prevPosY = scrollPos[1];
      var test = window.onscroll;
      
      window.onscroll = function(){
        
        scrollPos = _this.getScrollPosition();
        
        _this.manualFixItems.each(function(item){
          
          if (item.style.display != 'none') { 
            var curTop = parseInt(item.style.top);
            var curLeft = parseInt(item.style.left);
            item.style.left = curLeft + scrollPos[0] - prevPosX + "px";
            item.style.top = curTop + scrollPos[1] - prevPosY + "px";
          }
          
        });
        
        prevPosX = scrollPos[0];
        prevPosY = scrollPos[1];
      };
    },
    
    getScrollPosition: function(){
        var scrollX, scrollY;
        if(window.pageYoffset ) {
          scrollX = window.pageXoffset;
          scrollY = window.pageYoffset;
        } else if( document.documentElement && document.documentElement.scrollTop ) {
          scrollX = document.documentElement.scrollLeft;
          scrollY = document.documentElement.scrollTop;
        } else if( document.body ) {
          scrollX = document.body.scrollLeft;
          scrollY = document.body.scrollTop;
        };
        return [scrollX,scrollY];
    },
    
    hide: function(){ 
      if(typeof this.bgImg!="undefined")this.bgImg.style.display = 'none';
      this.container.style.display = 'none';
      this.setZIndex(this.zIndex);
      this.container.fire("dialog:hide");
      if(this.config.killOnHide)this.destroy();
    },
    
    show: function(){
      this.setPosition();
      if(typeof this.bgImg!="undefined")this.bgImg.style.display = 'block';
      this.container.style.display = 'block';
      
      if (this.config.bringToTop || typeof this.config.bringToTop=="undefined") {
        this.bringToTop(); 
      } else {
        this.setZIndex(this.zIndex);
      }
    },
    
    destroy: function(){
      this.parentEl.removeChild(this.container);
      if(this.config.modal)document.body.removeChild(this.bgImg);
    },
    
    isIe6: function(){
      return document.getElementById && document.all&&(navigator.appVersion.indexOf("MSIE 6.")>=0);
    }
   
  })