﻿

/**
* modal layer class
* @author acsikos@kirowski.com
* @param {String}  msg    Simple modal layer content (like alert message)
* @param {Object}  params  
*                            type:        modal window type (window - default, alert)
*                            source:	  window content source (html blok (ID), ajax (url), default: null)
*                            draggable:	  draggable window (true - default, false)
*                            revert:	  move window the original position after drag (true - default, false)
*                            scroll:	  scrollbar position when content is too long (page - default, inside) 
*                            overlay:	  overlay layer under the content window (true - default, false)
*                            title:       the window title (string, default value: "")
*                            closebtn:    
*                                    pos:    close button position ('topRight' - default, 'bottom', 'insite')
*                                    title:  set the close link title (default: 'X')
*                            design:     
*                                    rounded:	    set rounded or simple design (default false)
*                                    footer:        insert footer line after the window (default: false)
*                            opacity:     set overlay layer opacity (default value: "0.8")
*                            effect:      set window effects (
*                                            scriptaculous example:
*                                                effect:     {
*                                                    effType: 'toggle',
*                                                    effect:  'appear'
*                                                    }
*                                            )
*/
modalLayer=Class.create();
modalLayer.prototype={
	/**
	 * default entry point, object initializing
	 * 
	 * @param {Object} msg
	 * @param {Object} params
	 */
    initialize: function(msg, params){
		this.prototypeMinVersion='1.6'; 
		this.myName='overlayContentFrame',
		
		this.msg=msg;
		this.options=Object.extend({
            type: 		'alert', 
			source:	    null,
			draggable:	false,
			revert:		false,
            scroll:     'inside',
			overlay:	true,
			title:		'',
            closebtn:   {
                pos:    'top',
                title:    'X'                
            },
            design:    {
                rounded:    false,
                footer:    false
            },            
			opacity:	'0.8',
            effect:     null,
            func:    null
		},params ||{});
		if (Prototype.Version>=this.prototypeMinVersion)
		{
			/*only 1 modal window!*/
            if ($$('.'+this.myName).length==0)
			{
				var check=this.logicCheck();
                if (check.status) this.setup()
                    else alert(check.msg);
			}
		}
		else
		{
			alert('Sorry, required min. Prototype.js version is: '+this.prototypeMinVersion+' and you have: '+Prototype.Version);
		}
	},
    /**
     * check the options
     */
    logicCheck: function(){
        var check=new Object({'status': true, 'msg':''});
        if (this.options.closebtn.pos=='bottom' && !this.options.design.footer)
        {
            check.status=false;
            check.msg='Conflict!\nCheck close button position and design footer!';
        }
        return check;
    },
    
    /**
     * swicth object parameters, and run choosed type
     */
    setup: function() {
        if (navigator.appVersion.indexOf('MSIE 6')>0)
            this.browser="IE6";        
        this.build();
        switch (this.options.type)
        {
            case 'alert':
    				//this.options.overlay=false;
        			this.content.innerHTML=this.msg;
                break;                
            case 'window':
                    if (!$(this.options.source))
                        this.content.innerHTML='Sorry, the document doesn\'t have the referrer content ID: <strong>'+this.options.source+'</strong>';
                    else 
                        this.content.innerHTML=$(this.options.source).innerHTML;                    
                break;
            case 'ajaxwindow':
                    if (Element.hasClassName(this.options.source,'ajaxcontent'))
                    {   
                        var ajaxContent=this.ajaxContent({
                            url: this.options.source.href,
                            _target: this.content
                        });
                    }
                break;
        }
        if (this.options.title) this.contentFrameTitle.innerHTML=this.options.title;
        this.display();
        if (this.options.effect) 
            this.effects({'effType':this.options.effect.effType,'effect':this.options.effect.effect});
	},
	
    /**
     * build html elements
     */
    build: function(){
    		if (this.options.overlay)
            {
    			this.overlay = new Element('div',{'class':'overlay'});
    			this.overlay.setOpacity(this.options.opacity);
            }
            if (this.options.scroll=='page'){
    			this.scrollLayer = new Element('div',{'class':'scrollLayer'});
            }
    		if(this.options.effect!=null)
                dispStyle='display:none';
            else dispStyle='';
            this.contentFrame= new Element('div',{'class':this.myName,'style':dispStyle});
            if (this.options.design.rounded)
                Element.addClassName(this.contentFrame,'rounded');
            this.contentFrameHeader= new Element('div',{'class':'overlayContentHeader'});
                    if (this.options.design.rounded)
                    {
                        this.contentFrameHeaderLeft=new Element('div',{'class':'overlayTopLeftCorner'});
                        this.contentFrameHeaderRight=new Element('div',{'class':'overlayTopRightCorner'});

           		    	this.contentFrameFooterLeft= new Element('div',{'class':'overlayContentFooterLeft'});
           		    	this.contentFrameFooterRight= new Element('div',{'class':'overlayContentFooterRight'});
                    }
                        
                    this.contentFrameHeaderContent=new Element('div',{'class':'overlayHeaderContent'});
    				this.contentFrameTitle= new Element('h2',{'class':'overlayContentTitle'});
    				this.close=new Element('a',{'class':'overlayClose',href:'#'}).update(this.options.closebtn.title);
       			this.content= new Element('div',{'class':'overlayContent'});
   		    	if (this.options.design.footer)
                {
                    this.contentFrameFooter= new Element('div',{'class':'overlayContentFooter'});
             		    this.contentFrameFooterContent= new Element('div',{'class':'overlayContentFooterContent'});
                }
	},    

    /**
     * set modal layer elements dimensions
     */
	setDimensions: function(){
        var de = document.documentElement;
		this.pageWidth=self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
		this.pageHeight=self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
		
		
		
        this.windowDimensions=document.viewport.getDimensions();
		this.frameDimensions=this.contentFrame.getDimensions();
		this.leftPos=parseInt((this.windowDimensions.width-this.frameDimensions.width)/2);
		this.topPos=parseInt((this.windowDimensions.height-this.frameDimensions.height)/2);
		if (this.leftPos<0) this.leftPos=5;
		if (this.topPos<0) this.topPos=5;
        
        /**
         * set positions
         */
		
        this.overlayHeight=$$('body')[0].up().scrollHeight>this.pageHeight?$$('body')[0].up().scrollHeight:this.pageHeight;
		if (this.overlay) this.overlay.style.height=this.overlayHeight+'px';
		this.contentFrame.style.left=this.leftPos+'px';
		this.contentFrame.style.top=parseInt(this.topPos+document.viewport.getScrollOffsets().top)+'px';
        if (this.scrollLayer){
            this.content.style.height='auto';
            $$('html')[0].style.overflow='hidden'
            this.scrollLayer.style.height=this.pageHeight+'px';
        }
		
	},
	/**
	 * insert and show elements in documents
	 */
	display: function(){
		var root = $$('body')[0];

		/* build */
		if (this.options.overlay)
			{
				root.appendChild(this.overlay);
                if (this.options.scroll=='page')
                {
                    root.appendChild(this.scrollLayer);
                    this.scrollLayer.appendChild(this.contentFrame);
                }
                else
                {
    				root.appendChild(this.contentFrame);
                }
			}
		else
			{
				root.appendChild(this.contentFrame);
			}

       	// iframe insert - IE bug 
        ifram=false;
      	if (this.browser=="IE6" && document.getElementsByTagName('select').length>0)
        {             
            if (this.options.overlay)
            {
                var selects=$$('select');
                selects.each(function(element,index){
                   element.style.visibility='hidden' ;
                });
            }
            else{
                ifram = new Element('iframe',{'src':'empty.html'});
        		ifram.style.border = "0";
                ifram.style.frameborder='0';
        		ifram.style.position = "absolute";
        		ifram.style.left = '0';
        		ifram.style.top = '0';
        		ifram.style.zIndex = "-1";
              	this.contentFrame.appendChild(ifram);
            }
        }
		
		this.contentFrame.appendChild(this.contentFrameHeader);
		this.contentFrame.appendChild(this.content);
            if (this.options.closebtn.pos=='insite')
                this.content.appendChild(this.close);

            if (this.contentFrameHeaderLeft) this.contentFrameHeader.appendChild(this.contentFrameHeaderLeft);
            this.contentFrameHeader.appendChild(this.contentFrameHeaderContent);
            this.contentFrameHeaderContent.appendChild(this.contentFrameTitle);
            if (this.options.closebtn.pos=='top')
                this.contentFrameHeaderContent.appendChild(this.close);
            if (this.contentFrameHeaderRight) this.contentFrameHeader.appendChild(this.contentFrameHeaderRight);
	
        if (this.contentFrameFooter)
            {
                this.contentFrame.appendChild(this.contentFrameFooter);
                if (this.contentFrameFooterLeft) this.contentFrameFooter.appendChild(this.contentFrameFooterLeft);
                if (this.contentFrameFooterContent) this.contentFrameFooter.appendChild(this.contentFrameFooterContent);
                if (this.options.closebtn.pos=='bottom')
                    this.contentFrameFooterContent.appendChild(this.close);
                if (this.contentFrameFooterRight) this.contentFrameFooter.appendChild(this.contentFrameFooterRight);
            }
        
        /* inherits */        
        if (this.overlay)
        {
            this.overlay.contentFrame = this.contentFrame;
            if (this.scrollLayer) 
            {
                this.close.scrollLayer = this.scrollLayer;
                this.options.scrollLayer = this.scrollLayer;
            }            
        }

        this.contentFrame.options = this.options;
        this.close.overlay = this.overlay;
        this.close.contentFrame = this.contentFrame;
		
		/*  positions */
		this.setDimensions();
        if (ifram)
        {
            /*if (this.options.overlay){
                ifram.style.width = this.overlay.getDimensions().width+'px';
          		ifram.style.height = this.overlay.getDimensions().height+'px';
            }
            else*/{
                ifram.style.width = this.contentFrame.getDimensions().width+'px';
          		ifram.style.height = this.contentFrame.getDimensions().height+'px';
            }
        }
	
		if (this.options.draggable)
		{
		  Element.addClassName(this.contentFrameHeader,'moveable');
		  new Draggable(this.contentFrame,
			  {
				handle:this.contentFrameHeader,
				revert:this.options.revert,
				zindex:10000
			  });
		}
	
		/* functions */
		this.close.onclick=this.remove;
		Event.observe(window,'resize',this.setDimensions.bind(this));
        Event.observe(window, 'keypress',
            (function (evt) {
               if (evt.keyCode == Event.KEY_ESC) {
                   this.remove();
                }
               //Event.stop (evt);
            }).bindAsEventListener(this),true);
        
        
	},
    /**
     * 
     * @param {Object} obj
     */
    ajaxContent: function(obj){
      new Ajax.Request(
			obj.url, 
			{
				method: 'get',
				parameters: obj.params,                
                asynchronous: false, 
				onSuccess: function(status) 
				    {	
                        obj._target.innerHTML=status.responseText;
				    },
				onComplete: function(status) 
				    {	
                        obj._target.innerHTML=status.responseText;
				    },
				onLoading: function()
				    {
				        var ajaxLoad='<div align="center"><img src="img/ajax-loader.gif" width="31" height="31" /><br />Please wait...</div>';
                        obj._target.innerHTML=ajaxLoad;
				    }, 
				onFailure: reportError
			});
        var reportError=function(){
            //FIXME:nahh ide még kell valami....
            alert('hiba'); 
        }
    },
    /**
     * 
     * @param {Object} param
     * 
     */
    effects: function(param){
        var str="Effect."+param.effType+"(this.contentFrame,param.effect)";
        eval(str);        
    },
    /**
     * remove modal layer element from document
     */
	remove: function(){
        if (this.contentFrame) Element.remove(this.contentFrame);
        if (this.scrollLayer) Element.remove(this.scrollLayer);
        if (this.overlay) Element.remove(this.overlay);
        $$('html')[0].style.overflow='auto';
        if (this.browser=="IE6" && document.getElementsByTagName('select').length>0)
        {
            var selects=$$('select');
            selects.each(function(element,index){
               element.style.visibility='visibility' ;
            });
        }
        return false;
	}
}


