if( !Browser.Features.Touch ) {
	window.addEvent( "load", initPage );
}else{
	window.addEvent( "domready", initPage );
}



function initPage()
{
	new MA_Env();
	new MA_NL();
	document.id("footlogo").addEvent( "click", clickHome );
	if( Browser.Features.Touch ) {
		new MA_Touch();
	}
}

function clickHome()
{
	window.location.href = REMOTE_BASE;
}


function toTop()
{
	new Fx.Scroll( window,  { offset: {
        'x': 0,
        'y': 15
    }} ).toTop();
}


function d()
{
	if( window["console"] ) {
		console.log.apply( console, arguments );
	}
}


( function() {

	EmailValidator =
	{
		validate: function( str )
		{
			var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
			if( emailPattern.test( str ) ) {
				return true;
			}
			return false;
		}
	};
	
	MA_Touch = new Class
	({
		initialize: function()
		{
			this.handleTopScroll();
			this.setupFooter();
			this.handleHome();
			this.handleOrientation();

			window.addEvent( "resize", this.resizeListener.bind(this) );
			
			delete Element.NativeEvents["mouseenter"];
			delete Element.NativeEvents["mouseleave"];

			this.resize();
		},

		handleOrientation: function()
		{
			var orientationHandler = new MA_Touch_Orientation();
			orientationHandler.addEvent( "orientationchange", this.orientationListener.bind(this) );
			MA_Touch.orienter = orientationHandler;
			
		},

		handleTopScroll: function()
		{
			toTop();
			toTop.delay( 100 );
			//toTop.delay( 1000 );
			//toTop.delay( 2000 );
		},

		setupFooter: function()
		{
			//document.id("footer").inject( document.id(document.body) );
			//this.reposFooter.periodical( 300, this );
		},

		reposFooter: function()
		{
			//document.id("footer").setStyle( "top",  document.id("content").getSize().y  );
			//d( document.id("wrapper").getSize().y  );
		},

		handleHome: function()
		{
			if( !!document.id("homeCop") ) {
				document.id("homeCop").setStyle("display","none")
			}
		},

		resize: function()
		{
			this.reposFooter();
		},
		
		resizeListener: function( e )
		{
			this.resize();
		},
		orientationListener: function( orientation )
		{
			document.id( document.body ).addClass( "orient-" + orientation );
			document.id( document.body ).addClass( "mobile" );
			document.id( document.body ).addClass( navigator.platform.toLowerCase() );
			toTop();
			switch( orientation )
			{
				case "portrait" :
					MA_Portrait_Warn.show();
					break;

				default :
					MA_Portrait_Warn.hide();
					break;
			}
		}
	});

	MA_Touch.isIphone = function()
	{
		return navigator.platform.toLowerCase() == "iphone";
	};


	MA_Portrait_Warn =
	{
		sign:null,
		clicky:null,
		show: function()
		{
			if( !this.sign ) {
				this.sign = new Element("div").set( "id", "portraitwarn" );
				var clicky = new Element("div").set("id", "portraitwarnClick" );
				clicky.addEvent( "touchend", this.touchListener.bind(this) );
				this.sign.adopt(clicky);
				this.clicky = clicky;
				document.body.adopt( this.sign );
				this.sign.setStyles( {left:(window.getSize().x - this.sign.getSize().x)/2,  top:(window.getSize().y - this.sign.getSize().y)/2 - 120} );
			}
			this.sign.setStyle( "display", "block" );
		},
		hide: function()
		{
			if( this.sign ) {
				this.sign.setStyle( "display", "none" );
			}
		},
		touchListener: function()
		{
			this.hide();
		}

	};

	MA_Footer_Touch = new Class
	({
		initialize: function( correctY )
		{
			if( !correctY ) {
				correctY = 0;
			}
			this.correct( correctY );
		},
		correct: function( correctY )
		{
			document.id("footer").setStyle( "bottom", null  );
			document.id("newsletter").setStyle( "bottom", null  );
			document.id("footer").setStyle( "top", document.id( "content" ).getSize().y + correctY  );
			document.id("newsletter").setStyle( "top", document.id( "content" ).getSize().y + correctY  );
			//this.correct.delay( 500, this, [correctY] );
		}
	});
	
	MA_Touch_Orientation = new Class
	({
		Implements:[Events],
		initialize: function()
		{
			//MA_Touch_Orientation.previousOrientation = MA_Touch_Orientation.getOrientation();
			window.addEvent( "orientationchange", this.orientationListener.bind(this) );
			this.orientationListener.delay( 10, this );
		},
		
		orientationListener: function()
		{
			this.fireEvent("orientationchange", MA_Touch_Orientation.getOrientation() );
			MA_Touch_Orientation.previousOrientation = MA_Touch_Orientation.getOrientation();
		}

	});
	
	MA_Touch_Orientation.getOrientation = function()
	{
		switch( window.orientation )
		{
			case 0 :
				return "portrait";

			case 90 :
				return "landscape";

			case -90 :
				return "landscape";

		}
	};
	
	MA_Touch_Orientation.isLandscape = function()
	{
		return MA_Touch_Orientation.getOrientation() == "landscape";
	};
	MA_Touch_Orientation.previousOrientation = null;
	

	MA_NL = new Class
	({
		shell:null,
		iName:null,
		iMail:null,
		iAddress:null,
		defText:null,
		btn:null,
		canvas: null,
		form:null,


		initialize: function()
		{
			this.iName = document.id("nlInputName");
			this.iMail = document.id("nlInputEmail");
			this.iAddress = document.id("nlInputAddress");
			this.btn = document.id("nlBtnSend");
			this.form = document.id( "nlForm" );

			this.btn.addEvent( "click", this.clickListener.bind(this) );
			this.form.addEvent( "submit", this.submitListener.bind(this) );
			this.canvas = new MA_NL_Canvas();

		},
		send: function( email )
		{
			email = email != null ? email :  this.getVal("mail").trim();
			var name = this.getVal("name").trim();
			var address = this.getVal("address").trim();
			
			if( !( email.length > 0 && name.length > 0 ) ) {
				return; // TODO error hint
			}
			if( !EmailValidator.validate(email) ) {
				return;
			}

			var r = new Request( {url:REMOTE_BASE + "newsletterss", onComplete:this.completeHandler.bind(this), method:"post"} );
			r.send( "email="+email+"&name="+name+"&address="+address );

			this.hideBtn();

		},
		submitListener: function(e)
		{
			e.stop();
		},
		focListener: function()
		{
			if( this.getVal() == this.defText ) {
				this.setVal(" ");
			}
		},
		blurListener: function()
		{
			if( this.getVal() == " "  || this.getVal() == "" ) {
				this.setVal( this.defText );
			}
		},
		clickListener: function()
		{
			this.send();
		},
		completeHandler: function()
		{
			this.disableFields();
			document.id("nlBtnSendSucc").setStyle( "display", "block" );
			this.canvas.closeClickListener.delay( 2000, this.canvas, [null] );
			this.enableFields.delay( 4000, this );
		},
		getVal: function( v )
		{
			var els = {
				"mail" : this.iMail,
				"name" : this.iName,
				"address" : this.iAddress
			};
			return !!els[v] ? els[v].get("value") : null;
		},
		disableFields: function( str )
		{
			this.iAddress.set("value", "" );
			this.iMail.set("value","");
			this.iName.set("value", "" );
			this.iMail.set("disabled", "disabled");
			this.iName.set("disabled", "disabled");
			this.iAddress.set("disabled", "disabled");
			
		},
		enableFields: function()
		{
			this.iMail.set("disabled", null);
			this.iName.set("disabled", null);
			this.iAddress.set("disabled", null);
			this.iMail.set("enabled", "enabled");
			this.iName.set("enabled", "enabled");
			this.iAddress.set("enabled", "enabled");
			this.btn.setStyle( "display", "block" );
			document.id("nlBtnSendSucc").setStyle( "display", "none" );
		},
		hideBtn: function()
		{
			this.btn.setStyle( "display", "none" );
		}


	});

	MA_NL_Canvas = new Class
	({
		close:null,
		show:null,
		canvas:null,
		trigg1: null,
		trigg2: null,
		
		initialize: function()
		{
			this.canvas = document.id("newsletter");
			this.close = document.id("nlClose");
			this.show = document.id("nlTrigger");
			
			this.close.addEvent( "click", this.closeClickListener.bind(this) );
			this.show.addEvent( "click", this.showClickListener.bind(this) );
			if( !Browser.Features.Touch ) {
				this.show.addEvent( "mouseenter", this.showEnterListener.bind(this) );
				this.show.addEvent( "mouseleave", this.showLeaveListener.bind(this) );
			}
			
			this.trigg1 = document.id("nlTrigg1");
			this.trigg2 = document.id("nlTrigg2");

			this.trigg1.setStyle( "display", "none" );
			this.trigg2.setStyle( "display", "block" );

			this.trigg1.setStyle( "display", "block" );
			this.trigg2.setStyle( "display", "none" );
		},

		showClickListener: function(e)
		{
			if( Browser.Features.Touch ) {

				if( document.id("footer").getStyle( "top" ) == "auto" ) {
					this.canvas.tween("bottom", parseInt( document.id("footer").getStyle( "bottom" ) ) + 110 );
				}else{
					this.canvas.tween("top", parseInt( document.id("footer").getStyle( "top" ) ) - 90 );
				}
				
				if( !!document.id("contactInfo") &&  MA_Touch.isIphone() ) {
					document.id("contactInfo").setStyle("display", "none");
				}
			}else{
				this.canvas.setStyle("top", null );
				this.canvas.setStyle("bottom", 0);
				this.canvas.tween("bottom", 110 );
			}
			this.show.removeEvents( "click" ).addEvent( "click", this.closeClickListener.bind(this) );
		},
		showEnterListener: function(e)
		{
			this.trigg1.setStyle("display", "none");
			this.trigg2.setStyle("display", "block");
		},

		showLeaveListener: function(e)
		{
			if( parseInt( this.canvas.getStyle("bottom") ) == 0 ) {
				this.trigg1.setStyle("display", "block");
				this.trigg2.setStyle("display", "none");
			}
		},
		
		closeClickListener: function(e)
		{
			if( document.id("footer").getStyle( "top" ) == "auto" ) {
				this.canvas.tween("bottom", parseInt( document.id("footer").getStyle( "bottom" ) ) );
			}else{
				this.canvas.tween("top", parseInt( document.id("footer").getStyle( "top" ) ) );
			}
			this.trigg1.setStyle("display", "block");
			this.trigg2.setStyle("display", "none");
			this.show.removeEvents( "click" ).addEvent( "click", this.showClickListener.bind(this) );

			if( !!document.id("contactInfo") ) {
				document.id("contactInfo").setStyle("display", "block");
			}
		}

	});
	
	MA_Env = new Class
	({
		lastContPadd:0,
		
		initialize: function()
		{
			window.addEvent( "resize", this.resizeListener.bind(this) );
			this.evaluateEnvSize();
		},
		resizeListener: function()
		{
			this.evaluateEnvSize();
		},
		evaluateEnvSize: function()
		{
			this.applySizeClasses();
			this.controlContentScroll();
		},
		applySizeClasses: function()
		{
			var s = window.getSize();
			var w = s.x;
			var h = s.y;
			var fac = 3;

			if( w <= 1400 ){
				fac = 22;
			}
			if( w <= 1200 ) {
				fac = 2;
			}
			
			var e = document.id("wrapper");
			var cl = e.get("class");
			e.removeClass( "s-2" );
			e.removeClass( "s-22" );
			if( fac != null ) {
				e.addClass( "s-" + fac );
			}
			["footer","csheader", "newsletter"].each( function( it ) { if( document.id(it) ) { document.id(it).setStyle("visibility", "visible"); } } );


		},
		controlContentScroll: function()
		{
			if( document.id("wrapper").hasClass("about") ) {
				return;
			}
			if( document.id("wrapper").hasClass("news") ) {
				return;
			}
			var correction = -30;
			var cH = document.id("content").getSize().y - this.lastContPadd - correction;
			var d = window.getSize().y - document.id("footer").getSize().y;

			if( cH > d ) {
				var padd = cH-d + document.id("footer").getSize().y;
				document.id( "content" ).setStyle( "padding-bottom", (padd > 0 ? padd : 0) );
				this.lastContPadd = padd;
			}
		}
	});
	


	// ############################### PORTFOLIO ##########################################################


	MA_Portfolio = new Class
	({
		initialize: function()
		{
			new MA_Portfolio_Env();
			new MA_Portfolio_Sort();
			new MA_Portfolio_Reel();

			if( Browser.Features.Touch ) {
				document.id("content").setStyle( "padding-bottom", 0  );
				if( MA_Touch.isIphone()  ) {
					new MA_Footer_Touch( 80 );
				}else{
					if( MA_Touch_Orientation.isLandscape() ) {
						new MA_Footer_Touch( 80 );
					}else{
						new MA_Footer_Touch( 620 );
					}
					//document.id("content").addEvent("touchmove", function(e) { e.preventDefault(); } );
				}
				MA_Touch.orienter.addEvent( "orientationchange", this.orient.bind(this) );
			}

		},
		orient: function( d )
		{
			if( !MA_Touch.isIphone()  ) {
				if( d == "landscape" ) {
					new MA_Footer_Touch( 80 );
				}else{
					new MA_Footer_Touch( 620 );
				}
			}
		}
	});
	
	
	
	MA_Portfolio_Sort = new Class
	({
		btn: null,
		panel: null,
		active: false,
		waitHideInterval: null,
		origH: 0,
		origOpac: .9,


		initialize: function()
		{
			this.btn = document.id("btnSort");
			this.panel = document.id("panelSort");
			this.panel.setStyle("display", "block").setStyle.delay(1, document.id("panelSort"), ["display", "none"] );

			this.btn.addEvent("click", this.clickSortListener.bind(this) );
			this.btn.addEvent("mouseleave", this.btnLeaveListener.bind(this) );

			this.panel.set("tween", { duration:350} );

			document.id("headnav").getElements("a").each( function(el) {
				el.addEvent( "click", this.hide.bind( this ) );
			}.bind(this));
		},

		clickSortListener: function(e)
		{
			var p = document.id("panelSort");
			var btn = document.id("btnSort");
			p.setStyle( "visibility", "visible" );

			if( p.getStyle("display") == "none" ) {
				p.setStyle("display", "block" );

				if( !this.origH ) {
					this.origH = this.panel.getSize().y;
					this.panel.setStyle("height", 0 );
					this.origOpac = this.panel.get( "opacity" );
				}

			}

			p.setStyle( "left", btn.getPosition().x );
			
			this.active = !!this.active ? false : true;
			
			if( this.active ) {
				
				this.panel.setStyle("height", 0 );
				this.panel.set( "opacity", this.origOpac );
				this.btn.addClass( "active" );
				this.panel.removeEvents( "mouseleave" ).addEvent( "mouseleave", this.induceOut.bind(this) );
				this.panel.removeEvents( "mouseenter" ).addEvent( "mouseenter", this.resetWaitOut.bind(this) );
				this.show();
				
			}else{
				
				this.btn.removeClass("active");
				
			}

			//this.induceOut();

		},
		show: function()
		{
			//this.panel.tween( "opacity", 1 );
			//this.slide.slideIn();
			//this.slide.toggle();
			this.panel.tween( "height", this.origH );
			
		},
		btnLeaveListener: function( e )
		{
			if( this.active ) {
				this.induceOut();
			}
		},
		induceOut: function( e )
		{
			clearTimeout( this.waitHideInterval );
			this.waitHideInterval = this.hide.delay( 1000, this );
		},

		resetWaitOut: function( e )
		{
			clearTimeout( this.waitHideInterval );
		},

		hide: function()
		{
			this.panel.tween( "opacity" , 0 );
			this.btn.removeClass( "active" );
			this.active = false;
		}

	});


	MA_Portfolio_Env = new Class
	({
		initialize: function()
		{
			window.addEvent( "resize", this.resizeListener.bind( this ) );
			this.normalizePositions();
			this.resize();
		},

		normalizePositions: function()
		{
			if( ! document.id("rollWrapper") ){
				return;
			}
			var ph = document.id("portfolioheader").getSize().y;
			var h = window.getSize().y - ( ph + document.id("footer").getSize().y + document.id("rollWrapper").getSize().y );
			var p = Math.round( h/2 );
			if( p < 20 ) {
				p = 20;
			}
			document.id("rollWrapper").setStyles( {"top": p, "visibility": "visible"} );
		},


		resize: function()
		{

		},

		resizeListener: function( e )
		{
			this.normalizePositions();
			this.resize();
		}
	});


	MA_Portfolio_Reel = new Class
	({
	
		shell:null,
		itemPool:null,
		unitW: 344, // scroll distance per step ( 2 columns width )
		leftMaxCorrect: 10, // scroll padding correct to left viewport edge
		colWCalculated:0,
		controlLeftBound:null,
		controlRightBound:null,
		scrollPosStep:0,
		tweening: false,
		initImage: "gfx/portfolio/init.png",

		/**
		 * @type {MA_Portfolio_Controls}
		 */
		controls:null,


		loadPoolUrls: null,
		loadPoolElements: null,
		loadItemCount: 0,


		initialize: function()
		{
			if( ! document.id("roll") ) {
				return;
			}
			var itemPool = [];
			var shell = document.id("roll");
			shell.getElements(".rollItem").each( function( li ) {
				var item =  new MA_Portfolio_Reel_Item( li );
				itemPool.push( item );
			}.bind(this));
			this.shell = shell;
			this.itemPool = itemPool;

			this.initControls();
			this.adjustRollwidth();
			this.replaceLoad();

			if( MA_Touch.isIphone() && !MA_Touch_Orientation.isLandscape() ) {
				( function() {
					new MA_Footer_Touch( 500 );
				}).delay(500);

			}

		},

		replaceLoad: function()
		{
			var loadPoolUrls = [];
			var loadPoolElements = [];
			this.shell.getElements("img.repl").each( function( el ) {
				var url = el.get("src");
				loadPoolUrls.push( url );
				loadPoolElements.push( el );
				el.store( "origURL", url );
				el.set( "src", REMOTE_LAYOUT_BASE + this.initImage ).setStyle("visibility", "visible");
				el.set("tween", {duration:600, transition:"linear" });
			}.bind(this));
			this.loadPoolUrls = loadPoolUrls;
			this.loadPoolElements = loadPoolElements;
			var q = new PreloaderQueue( loadPoolUrls );
			q.addEvent( "success", this.itemLoadListener.bind(this) );
			q.addEvent( "complete", this.itemAllLoadListener.bind(this) );

		},

		itemLoadListener: function( url )
		{
			var el = this.getElForLoadedURL( url );
			el.set( "src", url );
			el.set("opacity", 0).tween.delay( 1000, el, ["opacity", 1]);
			var rollItem = el.getParent(".rollItem");
			var info = rollItem.getElement( ".info" );
			if( !!info ) {
				info.tween( "opacity", 1 );
			}
		 	this.loadItemCount++;
		},

		getElForLoadedURL: function( url )
		{
			var p = this.loadPoolElements;
			for( var i=0; i<p.length; i++)
			{
				if( p[i].retrieve( "origURL") == url ) {
					return p[i];
				}
			}
		},

		itemAllLoadListener: function()
		{
		   if( !!document.id("rollwords") ) {
			   document.id("rollwords").setStyle( "visibility", "visible" ).set("opacity", 0 ).tween.delay( 300, document.id("rollwords"), ["opacity", 1] );
		   }
		},
		
		adjustRollwidth: function()
		{
			var cols = this.shell.getElements("ul");
			var colNum = cols.length;
			var col1 = cols[0];
			var cW = col1.getSize().x + parseInt( col1.getStyle("margin-right") ) ;
			this.colWCalculated = cW;

			this.shell.setStyle( "width", cW * colNum );
			this.shell.set( "tween", {duration:1000, transition:Fx.Transitions.Sine.easeInOut, onComplete:this.tweenEndHandler.bind(this) } );
		},


		initControls: function()
		{
			this.controls = new MA_Portfolio_Controls();
			this.controlLeftBound = this.leftListener.bind(this);
			this.controlRightBound = this.rightListener.bind(this);

			this.controls.addEvent( "right", this.controlLeftBound );
			this.controls.addEvent( "left", this.controlRightBound );

		},

		getPos: function()
		{
			return parseInt( this.shell.getStyle( "left" ) );
		},

		getItemViewportNormalizedMeasure: function()
		{
			return window.getSize().x % this.colWCalculated;
		},


		tween: function( shift )
		{
			if( !this.tweening ) {
				this.shell.set( "tween", {duration:1200, transition:Fx.Transitions.Sine.easeInOut, onComplete:this.tweenEndHandler.bind(this) } );
			}else{
				this.shell.set( "tween", {duration:600, transition:Fx.Transitions.Sine.easeOut, onComplete:this.tweenEndHandler.bind(this) } );
			}
			this.shell.tween( "left", shift  );
			this.tweening = true;
		},
		

		tweenEndHandler: function()
		{
			this.tweening = false;
		},
		
		leftListener: function( e )
		{
			var p = this.getPos();
			var d = this.shell.getSize().x - window.getSize().x;
			var shift;

			if( (p + d) < this.unitW ) {
				shift = ( this.shell.getSize().x - window.getSize().x ) * -1;
			}else{
				shift = p - ( this.unitW + this.getItemViewportNormalizedMeasure() )
			}

			
			this.tween(  shift );
			
			this.scrollPosStep--;
		},
		rightListener: function( e )
		{
			if( !this.scrollPosStep ) {
				return;
			}
			var shift = this.getPos() + this.unitW ;
			if( Math.abs( shift ) < this.unitW ) {
				shift = this.leftMaxCorrect;
			}
			if( shift > this.leftMaxCorrect ) {
				shift = this.leftMaxCorrect;
			}

			this.tween(  shift );

			this.scrollPosStep++;
		}

	});


	MA_Portfolio_Controls = new Class
	({
		Implements:[ Events ],

		leftControl:null,
		rightControl:null,
		h: 66,
		hCorrFac:10,
		xOff:-15,
		xManualCorrection:0,

		initialize: function()
		{
			
			var left = document.id("rollLeftCont");
			var right = document.id("rollRightCont");

			left.addEvent( "click", this.clickListener.bind(this));
			right.addEvent( "click", this.clickListener.bind(this));
			left.addEvent( "mouseenter", this.hoverListener.bind(this) );
			right.addEvent( "mouseenter", this.hoverListener.bind(this) );
			left.addEvent( "mouseleave", this.outListener.bind(this) );
			right.addEvent( "mouseleave", this.outListener.bind(this) );

			left.set( "tween", { duration:200 } );
			right.set( "tween", { duration:200 } );
			window.addEvent("resize", this.position.bind(this) );

			left.setStyle( "visibility", "hidden" );
			right.setStyle( "visibility", "visible" );


			try{
				this.xOff = parseInt( left.getStyle( "background-position" ).split( " " )[0] );
			}catch(e) {
				//return;
			}


			this.leftControl = left;
			this.rightControl = right;

			this.position();
			
		},

		clickListener: function( e )
		{
			document.id("rollLeftCont").setStyle( "visibility", "visible" );
			switch( document.id( e.target ).get("id") )
			{
				case "rollLeftCont" :
					this.fireEvent("left");
					break;

				case "rollRightCont" :
					this.fireEvent("right");
					break;
			}
		},
		position: function()
		{
			var p = document.id("roll").getPosition().y + Math.round( document.id("roll").getSize().y / 2) - Math.round( this.h/2 ) - this.hCorrFac;
			this.leftControl.setStyle( "top", p );
			this.rightControl.setStyle( "top", p );

		},
		hoverListener: function( e )
		{
			var el = document.id( e.target );
			el.tween( "background-position", 0 + ", 0" );
		},
		outListener: function( e )
		{
			var el = document.id( e.target );
			var shift;
			switch( el )
			{
				case this.rightControl :
					shift = Math.abs( this.xOff );
					break;
				case this.leftControl :
					shift = Math.abs( this.xOff ) * -1;
					break;
			}
			el.tween( "background-position", shift + this.xManualCorrection + "px, 0px" );
		}

	});


	MA_Portfolio_Reel_Item = new Class
	({
		Implements:[Events],

		btn: null,
		text:null,
		purple:null,
		el:null,
		delInt:null,

		initialize: function( el )
		{
			var btn = el.getElement(".rollItemInteractive");
			if( !Browser.Features.Touch ) {
				btn.addEvent( "mouseenter", this.hoverItemListener.bind(this) );
				btn.addEvent( "mouseleave", this.leaveItemListener.bind(this) );
			}

			btn.addEvent( "click", this.clickItemListener.bind(this) );
			this.btn = btn;
			this.purple = el.getElement(".rollItemOverlay");
			this.text = el.getElement(".rollItemText");
			this.el = el;

			this.a = el.getElement("a");
			this.a.setStyle("display", "none");


			this.text.set("tween", {duration:200} );
		},
		hoverItemListener: function( e )
		{
			this.text.setStyle( "display", "block" ).set("opacity", 0.01 );
			if( !Browser.ie ) {
				this.text.tween( "opacity", 1 );
			}else{
				this.text.set( "opacity", 1 );
			}
			this.purple.fade(0.6);
		},
		leaveItemListener: function( e )
		{
			//this.text.setStyle("display", "none");
			if( !Browser.ie ) {
				this.text.tween( "opacity", 0.01 );
			}else{
				this.text.set("opacity",0);
			}
			clearInterval( this.delInt );
			this.purple.fade(0.01);
		},
		clickItemListener: function( e )
		{
			window.location.href = this.a.get("href");
		}
	});


	// ############################### PORTFOLIO CATEGORY #################################################
	MA_Portfolio_Category = new Class
	({
		Extends: MA_Portfolio,
		
		initialize: function()
		{
			new MA_Portfolio_Env();
			new MA_Portfolio_Sort();
			new MA_Portfolio_Category_Reel();
		}

	});


	MA_Portfolio_Category_Reel = new Class
	({
		Extends: MA_Portfolio_Reel,

		leftMaxCorrect: 460,
		
		rightListener: function( e )
		{
			if( !this.scrollPosStep ) {
				return;
			}
			var shift = this.getPos() + this.unitW ;
			if( ( Math.abs( shift - this.leftMaxCorrect ) ) < this.unitW ) {
				shift = this.leftMaxCorrect;
			}
			if( shift > this.leftMaxCorrect ) {
				shift = this.leftMaxCorrect;
			}


			this.tween( shift );
			this.scrollPosStep++;
		}
		
	});


	// ############################### CASE STUDIES INDEX #################################################
	// TODO with scroll get exact modulo to screen edge to let the next /previous image come in to close exatly with the edge of the viewport


	MA_CS = new Class
	({
		initialize: function()
		{
			new MA_CS_Env();
			new MA_CS_Reel();
			if( Browser.Features.Touch ) {
				if( MA_Touch.isIphone() ) {
					document.id("content").setStyle("padding-bottom", 80 );
					MA_Touch.orienter.addEvent( "orientationchange" , this.orientationChangeListener.bind(this) );
					this.orientationChangeListener( MA_Touch_Orientation.getOrientation() );

					var fEs = document.id("roll").getElements( ".info .inner" );
					fEs.each( function( fE ) {
						fE.getElement("h3").setStyle.delay( 300, fE, [ "font-size", "14px" ] );
						fE.getElement("p").setStyle.delay( 300, fE, [ "font-size", "13px" ] );
					});
				}
			}
		},
		orientationChangeListener: function( orientation )
		{
			new MA_Footer_Touch( orientation == "portrait" ? 400 : 0 );
		}
	});


	MA_CS_Env = new Class
	({
		Extends: MA_Portfolio_Env,

		initialize: function()
		{
			this.parent();
		},

		normalizePositions: function()
		{
			var ph = document.id("csheader").getSize().y;
			var h = window.getSize().y - ( ph + document.id("footer").getSize().y + document.id("rollWrapper").getSize().y );
			var p = Math.round( h/2 );
			if( p < 10 ) {
				p = 10;
			}
			// TODO shrink or reset the space between heading and keyline
			document.id("rollWrapper").setStyle( "top", p );
		}
	});
	


	MA_CS_Reel = new Class
	({
		Extends: MA_Portfolio_Reel,

		unitW: 480, // scroll distance per step ( 1 item width )
		w:null,

		/**
		 * @type {MA_CS_Controls}
		 */
		controls:null,


		initialize: function()
		{
			var itemPool = [];
			var shell = document.id("roll");
			shell.getElements(".rollItem").each( function( li ) {
				var item =  new MA_CS_Reel_Item( li );
				itemPool.push( item );
			}.bind(this));
			this.shell = shell;
			this.itemPool = itemPool;

			this.initControls();
			this.adjustRollwidth();
			this.replaceLoad();


		},


		adjustRollwidth: function()
		{
			var cols = this.shell.getElements("li");
			var colNum = cols.length;
			var col1 = cols[0];
			var cW = col1.getSize().x + parseInt( col1.getStyle("margin-right") ) ;
			this.colWCalculated = cW;
			this.shell.setStyle( "width", cW * colNum );
			this.w = cW * colNum;
		},


		initControls: function()
		{
			this.controls = new MA_CS_Controls();
			this.controlLeftBound = this.leftListener.bind(this);
			this.controlRightBound = this.rightListener.bind(this);

			this.controls.addEvent( "right", this.controlLeftBound );
			this.controls.addEvent( "left", this.controlRightBound );

		},

		leftListener: function( e )
		{
			var p = this.getPos();
			var d = this.shell.getSize().x - window.getSize().x;
			var shift;
			
			if( (p + d) < this.unitW ) {
				shift = ( this.shell.getSize().x - window.getSize().x ) * -1;
			}else{
				shift = p - ( this.unitW + this.getItemViewportNormalizedMeasure() )
			}

			this.tween( shift );
			this.scrollPosStep--;

		},
		
		rightListener: function( e )
		{
			var shift = this.getPos() + this.unitW ;
			
			if( !this.scrollPosStep ) {
				this.tween(  this.leftMaxCorrect );
				return;
			}

			if( Math.abs( shift ) < this.unitW ) {
				shift = this.leftMaxCorrect;
			}
			if( shift > this.leftMaxCorrect ) {
				shift = this.leftMaxCorrect;
			}
			this.tween(  shift );

			this.scrollPosStep++;

		}

	});


	MA_CS_Controls = new Class
	({
		Extends: MA_Portfolio_Controls,


		initialize: function()
		{
			this.parent();
		}
		
	});


	MA_CS_Reel_Item = new Class
	({
		Extends: MA_Portfolio_Reel_Item,

		initialize: function( el )
		{
			this.parent( el );
		}

	});







	// ######################################### CASE STUDIES ITEM ################################
	// TODO hook
	MA_CS_Study = new Class
	({
		Extends: MA_CS,
		
		initialize: function()
		{
			new MA_CS_Study_Env();
			new MA_CS_Study_Reel();
			new MA_CS_Study_SmallScreenControl();
			new TMShareLink();

			if( Browser.Features.Touch ) {
				document.id("content").setStyle("padding-bottom", 80 );

				if( MA_Touch.isIphone() && !MA_Touch_Orientation.isLandscape() ) {
					new MA_Footer_Touch( 20 );
				}else{
					new MA_Footer_Touch( 0 );
				}
			}

		}

	});


	MA_CS_Study_Env = new Class
	({
		Extends: MA_CS_Env,

		resize: function()
		{
			this.parent();
			var info = document.id("csStudyInfo");
			var reel = document.id("rollWrapper");
			info.setStyles( {
				"margin-top" : reel.getStyle("top")
				//,"padding-bottom" : document.id("footer").getSize().y
			});
		},
		
		normalizePositions: function()
		{
			var backlinkCorrection = 30;
			var ph = document.id("csheader").getSize().y;
			var h = window.getSize().y - backlinkCorrection - ( ph + document.id("footer").getSize().y + document.id("rollWrapper").getSize().y + document.id("csStudyInfo").getSize().y );
			var p = Math.round( h/2 );
			if( p < 10 ) {
				p = 10;
			}
			// TODO shrink or reset the space between heading and keyline
			document.id("rollWrapper").setStyle( "top", p );
		}
	});


	MA_CS_Study_Reel = new Class
	({
		Extends: MA_CS_Reel,

		unitW: 654,
		
		initialize: function()
		{
			var itemPool = [];
			var shell = document.id("roll");
			shell.getElements(".rollItem").each( function( li ) {
				var item =  new MA_CS_Study_Reel_Item( li );
				itemPool.push( item );
			}.bind(this));
			this.shell = shell;
			this.itemPool = itemPool;

			this.initControls();
			this.adjustRollwidth();
			this.replaceLoad();
		},
		itemAllLoadListener: function()
		{
			this.fadeupUl.delay( 300, this );
			this.fadeupInfo2.delay( 700, this );
			this.fadeupInfo.delay(1200, this);
		},
		fadeupInfo: function()
		{
		 	 document.id("csStudyStickyInfo").set("tween", {duration:1000, transition:"linear"} ).tween("opacity",1);
		},
		fadeupUl: function()
		{
			$$("#csStudyInfo ul").tween( "opacity", 1 );
		},
		fadeupInfo2: function()
		{
		   document.id("csStudyInfoP").tween( "opacity", 1 );
		}
	});


	 MA_CS_Study_SmallScreenControl = new Class
	 ({
	    readmore: null,
		initialize: function()
		{
			var h = document.id( window ).getSize().y;
			if( h > 670 ) {
				return;
			}
			this.readmore = document.id( "lowrestrig" );
			this.readmore.setStyle.delay( 2200, this.readmore, [ "display", "block" ] );
			this.readmore.addEvent( "click", this.clickListener.bind(this));
		},
		clickListener: function()
		{
			var sc = new Fx.Scroll( document.id( window ), {
				offset: {
					x: 0,
					y: -30
				},
				duration:600
			} );
			sc.toElement( document.id("studAnch") );
		}
	 });



	MA_CS_Study_Reel_Item = new Class
	({
		Implements:[Events],
		Extends: MA_Portfolio_Reel_Item,

		initialize: function( el )
		{
			this.el = el;
		}
		
	});



	// ######################################### CASE STUDIES ITEM ################################
	MA_News = new Class
	({
		initialize: function()
		{
			if( !!document.id( "newsitemsList" ) ) {
				document.id( "newsitemsList" ).getElements( "a.over img" ).each( function( el ) {
					el.set( "tween", { duration: 200 } );
					if( !Browser.Features.Touch ) {
						el.addEvent( "mouseenter", this.hoverListener.bind(this) );
						el.addEvent( "mouseleave", this.outListener.bind(this) );
					}
				}.bind(this));
				if( Browser.Features.Touch ) {
					new MA_Footer_Touch(  );
				}
			}else{
				if( Browser.Features.Touch ) {
					new MA_Footer_Touch(  );
				}
			}

			if( !!document.id("addthiswrapper") ) {
				new TMShareLink();
			}
		},
		hoverListener: function( e )
		{
			if( !Browser.ie ) {
				document.id(e.target).tween( "opacity", 1 );
			}else{
				document.id(e.target).set( "opacity", 1 );
			}

		},
		outListener: function( e )
		{
			if( !Browser.ie ) {
				document.id(e.target).tween( "opacity", 0.01 );
			}else{
				document.id(e.target).set( "opacity", 0.01 );
			}
		}
	});

})();




