/*
 * Layer Class
 */

var pubLayer = Class.create();
pubLayer.prototype = Object.extend(new Layer, {
	initialize: function(node, trigger, idstring, options, optionskey) {
		
		this.debug				= false;
		this.idstring 			= idstring;
		this.layerIdstring 		= "layer-content-" + idstring;
		this.node 				= node;
		this.replacer 			= "replacer-" + idstring;
		this.videoContent 		= false;
		this.options			= options;
		
		if (this.debug) this.debugOut("initializing pubLayer (" +this.idstring+")");
		
		//check if node exists or inline node is already defined , if not create layer
		if(!node && !$( (options.idprefix || 'lightbox-layer-')+idstring))
		{
			var elm = "<div id='"+ (options.idprefix || 'lightbox-layer-')+idstring+ "' class='"+(options.cssClass || 'lightbox-layer')+"'><div class='close'><a href='javascript:void(0);'>";
			elm += "<span class='access'>Close Layer</span></a></div>";
			elm += "<div class='layer-content'><div id='layer-content-"+idstring+"'></div></div></div>";
			new Insertion.Before($('footer-position-placeholder'), elm);
			node = $( (options.idprefix || 'lightbox-layer-')+idstring);
		}
		else if($( (options.idprefix || 'lightbox-layer-')+idstring))
		{
			node = $( (options.idprefix || 'lightbox-layer-')+idstring);
		}
		
		//variables for loading content
		if(typeof(this.options.src) != "undefined") {
			this.isContentLoading 	= false;
			this.isContentReady		= false;
		}
		
		//add iframe if needed
		if(typeof(this.options.iframe) != "undefined" && this.options.iframe == true) {
			this.iframehref 		= trigger.href;
			this.iframeidstring 	= "iframe-" + idstring;
			this.iframeisloaded 	= false;
			this.iframeheight 		= 50;
			
			// only do so, if no iframe already exists
			if( !$(this.layerIdstring).down('iframe') ) {
				var iframe = document.createElement('iframe');
				iframe.setAttribute('id', this.iframeidstring);
				iframe.setAttribute('name', this.iframeidstring);
				if(Info.browser.isIEpre7) iframe.setAttribute('src', "javascript:void(0)");
				else iframe.setAttribute('src', "about:blank");
				iframe.setAttribute('height', this.iframeheight + 'px');
				iframe.setAttribute('width', '100%');
				iframe.setAttribute('frameBorder', '0');
				iframe.setAttribute('border', '0');
				iframe.setAttribute('marginwidth', '0');
				iframe.setAttribute('marginheight', '0');
				iframe.setAttribute('scrolling', 'no');
				
				$(this.layerIdstring).appendChild(iframe);
			}
		}
		
		this.initSuper(node, trigger);
		
		var closeButton = Helper.getCloseButton(this.node);
		closeButton.observe("click", function() { this.close();}.bindAsEventListener(this));
		
		//add curtain if needed
		if(this.options.curtain == true) {
			if(!$('lightbox-curtain')) {	
				//new Insertion.After($('content-zone'), "<div id='lightbox-curtain' class='lightbox-curtain'>&nbsp;</div>");
				$('footer-position-placeholder').insert("<div id='lightbox-curtain' class='lightbox-curtain'>&nbsp;</div>", {position:'before' });
				Event.observe(window, "resize", function() {this.resizeCurtain();}.bindAsEventListener(this));
			}
			this.curtain = $('lightbox-curtain');
			
			//add iframelining
			if (Info.browser.isIEpre7) {
				this.iframeLining = new IframeLining(this.curtain);
			}
		}
		
		//header Animation listener
		if (typeof(this.options.position) != "undefined" && this.options.position != 'toolbar') {
			this.listener = {'augmentDone' :this.handleOpen.bind(this), 'event': null};
		}
		
		// new trigger mechanic: get all identical rel-links and add "trigger" observer
		$$('a[rel="publayer-'+idstring+'-'+optionskey+'"]').each( function(trigger, index) {
			// first trigger must initialize layer
			if(index > 0) {
				trigger.observe('click', function(e) { Event.stop(e);navigateToLayer(idstring,trigger.href); }.bindAsEventListener(this));
				trigger.rel = "pubtrigger-"+trigger.rel
			}
		});
		
		//callback
		if(typeof(this.options.callbacks) != 'undefined' && typeof(this.options.callbacks.initialize) == 'function') {
			this.options.callbacks.initialize.apply(this);
		}
		
		if(this.debug) this.debugOut("done initializing pubLayer (" +idstring+")");
	},
	show: function(e) {
		if(this.debug) this.debugOut("pubLayer.show("+ this.idstring +", "+ e +")");
		
		if(this.options.position == 'toolbar') {
			this.node.addClassName("active-layer");
	        this.trigger.up().addClassName("active");
	        this.trigger.addClassName("clicked"); // avoids hover effect (only for the first time)
	        this.trigger.observe("mouseout",
	            function(e) {
	                var elm = Event.findElement(e, "a");
	                elm.removeClassName("clicked");
	                elm.stopObserving("mouseout");
	            }
	        );
		} else if(typeof(this.options.callbacks) != 'undefined' && typeof(this.options.callbacks.show) == 'function') {
			this.options.callbacks.show.call(this, e);
		} else {
			this.node.setStyle({'display':'block'});
		}
	},
	hide: function() {
		if(this.debug) this.debugOut("pubLayer.hide("+ this.idstring +")");
		
		if(this.options.position == 'toolbar') {
			this.node.removeClassName("active-layer");
	        this.trigger.up().removeClassName("active");
		} else {
			this.node.setStyle({'display':'none'});
		}
		
		if(typeof(this.options.callbacks) != 'undefined' && typeof(this.options.callbacks.hide) == 'function') {
			this.options.callbacks.hide.apply(this);
		}
	},
	open: function(e) {
		if(this.debug) this.debugOut(this.layerIdstring);
		if(this.debug) this.debugOut("pubLayer.open("+ this.idstring +")");
		
		if(this.options.position == "default") {
			if (HeaderAnimation.diminishable && !HeaderAnimation.augmented) {
				Layer.closeCurrent();
				this.listener.event = e;
				HeaderAnimation.listenerQueue.add(this.listener);
				HeaderAnimation.augment();
			} else {
				Layer.prototype.open.call(this, e);
			}
		} else {
			Layer.prototype.open.call(this, e);
		}
		
		if(typeof(this.options.callbacks.open) == 'function') {
			this.options.callbacks.open.apply(this);
		}
	},
	beforeOpen: function() {
		if(this.debug) this.debugOut("pubLayer.beforeOpen("+ this.idstring +")");
		
		if(typeof(this.options.callbacks) != 'undefined' && typeof(this.options.callbacks.beforeOpen) == 'function') {
			if(this.options.callbacks.beforeOpen.apply(this) === false) return false;
		}
		
		if(this.options.curtain) {
			//	calculate/set curtain size 
			this.resizeCurtain();
	
			//position the curtain
			if(this.curtain) this.curtain.setStyle({'top':'0px'});
		}
		
		if(this.options.position == 'default') {
			//set the dimensions of layer
			this.node.setStyle({'display':'block'});
			if (!this.nodeTop)
				this.nodeTop = parseInt(this.node.getStyle('top'));
			if (!this.nodeLeft)
				this.nodeLeft = parseInt(this.node.getStyle('left'));
			if (!this.nodeHeight)
				this.nodeHeight = this.node.getDimensions().height;
			this.node.setStyle({'display' :'none'});
			
			//check whether layer is higher than current page
			var wrapper = $('footer-position-wrapper');
			this.diff = parseInt(wrapper.getDimensions().height) - this.nodeTop	- this.nodeHeight;
			if (this.diff < 0) {
				//resize the content zone
				var layerOccupation = this.nodeHeight + this.nodeTop;
				
				//difference between layer height and content height
				var diff2 = $('content-zone').getDimensions().height - layerOccupation;
				$('content-zone').setStyle(	{
							'height' :$('content-zone').getDimensions().height	- diff2 + 'px'
						});
				//	after content-zone resizing, check again curtain size
				this.resizeCurtain();
			}
			this.node.setStyle({'top' :this.nodeTop + 'px'});
		} else if(this.options.position == 'toolbar') {
			HeaderAnimation.registerLayer(this);
		}
		
		if(typeof(this.options.src) != "undefined" && this.options.src != null) {
			if( this.isContentLoading == false && this.isContentReady == false ) {
				this.isContentLoading = true;
				this.loadContent(this.options.src);
			}
		}
		
		//add preloader BEFORE showing layer
		if(this.options.iframe) {
			if(!this.iframeisloaded || this.iframehref != this.iframecurrenthref)
				new Insertion.Before($(this.iframeidstring),"<div id='lightbox-preloader'>&nbsp;</div>");
		}
		
		if (this.iframeLining)
			this.iframeLining.show();
		
		if(this.options.curtain) {
			this.curtain.setStyle({'display':'block'});
		}
		
		return true;
	},
	afterOpen: function() {
		if(this.debug) this.debugOut("pubLayer.afterOpen("+ this.idstring +")");
		
		if(this.options.iframe) {
			if (!this.iframeisloaded) {
				this.setIFrameLocation();
				this.iframeisloaded = true;
			}
			else if(this.iframehref != this.iframecurrenthref) {
				this.setIFrameLocation();
			}
			else if(this.options.curtain){
				this.correctCurtain();
			}
		}
		else if(this.options.curtain){
			this.correctCurtain();
		}
		
		if(this.options.position == 'toolbar') {
			 HeaderAnimation.diminish();
		}
		
		if(typeof(this.options.callbacks) != 'undefined' && typeof(this.options.callbacks.afterOpen) == 'function') {
			this.options.callbacks.afterOpen.apply(this);
		}
	},
	handleOpen: function() {
		if(this.debug) this.debugOut("pubLayer.handleOpen("+ this.idstring +")");
		
		HeaderAnimation.listenerQueue.remove(this.listener);
		Layer.prototype.open.call(this);
	},
	setOffset:function(offset) {
        this.node.style.top = offset + "px";
    },
	beforeClose: function(newLayer) {
    	if(this.debug) this.debugOut("pubLayer.beforeClose("+ this.layerIdstring +")");
		if(typeof(this.options.callbacks) != 'undefined' && typeof(this.options.callbacks.beforeClose) == 'function') {
			if (this.options.callbacks.beforeClose.apply(this) === false) { return false; };
		}
		
		if(this.options.position == "toolbar") {
			 HeaderAnimation.unregisterLayer();
		}
		
		if(this.options.curtain){
			this.curtain.setStyle({'display':'none'});
		}
		if (this.iframeLining)
			this.iframeLining.hide();
		if (this.diff < 0) {
			if (Info.browser.isIE) {
				$('content-zone').setStyle({'height':'1%'});
			} else {
				$('content-zone').setStyle({'height':'auto'});
			}
		}
		return true;
	},
	afterClose: function() {
		if(this.debug) this.debugOut("pubLayer.afterClose("+ this.idstring +")");
		
		if(this.options.iframe) {
			if(this.options.forcereload === true) {
				if(Info.browser.isIEpre7) $(this.iframeidstring).src = 'about:blank'; // IE6 video stop hack; usually: javascript:void(0)
				else $(this.iframeidstring).src = 'about:blank';
				this.iframeisloaded = false;
				this.iframeheight = 50;
			}
			Event.stopObserving($(this.iframeidstring), 'load');
		}
		
		if(this.options.position == 'toolbar') {
			if (!Layer.toggle) {
	            HeaderAnimation.augment();
	        }
		}
		
		if(typeof(this.options.callbacks) != 'undefined' && typeof(this.options.callbacks.afterClose) == 'function') {
			this.options.callbacks.afterClose.apply(this);
		}
		if (this.debug) this.debugOut(this.layerIdstring);
	},
	/*
	 * Special Implementations
	 */
	resizeCurtain : function() {	
		if(this.curtain) {
			var wrapper = $('footer-position-wrapper').getDimensions();
			var header 	= $('header-zone').getDimensions();
			var toolbar = $('toolbar-zone');

			this.contentHeight 	= parseInt(wrapper.height) - parseInt(header.height) - parseInt(toolbar.getDimensions().height);
			this.contentWidth 	= wrapper.width;
			//982px is toolbar min-width (926px) plus its margins (34px left + 22px right)
			if(this.contentWidth < 982) {
				this.contentWidth = 982;
			}
			this.curtain.setStyle({'height': parseInt(wrapper.height) +'px','width': this.contentWidth+'px'});
			if(this.iframeLining) {
				this.iframeLining.refresh();
			}
		}
	},
	correctCurtain : function() {
		if (this.curtain) {
			
			var wrapper = $('footer-position-wrapper').getDimensions();
			var header 	= $('header-zone').getDimensions();
			var toolbar = $('toolbar-zone');
			var footer 	= $('footer-zone');
			
			//	complete height of layer (close Button + iframe content)
			var iframeLayerHeight = $(Layer.current.layerIdstring).up().up().getDimensions().height;
			// total height for curtain/shadow 
			var wrapperHeight = parseInt(wrapper.height);						
			//	layer top position + layer height
			var iframeHeightTotal = parseInt(iframeLayerHeight) + parseInt(this.nodeTop);
			
			if (wrapperHeight < iframeHeightTotal) {
				
				var contentHeightNew = iframeHeightTotal - header.height - toolbar.getDimensions().height; 
				this.diff = -1;
				//	resize content-zone height to total iframe/layer height + position top
				$('content-zone').setStyle({'height':contentHeightNew + 'px'});
				
				this.contentHeight = contentHeightNew;
				this.contentWidth = parseInt(wrapper.width);
				this.curtain.setStyle( {
					'height' :parseInt($('footer-position-wrapper').getDimensions().height) + 'px',
					'width' : this.contentWidth + 'px'
				});									
				if (this.iframeLining) {
					this.iframeLining.refresh();
				}
			}
			else {
				// no correction, but scroll to content (if lightbox is opened in footer etc)
				$('footer-position-wrapper').scrollTo();
			}
		}
	},
	setIFrameLocation : function() {
		if(this.debug) this.debugOut("pubLayer.setIFrameLocation");
		Event.observe($(this.iframeidstring), 'load', 
				function(e) { this.rechunkIFrame(e);}.bindAsEventListener(this));
		$(this.iframeidstring).style.visibility = 'hidden';
		$(this.iframeidstring).src = this.iframehref;
		this.iframecurrenthref = this.iframehref;
	},
	rechunkIFrame : function(loadevt) {
		if(this.debug) this.debugOut("pubLayer.rechunkIFrame");
		//	afterClose: sets iframe src=about:blank (IE video hack)
		//	==> fires this function
		//	==> layer/iframe already closed -> skip this function
		if(!Layer.current) return;
		var crossevt = (window.event) ? event : loadevt;
		var iframeroot = (crossevt.currentTarget) ? crossevt.currentTarget	: crossevt.srcElement;
		if (iframeroot) {
			if (iframeroot.contentWindow) {
				var iframedoc = iframeroot.contentWindow.document;
			} else if (iframeroot.contentDocument) {
				var iframedoc = iframeroot.contentDocument.document;
			}
			iframedoc.body.style.backgroundImage = "url('')";
			if(this.options.position == 'toolbar') {
				iframedoc.body.style.backgroundColor = '#e7e8eb';
			} else {
				iframedoc.body.style.backgroundColor = '#fff';
			}

			iframedoc.getElementsByTagName('html')[0].className += ' iframe';
					
			//callback
			if(typeof(this.options.callbacks) != undefined && typeof(this.options.callbacks.rechunkIframe) == "function") {
				this.options.callbacks.rechunkIframe.call(this, iframedoc);
			}
			
			//set iframe height AFTER callback
			if (iframedoc.getElementById('content-zone')) {
				var h = iframedoc.getElementById('content-zone').offsetHeight + 0;
				this.iframeheight = h;
			}
			iframeroot.height = this.iframeheight;
			
			this.iframeisloaded = true;
			if ($('lightbox-preloader')) {
				$('lightbox-preloader').remove();
			}
			
			//correct curtain and show layer AFTER callback function
			if(this.options.curtain) {
				this.correctCurtain();
			}
			
			//callback
			if(typeof(this.options.callbacks) != undefined && typeof(this.options.callbacks.afterRechunk) == "function") {
				this.options.callbacks.afterRechunk.call(this, iframedoc, iframeroot);
			}

			$(this.iframeidstring).style.visibility = 'visible';
		}
	},
	loadContent: function(url) {
		if(this.debug) this.debugOut("pubLayer.loadContent("+ this.idstring +")");
		if( this.isContentReady == false ) {
			new Ajax.Request(url,  { 
					method:'get', 
					onComplete: this.showContent.bind(this), 
					onFailure: function(oXHR) { alert("Error: " + oXHR.status); }	
			});
		}
	},
	showContent: function (xhr) {
		if(this.debug) this.debugOut("pubLayer.showContent("+ this.idstring +")");
		
		this.isContentReady = true;
		this.isContentLoading = false;
		
		if(typeof(this.options.callbacks) != 'undefined' && typeof(this.options.callbacks.showContent) == 'function') {
			this.options.callbacks.showContent.apply(this, new Array(xhr) );
		} else {
			$("layer-content-"+this.idstring).update(xhr.responseText);
		}
	},
	debugOut: function(msg) {
		if(typeof(console) != 'undefined') {
			console.log(msg);
		} else {
			alert(msg);
		}
	}
});




