/**
 * Ajax Newsletter overlay for zeitgeist
 */

var NewsletterOverlay = Class.create({

	appname: 	'NewsletterOverlay',     
	init: 		false,       
	url_form: 	"?type=800",
	url_handle: "?type=810",  

	initialize: function()
	{                   
		                      
		this.init 		= true; 
		                                                                     
	    this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
	    this.showForm 		= this.showForm.bindAsEventListener(this); 
		                     
		this.addContainers();      
		this.bindObservers();       
	},
	
	bindObservers: function()
	{    
		
		// download links                                                             
		/*
		$('download').observe('click', (function() { this.showForm(); }).bind(this));
		$('download').observe('click', (function() { this.showForm(); }).bind(this));
		*/
		//$('download').observe('click', function() { alert("moin");});    
		/*
		$$('#projectdetails .download').invoke('observe', 'click', function(e) { 
			this.showForm();
			Event.stop(e);
		}.bind(this));
		*/
		/*
		if($$('.download').length > 0) { 
			$$('.download').each(function(a) {   
				a.observe('click', function(e) {
					alert("click");
					this.showForm();
					Event.stop(e);
				}); //.bind(this)
			}); //.bind(this)
		} 
		*/
		                
	},        
	
	addContainers: function()
	{                               
		if(! $('overlay')) {         
        	var objBody = $$('body')[0];
			objBody.appendChild(Builder.node('div',{id:'overlay'})); 
        	objBody.appendChild(Builder.node('div',{id:'overlaycontent'}));   

			$('overlay').hide().observe('click', (function() { this.hideForm(); }).bind(this)); 
		}                                                                             
		/*
		$('overlaycontent').hide().observe('click', (function(event) { if (event.element().id == 'overlaycontent') {this.hideForm();} }).bind(this));   
		*/
	},
       
	
	showForm: function( )
	{                
		if(slideshow) {            
			slideshow.disableKeyboardNav(); 
		}
		this.enableKeyboardNav();                                                                                    
                                                    
		this.showLoading();                     
		
		var arrayPageSize = this.getPageSize();
        $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); 
        var ap = new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.8});                                          
		    
		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden'; });
        var parameters = { form:'subscribe' };          
		var aj = new Ajax.Updater('overlaycontent', this.url_form, { 
			method: 'post',
			parameters: parameters,
			onComplete: function()
			{
				this.showOverlay( true ); 
			}.bind(this) 
		});
	},
	
	showRequestForm: function()
	{            
		if(slideshow) {                    
			slideshow.disableKeyboardNav(); 
		}
		this.enableKeyboardNav();      
		                                                       
		this.showLoading();   
		                                                                                      
		//$('overlaycontent').hide();
		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden'; });
        var parameters = { form:'request' };        
		var aj = new Ajax.Updater('overlaycontent', this.url_form, { 
			method: 'post',
			parameters: parameters,
			onComplete: function()
			{                                  
				this.showOverlay( false );         
			}.bind(this) 
		});      
	},  
	
	hideForm: function() 
	{	       
		if(slideshow) {
			slideshow.enableKeyboardNav(); 
		}
		this.disableKeyboardNav();
        
		$('overlaycontent').hide();
        var fd = new Effect.Fade('overlay', { duration: 0.8 });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible'; });
    },
	   
	showOverlay: function( appear )
	{                                                                                                                       
		this.hideLoading();                                                          
        
		// show black background
		if( appear ) {                 
			$$('#overlaycontent .box-text')[0].setStyle( { width:'434px' } );
		} else {    
			$$('#overlaycontent .box-text')[0].setStyle( { width:'920px' } );  
		}   

		// show content
		var arrayPageScroll = document.viewport.getScrollOffsets();
        var overlayTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var overlayLeft = arrayPageScroll[0];
        $('overlaycontent').setStyle({ top: overlayTop + 'px' }); 
		var ap2 = new Effect.Appear('overlaycontent', { duration: 0.2, delay: 0.6}); 
		      
   		$('submit').observe('click', ( 
			function(event) { 
				this.submitSubscribe();    
				}).bind(this)
		);
		
		this.insertDefaults();
	}, 
    
	submitSubscribe: function()
	{                 
		var valid = new Validation('subscribeform', { onSubmit:false, onElementValidate:function(success, element)
			{      
				// add a custom validation method to add a css class to the parent paragraph                     
				if(element.type && element.type == 'checkbox') {                  
					if(success) {                                
						element.up().removeClassName('validation-failed');        
					}else {                                             
						element.up().addClassName('validation-failed');    
					}
				}                                    
			} });
		var defaultValues = [];
		$$('div#imprint form p label').each(function(a) { 
			defaultValues.push( a.innerHTML ); 
		});  
		Validation.add('validate-defaults', 'eintragen', {                   
    		notOneOf : defaultValues
		});
    	var result = valid.validate();   
        
        if( ! result ) {
			return;
		}
		                                  
	    $('message').update( "" );  
	       

		var parameters = {                 
			Vorname : $('firstname').value,
			Nachname : $('lastname').value,
			eMail : $('email').value,
			formtype : 'eMail',         
			customerID : 'MTI0Mw%3D%3D',  
			forceCharset: 'utf-8'
		};                                      
		parameters['Liste[1]'] = 'NjIwMA%3D%3D';          
		parameters['extdbfields[0][value]'] = 'Website'; 
		parameters['extdbfields[0][ID]'] = '100011293';  
		if($('subscribe').checked) {
			parameters['action'] = 'subscribe';
		}else if($('unsubscribe').checked) {
			parameters['action'] = 'unsubscribe'; 
		}                             
		
		var aj = new Ajax.Request(this.url_handle, { 
			method: 'post',   
			parameters: parameters,                        
			onSuccess: this.handleForm.bind(this)
			/*
			onFailure: function()
			{
				console.log('onFailure');         
			}.bind(this),
			onComplete: function()
			{
				console.log('onComplete');         
			}.bind(this), 
			onException: function(e,a)
			{                               
				console.log(e);
				console.log(a);
				console.log('onException');         
			}.bind(this)  
			*/   
			
		}) ; 
	},
	
	handleForm: function( transport )
	{                                                 
		var response = transport.responseJSON;     
		$('message').update( response.message );   			
		if( response.close == 1 ) {
			this.hideForm();   
		}                       
	},     
	
	showLoading: function()
	{                                                                                   
		//var ap = new Effect.Appear('overlaycontent', { duration: 0.2, delay: 0.6});   
		if( $('overlaycontent') ) {                                                       
			$('overlaycontent').update('<img src="fileadmin/templates/images/ajax-loader.gif" class="loading" />');  
			$('overlaycontent').show();
		}
	},
	
	hideLoading: function()
	{
		//$('overlaycontent').hide();                                                                                                        
	},   
	
	insertDefaults: function()
	{
		                                                  
		$$('div#imprint form p label').each(function(a) {
			if(a.next().tagName != 'select' && a.className != 'visible') { 
				
				if(a.next().id == 'resume') {  
					if(a.next().innerHTML == '') {
						a.next().innerHTML = a.innerHTML;  
					}
				} else {     
					if(a.next().value == '') {
						a.next().value = a.innerHTML;  
					}                                            
				}  
				   
				a.next().onfocus = function() {
					if(this.id == 'comment') {         
						if(this.innerHTML == a.innerHTML) {
							this.innerHTML = ''; 
						}
					} else {                       
						if(this.value == a.innerHTML) {
							this.value = ''; 
						}                    
					}
					
				};
				
				a.next().onblur = function() {           
					if(this.id == 'comment') {   
						if(this.getValue() == '') {
							this.innerHTML = a.innerHTML;  
						}                       
					} else {     
						if(this.value == '') {
							this.value = a.innerHTML;  
						}                                            
					}  
				};
				
			}   
		});
	},
	
	//
    //  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;
		}

		return [pageWidth,pageHeight];
	}, 
	
	//
    //  enableKeyboardNav()
    //
    enableKeyboardNav: function() 
	{
        document.observe('keydown', this.keyboardAction); 
    },

    //
    //  disableKeyboardNav()
    //
    disableKeyboardNav: function() 
	{
        document.stopObserving('keydown', this.keyboardAction); 
    },

    //
    //  keyboardAction()
    //
    keyboardAction: function(event) 
	{
        var keycode = event.keyCode;

        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();
        
        if ( keycode == escapeKey ){
            this.hideForm();
        }
    },

  	// helpers
	debug: function(msg)
	{
		if(window.console) {
			window.console.log(msg);//this.appname+': '+  
		}
	}
	
});