var FitImage = new Class(
{
	Implements: [Events, Options],
	interv: null,
	waited:0,
	isMobile:false,

	loadDoneBound: null,
	resizeBound: null,
	injectDelRef:null,

	options: {
		'class': 'resize-background',
		'center': true,
		'minWidth': 1024,
		'minHeight': 768,
		'primary': 'auto',
		'injectElement': null,
		'injectMobileElement' : null,
		'xManual' : null,
		'yManual' : null,
		'injectPosition': 'top',
		'xShiftManual' : null,
		'yShiftManual' : null,
		startupDelay: 0,
		fadeDuration:800

	},

	initialize: function( image, options )
	{
		options = options || {};
		options.primary = options.primary && ['width','height','auto'].contains( options.primary )
			? options.primary
			: 'auto';
		this.setOptions( options );

		
		this.isMobile = Browser.Platform.name == "ios" || Browser.Platform.name == "android";
		if( this.isMobile ) {
			var el = options["injectMobileElement"] ? options["injectMobileElement"] : document.body;
			el.setStyle( "background", "url("+image+") no-repeat" );
			el.setStyle( "-webkit-background-size", (options["xManual"] ? options["xManual"] : "992" ) + "px " +  ( options["yManual"] ? options["yManual"] : "700" ) + "px" );
			el.setStyle("background-position", (options["xShiftManual"] ? options["xShiftManual"] : "0" ) + "px " + (options["yShiftManual"] ? options["yShiftManual"] : "0" ) + "px"  );
			return;
		}

		



		if( Browser.Platform.ios || Browser.Platform.android ) {
			this.options["class"] = this.options["class"] + " mobile";
		}

		this.loadDoneBound = this.loadDone.bind( this );
		this.resizeBound = this.resize.bind( this );

		if( !this.options["triggerAlt"] ) {
			this.image = new Element( 'img', {
				'src': image,
				'class': this.options['class']
			} ).addEvent( 'load', this.loadDoneBound );
		}else{
			this.image = new Element( 'img', {
				'src': image + "?" + new Date().getTime(),
				'class': this.options['class']
			} ).addEvent( 'load', this.loadDoneBound );
		}


		document.id( window ).addEvent( 'load', this.loadDoneBound );
		document.id( window ).addEvent( 'domready', this.resizeBound );
		document.id( window ).addEvent( 'resize', this.resizeBound );

		this.interv = this.checkTime.periodical( 100, this );

	},

	dispose: function()
	{
		this.image.removeEvent( "load", this.loadDoneBound );
	 	document.id( window ).removeEvent( "load", this.loadDoneBound );
		document.id( window ).removeEvent( "domready", this.resizeBound );
		document.id( window ).removeEvent( "resize", this.resizeBound );
		try{
			clearInterval( this.interv );
			clearTimeout( this.injectDelRef );
		}catch(e){}
		this.image.destroy();

	},
	
	checkTime: function()
	{
		this.waited += 100;
	},
	loadDone: function()
	{
		clearInterval( this.interv );
		if( this.waited > 1000 ) {
			this.inject();
		}else{
			this.injectDelRef = this.inject.delay( this.options.startupDelay, this );
		}
	},
	inject: function()
	{
		if( this.injected ) return this;
		if( !this.options.injectElement ) this.options.injectElement = document.id( document ).body;
		this.image.inject( document.id( this.options.injectElement ), this.options.injectPosition );
		this.injected = true;
		// *** If image fails to resize, return launching resize on inject call even after inject becomes true
		this.resize();
		this.resize.delay( 10, this );

		this.image.set( "opacity", 0 ).set("tween", {duration:this.options.fadeDuration, transition:"linear"} ).tween( "opacity", 1 );


		this.fireEvent.delay( 1000, this, ["inject"] );

		return this;
	},

	resize: function()
	{
		var isMobile = this.isMobile;
		var size = !isMobile ?  document.id( window ).getSize() : document.id( window ).getSize() ;
		var rate = size.x / size.y;
		var styles = {};

		if( !this.size || this.size.x == 0 ) {
			// *** Detect image size
			this.size = document.id( this ).getSize();
			if( this.size.x == 0 ) return this; // Not loaded yet
			this.rate = this.size.x / this.size.y;
		}

		
		if( isMobile ) {

			if( this.options.yManual ) {
				styles.height = this.options.yManual;
			}
			if( this.options.xManual ) {
				styles.width = this.options.xManual;
			}
		}

		// *** Set first dimension size
		if( this.options.primary == 'width' || (this.options.primary == 'auto' && this.rate < rate) ) {
			styles.width = size.x;
			styles.height = null;

		} else if( this.options.primary == 'height' || (this.options.primary == 'auto' && this.rate > rate) ) {
			styles.width = null;
			styles.height = size.y;

		} else {
			// *** Perfect fit!
			styles.width = size.x;
			styles.height = size.y;

		}


		// *** Min width && height
		if( styles.width !== null && this.options.minWidth > styles.width )  styles.width = this.options.minWidth;
		if( styles.height !== null && this.options.minHeight > styles.height ) styles.height = this.options.minHeight;

		// *** Calculate second dimension size
		if( styles.width === null ) styles.width = Math.round( styles.height * this.size.x / this.size.y );
		if( styles.height === null ) styles.height = Math.round( styles.width * this.size.y / this.size.x );

		// *** Position in the center of the screen
		if( this.options.center ) {
			// *** Horizontal
			if( styles.width > size.x )      styles.left = 0 - Math.round( (styles.width - size.x) / 2 );
			else if( styles.width < size.x ) styles.left = Math.round( (size.x - styles.width) / 2 );
			else styles.left = 0;

			// *** Vertical
			if( styles.height > size.y ) {
				if( this.isMobile ) {
					styles.top = 0;
				}else{
					styles.top = 0 - Math.round( (styles.height - size.y) );
				}

			} else if( styles.height < size.y ) {
				styles.top = Math.round( (size.y - styles.height) );
			}
			else styles.top = 0;
		}
		styles.height = ( parseInt( styles.height ) - document.id("footer").getSize().y ) + "px";
		this.image.setStyles( styles );
		return this;
	},

	toElement: function()
	{
		return this.image;
	}
} );



