/**
 * dodatkowe pliki :
 * - overlay.css
 *
 */
 
// -----------------------------------------------------------------------------------
//
//  Configuration
//
OverlayOptions = Object.extend({
     'opacity'	: 0.7   // controls transparency of shadow overlay    
	,'color'	: '#000'
	,'zIndex'	: 300	
}, window.OverlayOptions || {});

// -----------------------------------------------------------------------------------

var Overlay = Class.create();

Overlay.prototype = {

    showCallback		: '', //funkcja wywoywana po wywietleniu warstwy
    closeCallback		: '', //funkcja wywoywana po ukryciu warstwy
    visibleContainer	: '', //id elementu ktory ma znajdowac sie nad warstwa
	
	containers			: [],	
    pageContainer		: {},
    //
    // initialize()
    // Constructor
    //
    initialize: function() {
		var self=this;            
		this.updateTagList();
		            
        // Code inserts html at the bottom of the page :
        //  <div id="overlay"></div>        
        
		if(!$('overlay'))
		{
			this.pageContainer= $('pageContainer') ?  $('pageContainer') : $$('body')[0];
			var el = new Element('div');
			el.id = 'overlay';				
			this.pageContainer.appendChild(el);
	    }    
		
		$('overlay').hide().observe('click', (function() { this.hide(); }).bind(this));
		
		/*$$('.overlayClose').each(function(elem, index) {
		  	elem.observe('click', function() { self.hide(); });
		});*/
		Event.observe(document, 'keydown',function(e){
			var key = (typeof e.which != "undefined") ? e.which : e.keyCode;			
			if(key==27 && $('overlay').visible())
			{
				self.hide();	
			}		
		});
		
		$('overlay').hide();
		$('overlay').setStyle({
			 'position'			: 'absolute' 
			,'top'				: '0'
			,'left'				: '0' 
			,'width'			: '100%'
			,'height'			: '100%'
			,'border'			: 'none'
			,'margin'			: '0'
			,'padding'			: '0'
			,'zIndex'			: OverlayOptions.zIndex 			
			,'backgroundColor'	: OverlayOptions.color	
			,'opacity'			: OverlayOptions.opacity	
		});
		//$('overlay').setStyle({ opacity: OverlayOptions.opacity });		
		//$('overlay').setOpacity(OverlayOptions.opacity);
    },
    
    /**
	 * Dodawanie elementu otwierajcego okno
	 * @param id kontenera
	 * @param tablica z id mapowanych elementow
	 */
    addTrigger: function(name,trigger)
    {
    	//alert(trigger);
    	var self=this;
    	if(this.containers[name])
		{
				
    			$(trigger).each(function(elem) {
					    				
    				if($(elem))
    				{
    					var oldOnclick=false;
    					if(typeof $(elem).onclick=='function')
	    				{
	    					oldOnclick = $(elem).onclick;
							$(elem).onclick=function(){return false};
	    				}							    				
    					
						$(elem).observe('click',function(event){
							
							//alert(elem);
							//alert(typeof oldOnclick);
							//alert(oldOnclick);
							
							if(typeof oldOnclick=='function')
							{
								result=oldOnclick(event);
							}
							else
							{
								result=true;
							}
							//alert(result);
							if(result!=false)
							{
								self.show(name,elem);					
								this.blur();
								event.stop();
							}
							return false;
						});
						
						$(elem).setStyle({'visibility':'visible'});
					}
				});
		}
		else
		{
			alert('Nie zdefiniowano kontenera');
		}
    },
	/**
	 * Dodawanie kontenera obslugiwanego przez Overlay
	 * @param id kontenera
	 * @param obiekt z parametrami kontenera {  }
	 */      
	addContainer: function(name,params)
	{
		var self=this;
		//alert(name);
		if($(name))
		{	
		//	alert('ok');
			this.containers[name]= params;
			
			/*if(typeof this.containers[name].onShow == 'function')
			{
				this.containers[name].onShow();
			}*/
			
			
			if($(params.trigger))
			{
				this.addTrigger(name,params.trigger);
				/*	
				$(params.trigger).each(function(elem) { 
					$(elem).observe('click',function(event){
						self.show(name);					
						this.blur();
						event.stop();
						return false;
					});
					
					$(elem).show();
				});*/
				
			}
		}
		//this.containers[name]=[];
		
		//this.containers[name]['name']=name;			
	},      
    //
    //  show()
    //  Display overlay
    //
    show: function(visibleContainer,trigger) { 
		   
    	var self=this;
    	var obj={};
		
    	self.hide();
    	
    	if($(visibleContainer))
    	{
			this.visibleContainer=visibleContainer;
			$(visibleContainer).show();
		}
    	
		if(this.visibleContainer)
		{    	
			$$('select', 'object', 'embed').each(function(node){
				
				if(!node.descendantOf(self.visibleContainer))
				{ 
					node.style.visibility = 'hidden';
				}
			});
		}
		else
		{
			$$('select', 'object', 'embed').each(function(node){
				
				node.style.visibility = 'hidden';
			});	
		}
		
	/*	this.pageContainer.setStyle({
			 overflow : 'hidden'
		
		});*/
        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('overlay').setStyle({ height: arrayPageSize[1] + 'px' });        
		$('overlay').show();				
		this.onShow(visibleContainer,trigger);

    },
    
    onShow : function(name,trigger) {
    	    			
		if(typeof this.showCallback == 'function')
		{
			this.showCallback();
		}
		
		if(typeof this.containers[name] != 'undefined')
		{
			if(typeof this.containers[name].onShow == 'function')
			{
				this.containers[name].onShow(trigger);
			}
		}
		
	},


    //
    //  hide()
    //
    hide: function() {
    	
	    if($('overlay').visible())
		{
			
			if($(this.visibleContainer))
			{
				$(this.visibleContainer).hide();	
			}
			$('overlay').hide();
		
	        $$('select', 'object', 'embed').each(function(node){ 
				node.style.visibility = 'visible';
			});
	        
	        this.onHide(this.visibleContainer);
	    }
    },
    
    onHide : function(name) {
		if(typeof this.hideCallback == 'function')
		{
			this.hideCallback();
		}
		if(typeof this.containers[name] != 'undefined')
		{
			if(typeof this.containers[name].onHide == 'function')
			{
				this.containers[name].onHide();
			}
		}
	},
	
	//
    // updateTagList()
    //
    /*updateTagList: function() {   
        this.updateTagList = Prototype.emptyFunction;

        document.observe('click', (function(event){
            //var target = event.findElement('[class^=showOverlay]') || event.findElement('[class^=showOverlay]');
            var target = event.findElement();
            //if (target) {
            if(target.hasClassName('showOverlay')) {
            	target.overlayObj=this;
                event.stop();
                this.show(target);
            }
        }).bind(this));
    },*/
    updateTagList: function() {   
        this.updateTagList = Prototype.emptyFunction;
		var self=this;
		/*$$('.addOverlay').each(function(elem) {
			elem.overlayObj=self;	
		  //alert(s);
		});*/

		
        document.observe('click', (function(event){
            //var target = event.findElement('[class^=showOverlay]') || event.findElement('[class^=showOverlay]');
            var target = event.findElement();
            //if (target) {
           /*if(target.hasClassName('showOverlay')) {
            	target.overlayObj=this;
                event.stop();
                this.show(target);
            }*/
            
            if(target.hasClassName('overlayClose')) {
            	event.stop();
                this.hide();
            }
            
        }).bind(this));
    },
	//
	// dodanie klasy overlayWindowLoaded dla kontenera (np. usuwanie animacji adowania zawartosci)
	//
	loaded: function(visibleContainer)
	{			
		if($(visibleContainer))
		{
			$(visibleContainer).addClassName('overlayWindowLoaded');
		}	
	},
	//
	// dodanie klasy overlayWindowLoaded dla kontenera (np. usuwanie animacji adowania zawartosci)
	//
	loading: function(visibleContainer)
	{			
		if($(visibleContainer))
		{
			$(visibleContainer).removeClassName('overlayWindowLoaded');
		}	
	},
	whoami: function()
	{
		return 'Overlay class';
	},
    //
    //  getPageSize()
    //
    getPageSize: function() {
	        
	     var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
				
		
		//alert(xScroll+' '+pageWidth);
		return [pageWidth,pageHeight];
	},
	
	/**
	 * Zwraca szerokosc scrola
	 * nie dziala pod ie
	 *
	 */
	getScrollerWidth : function () {
	    var scr = null;
	    var inn = null;
	    var wNoScroll = 0;
	    var wScroll = 0;
	 
	    // Outer scrolling div
	    scr = document.createElement('div');
	    scr.style.position = 'absolute';
	    scr.style.top = '-1000px';
	    scr.style.left = '-1000px';
	    scr.style.width = '100px';
	    scr.style.height = '50px';
	    // Start with no scrollbar
	    scr.style.overflow = 'hidden';
	 
	    // Inner content div
	    inn = document.createElement('div');
	    inn.style.width = '100%';
	    inn.style.height = '200px';
	    // Put the inner div in the scrolling div
	    scr.appendChild(inn);
	    // Append the scrolling div to the doc
	    document.body.appendChild(scr);
	    // Width of the inner div sans scrollbar
	    wNoScroll = inn.offsetWidth;
	    // Add the scrollbar
	    scr.style.overflow = 'auto';
	    // Width of the inner div width scrollbar
	    wScroll = inn.offsetWidth;
	    // Remove the scrolling div from the doc
	    document.body.removeChild(
	    document.body.lastChild);
		// Pixel width of the scroller
	    return (wNoScroll - wScroll);
	}	
}