/**
 *  Collect the special (modal layers) links (parts of the modal.js)
 *    
 */
function modalLinksCollect(){
	var modals=$$('.activateModal');
	modals.each(function(element, index){
		element.onclick=function() {
            var elementClass=this.className.split(" ");
            var effectParam=new Array();
            var paramEffect=null;
            var paramScroll='page';
            var paramObj=new Object();
            for (n=0;n<elementClass.length;n++)
            {
                 if (elementClass[n].indexOf('effect_')>-1)
                 {
                     effectParam=elementClass[n].split('_');
                     paramEffect={'effType':effectParam[1],'effect':effectParam[2]};
                     paramObj.effect=paramEffect;
                 }
                 if (elementClass[n].indexOf('scroll')>-1)
                 {
                     paramScroll=elementClass[n].split('_');
                     paramObj.scroll=paramScroll[1];
                 }
                 if (elementClass[n].indexOf('design')>-1)
                 {
                     paramObj.design=new Object();
                     paramDesign=elementClass[n].split('_');
                     if (paramDesign.indexOf('rounded')>-1)
                         paramObj.design.rounded=true;
                     if (paramDesign.indexOf('footer')>-1)
                         paramObj.design.footer=true;
                 }
                 if (elementClass[n].indexOf('draggable')>-1)
                 {
                     paramObj.draggable=true;
                 }
            }
            if (this.rel)
            {
                paramObj.source=this.rel;
            }
            if (this.title.length>0)
                 paramObj.title=this.title;
            
			if (Element.hasClassName(this, 'ajaxcontent')) {
                paramObj.type = 'ajaxwindow';
                paramObj.source = this;
            }
            else {
                paramObj.type = 'window';
            }
            
            var newLayer = new modalLayer('Próba',paramObj);
            Event.stopObserving(this,'click');
            return false;
		}
	});
    
    var alerts=$$('.alert');
	alerts.each(function(element, index){
		element.onclick=function() {
			var newLayer = new modalLayer('Alert message');
            return false;
		}
	});
}