var Preloader = new Class({
	'Implements': [Events],
	'initialize': function(file)
	{
		var self = this;
		if( !Browser.ie ) {
			new Request({
				'url': file,
				'method': 'get',
				'onSuccess': function(text)
				{
					self.length = text.length;
					self.fireEvent('onSuccess', [text.length]);
				},
				'onFailure': function()
				{
					self.fireEvent('onFailure');
				}
			}).send();
		}else{
			new Asset.image( file, {onLoad:self.onLoadIe.bind(self) } )
		}
	},
	onLoadIe: function()
	{
		this.fireEvent( "onSuccess" );
	}
});

var PreloaderQueue = new Class
({
	Implements: [Events, Options],
	initialize: function(assets, options)
	{
		var self = this,
			completed = 0,
			errors = 0;

		self.setOptions(options);

		if (self.options.length)
		{
			new Request({
				'url': self.options.length,
				'onSuccess': function(text)
				{
					self.length = text;
					self.fireEvent('onLength', [text]);
				}
			}).send();
		}

		for (i = 0; (asset = assets[i]); i++)
		{
			(function() {
				var reference = asset,
					preloader = new Preloader(reference);

				preloader.addEvents({
					'onSuccess': function(length)
					{
						completed++;

						self.fireEvent('onSuccess', [reference, length, self.length]);

						if (completed == assets.length)
						{
							self.fireEvent('onComplete', [errors]);
						}
					},
					'onFailure': function()
					{
						errors++;
						completed++;

						self.fireEvent('onFailure', [reference]);

						if (completed == assets.length)
						{
							self.fireEvent('onComplete', [errors]);
						}
					}
				});
			})();
		}
	}
});