var EproObjects={};

/**
 * 
 *
 *
 */
//Event.observe(window, 'load', function () {
document.observe("dom:loaded", function() {
	
	var overlay=new Overlay();
	
	EproObjects.overlay=overlay;
	
	/*Event.observe(window, 'resize', function () {
		overlay.hide();	
	});*/
	
	/**
	 * Zainicjowanie okna wyszukiwarki zaawansowanej
	 *
	 *
	 */
	overlay.addContainer('advancedSearchContainer',{
						
		 'trigger'	: ['advancedSearchTrigger']
		,'onShow'	: function(trigger) {
			// zapobiega ponownemu wykonaniu funkcji onShow 
			this.onShow=null;
			// zawartosci okna wyszukiwania zaawansowanego 
			new Ajax.Updater($('advancedSearchContainer').down('dd'), '/index/load/?module=offer&file=search_advanced', {
				method : 'get',
				evalScripts : true,
				parameters: {},
				onComplete: function() {
					// usunicie animacji adowania ( definicja w overlay.css )	
					overlay.loaded('advancedSearchContainer');
				}
			})
		}
		,'onHide'	: function() { }
	});	
	/**
	 * Zainicjowanie okna rejestracji w sklepie
	 * 
	 * 
	 */				
	overlay.addContainer('registerContainer',{
		 'trigger'	: ['registerTrigger','partnerRegisterTrigger']
		,'onShow'	: function(trigger) {
			// zapobiega ponownemu wykonaniu funkcji onShow 
			//this.onShow=null;
			//alert(trigger);
			overlay.loading('registerContainer');
			$('registerContainer').down('dd').update('');
			var url='/index/load/?module=account&file=register/actions&action=display';
			if(trigger=='partnerRegisterTrigger' || trigger=='logInContainerPartnerRegisterTrigger') url=url+'&partner=1';
			// zaadowanie zawartosci okna z przypominaniem hasla
			new Ajax.Updater($('registerContainer').down('dd'), url,
			{
				method : 'get',
				evalScripts : true,
				parameters: {},
				onComplete: function(){
					// usunicie animacji adowania ( definicja w overlay.css )
					overlay.loaded('registerContainer');
				}
			});
		}
		,'onHide'	: function() {}
	});
	
	/**
	 * Zainicjowanie okna logowania
	 *
	 *
	 */	
	overlay.addContainer('logInContainer',{			
		 'trigger'	: ['logInTrigger','partnerLogInTrigger','partnerLogInTriggerTopCMS','partnerLogInTriggerTopCMSSub','partnerLogInTriggerSitemap','checkoutLogInTrigger','wishlistLogInTrigger']
		,'onShow'	: function(trigger) {
			
			
			// jezeli wywolane przez ten sam trigger co ostatnio to nie wykonujemy dalszego kodu
			if(this.lastTrigger==trigger)
			{
				$('layout').scrollTo();
				if($('logInContainer').visible())	
				{
					$('accountLogInEmail').focus();	
				}
				if(trigger=='wishlistLogInTrigger') 
				{
					wishlistLoginShowInfo();
				}
				return;
			}
			else
			{
				this.lastTrigger=trigger;
				$('logInContainer').down('dd').update('');
				overlay.loading('logInContainer');
				
				
							
				
				//this.onShow=null;
				var url='/index/load/?module=account&file=logIn/actions&action=display';
				// modyfikacha url`a w zaleznosci od miejsca wywolania
				switch(trigger)
				{
					case 'partnerLogInTrigger':
					case 'partnerLogInTriggerTopCMS':
                                        case 'partnerLogInTriggerTopCMSSub':
                                        case 'partnerLogInTriggerSitemap':
						url=url+'&mode=partner';
						height=445; 
					break;
					case 'checkoutLogInTrigger':
						url=url+'&mode=checkout';
						height=469; 
					break;
					case 'wishlistLogInTrigger':
						url=url+'&mode=wishlist';
						height=358; 												
					break;
					default:
						height=358;
					break;
				}			
				$('logInContainer').setStyle({'height':height+'px','marginTop':'-'+(height/2)+'px'});	
				$('logInContainer').down('dd').setStyle({'height':(height-30)+'px'});
	 			
	 			$('layout').scrollTo();
	 		}
			 	
			// zaadowanie zawartosci okna logowania
			new Ajax.Updater($('logInContainer').down('dd'), url, {				
				method : 'get',
				evalScripts : true,
				parameters: {},
				onComplete: function(){
					// usunicie animacji adowania ( definicja styli w overlay.css )	
					overlay.loaded('logInContainer');
					// podpicie wyswietlania okna rejestracji
					overlay.addTrigger('registerContainer',['logInContainerRegisterTrigger','logInContainerPartnerRegisterTrigger']);
					/**
					 * Zainicjowanie okna z obsug przypomnania hasa
					 * inicjujemy dopiero po zaladowaniu okna logowania
					 * dopiero tam wystpuje element inicjujcy wywietlenie okna
					 */				
					overlay.addContainer('remindPasswordContainer',{
						 'trigger'	: ['remindPasswordTrigger']
						,'onShow'	: function(trigger) {
							// zapobiega ponownemu wykonaniu funkcji onShow 
							this.onShow=null;
							// zaadowanie zawartosci okna z przypominaniem hasla
							new Ajax.Updater($('remindPasswordContainer').down('dd'), '/index/load/?module=account&file=remindPassword/actions&action=display',								{
								method : 'get',
								evalScripts : true,
								parameters: {},
								onComplete: function(){
									// usunicie animacji adowania ( definicja w overlay.css )
									overlay.loaded('remindPasswordContainer');
								}
							})
						}
						,'onHide'	: function() {}
					});									
				}
			})
		}
		,'onHide'	: function() {}
	});
	
	
	

	
	
		 
	//alert(overlay.getScrollerWidth());			 
});
 