window.addEvent( "domready", function() { new SSMain(); } );
window.addEvent( "load", function() { new SSMainLoad(); } );

var SSMain = new Class
({
	initialize: function()
	{
		new SSNL();
	}
});


var SSMainLoad = new Class
({
	initialize: function()
	{
		if(  navigator.appVersion.indexOf( "Chrome" ) > -1  ) {
			new FancyImage();
		}else{
			new FancyImage();
		}
	}
});

var FancyImage = new Class
({
	initialize: function()
	{
		$$("img.fancy").each( function( img ) 
		{
			var propShell = new Element( "div" ).setStyles( {"background":"#000","height":img.getStyle("height") , "width":img.getStyle("width")} );
			var shell = new Element( "div" );
			propShell.wraps( img.getParent("a") );
			shell.wraps( propShell );
			img.set( "tween", {duration:300} );
			img.addEvent( "mouseover", this.hoverListener.bind( this ) );
			img.addEvent( "mouseout", this.leaveListener.bind( this ) );
			shell.setStyles( {"padding-bottom":img.getStyle("padding-bottom"), "border-bottom":img.getStyle("border-bottom")} );
			img.setStyles( {padding:0, margin:0, border:"none"});
			
			if( img.hasClass( "pb" ) ) { 
				shell.setStyle("margin-bottom", "3px" );
			}
			
		}.bind( this ));
	},
	hoverListener: function( e )
	{
		var img = $(e.target);
		img.tween( "opacity", .65 );
	},
	leaveListener: function( e )
	{
		var img = $(e.target);
		img.tween( "opacity", 1 );
	}
});


var SSNL = new Class
({
	initialize: function()
	{
		$("nlTrigger").addEvent( "click", this.clickListener.bind( this ) );
		var i = $("nlInput").getElement( "input" );
		i.addEvent( "focus", this.formFocusHandler.bind( i ) );
		i.addEvent( "blur", this.formBlurHandler.bind( i ) );
		i.store( "defaultValue", i.get( "value" ) );
		$("nlSubmit").addEvent( "click", this.clickSubmitListener.bind(this) );
	},
	clickListener: function()
	{
		$("nlPre").setStyle("display", "none");
		$("nlTrigger").setStyle( "display", "none" );
		$("nlInput").setStyle("display", "block");
	},
	formFocusHandler: function()
	{
		if(  this.get( "value" ) == this.retrieve( 'defaultValue' ) ) {
			this.set( "value", "" );
		}
	},
	formBlurHandler: function()
	{
		if( this.get( "value" ) == "" ) {
			this.set( "value", this.retrieve( 'defaultValue' ) );
		} 
	},
	clickSubmitListener: function(e)
	{
		var i = $("nlInput").getElement( "input" );
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		var m = i.get("value");
		if( !emailPattern.test( m ) ) {
			new Event( e ).stop();
			alert("Please enter a valid email address");
			return;
		}
		
		$("nlInput").setStyle("display", "none");
		$("nlBusy").setStyle("display", "block");
		
		// TODO show loading
		//console.log( m );
		var r = new Request.JSON( {url:REMOTE_BASE + "contact/Newsletter", onComplete:this.submitCompleteListener.bind(this) } ).post( {mail:m} );
	},
	submitCompleteListener: function()
	{
		$("nlBusy").setStyle("display", "none");
		$("nlCb").setStyle("display", "block" );
		
	}
	
});