var TMShareLink = new Class
({
	at: null,
	btn:null,
	men:null,
	interv:null,
	active:false,
	checkIntId:null,

	initialize: function()
	{
		this.at =  document.id("addthiswrapper");
		if( !this.at ) {
			return;
		}
		this.btn = this.at.getElement('.custom_button');
		this.men = this.at.getElement('.hover_menu');

	    $$('#addthiswrapper .custom_button, #addthiswrapper .hover_menu').each( function( el ) {
		    el.addEvent( "mouseenter", this.hoverListener.bind(this) );
		    el.addEvent( "mouseleave", this.leaveListener.bind(this) );
	    }.bind(this));

	},
	hoverListener: function(e)
	{
		var btn = this.btn;
		var men = this.men;
		clearTimeout( this.interv );
		clearInterval( this.interv );
		btn.addClass('active');
		if( this.active ) {
			return;
		}
		men.set("opacity", 0 ).setStyles( {display:"block",bottom:"23px",right:"0px"}).fade("in");
		this.active = true;
	},
	leaveListener: function(e)
	{
		this.btn.removeClass('active');
		this.interv = this.hide.delay( 200, this );
	},
	hide: function()
	{
		var btn = this.btn;
		var men = this.men;
		this.active = false;

		btn.removeClass("active");
		men.fade("out");
	}
});