/*
 * Layer Initialization
 */
var PUBLAYER_REL_REGEX = /^publayer-([^-]+)-?(.+)?$/;
var ADDITIONAL_TRIGGER_LINKS_REL_REGEX = /^trigger-(.+)$/;

function init_contentLayers() {
	//overwrite VI's init_contentLayers function with empty function so the layers won't get added twice!
}

function init_pubLayers( scope ) {
	scope = scope || $$('#content-zone a','#footer-zone a','#logo a','#toolbar-zone a');
	if ($("content-zone")) {
		$A( scope )
				.each(
						function(trigger) {
							trigger = $(trigger);
							if (PUBLAYER_REL_REGEX.test(trigger.rel)) {
								var id = trigger.rel.replace(PUBLAYER_REL_REGEX, "$1");
								var options = trigger.rel.replace(PUBLAYER_REL_REGEX, "$2");
								if(!options) options = 'external'; //set default options if none are passed via rel
								if(!layerOptions[options]) alert("LayerOptions for " + options + " are missing!");
								GLOBAL_LAYER_CONTROLLER[id] = new pubLayer(null, trigger, id, layerOptions[options], options);
							} else if (ADDITIONAL_TRIGGER_LINKS_REL_REGEX.test(trigger.rel)) {
								var manualTriggerId = trigger.rel.replace(ADDITIONAL_TRIGGER_LINKS_REL_REGEX,"$1");
								Event.observe(trigger, 'click', function(e) {
									navigateToLayer(manualTriggerId, trigger.href);
									Event.stop(e);
								}.bind(this));
							}
						}.bind(this));
	}
	//Share-Layer
	if($('tools-share') || $('footer-tools-share')) {
		GLOBAL_LAYER_CONTROLLER['share'] = new pubLayer(null,($('tools-share') || $('footer-tools-share')),'share',layerOptions['share']);
	}
}

// init
document.observe('dom:loaded', function() {
	init_pubLayers();
});