var de = {};
de.fascina = {};
de.fascina.utils = {};
de.fascina.utils.Deactivator = new Class
({
	dim: null,
	elem: null,
	isWaiter:null,
	opacity:null,
	/** @constructor */
	initialize: function( elem, color, opacity, isWaiter )
	{
		var hideAgain = elem.getStyle( "display") == "none";
		elem.setStyle( "display", "block" );
		this.dim = elem.getSize();
		if( hideAgain ) elem.setStyle( "display", "none" );
		this.elem = elem;
		this.isWaiter = isWaiter;
		this.color = !!color ? color : "#ffffff";
		this.opacity = !!opacity  ? opacity : 0.6;
		elem.store( "deactivator", this );
		return this;
	},
	show: function()
	{
		var overlay = new Element( "div" );
		overlay.set( "opacity", this.opacity );
		overlay.addClass( "deactivator" );
		overlay.setStyles(
			{
				width: this.dim.x,
				height: this.dim.y,
				background: ( this.isWaiter ? this.color + " url("+REMOTE_LAYOUT_BASE+"gfx/ajax/progressbar_loading.gif) center no-repeat" : this.color ),
				position: "absolute",
				"z-index":6000,
				top:0,
				left:0
			}
		);
		overlay.inject( this.elem );
		this.elem.store( "deactivator", overlay );
	},
	hide:function()
	{
		try {
			this.elem.retrieve("deactivator").dispose();
			return true;
		}catch( e ) {
			return false;
		}
	}
});





de.fascina.utils.IdleSpy = new Class({
	Implements: [Options, Events],

	options: {
	  idleTime: 60000 //1 min
	},

	el:null,

	initialize: function(options, element) {
	  this.setOptions(options);
	  this.idle = false;
	  this.el = !!element ? element : document.body;
	  $(this.el).addEvents({
		'mousemove': this.doBack.bind(this),
		'mousewheel': this.doBack.bind(this),
		'keydown': this.doBack.bind(this)
	  });
	},

	start: function() {
	  this.idleTimer = this.doIdle.delay(this.options.idleTime, this);
	},

	doBack: function() {
	  if (this.idleTimer) {
		clearTimeout(this.idleTimer);
	  }
	  if (this.idle) {
		this.idle = false;
		this.fireEvent('back');
	  }
	  this.start();
	},

	doIdle: function() {
	  if (this.idleTimer) {
		clearTimeout(this.idleTimer);
	  }
	  this.idle = true;
	  this.fireEvent('idle');
	 // this.idleTimer = this.doIdle.delay(this.options.idleTime, this);
	}
});
