/**
 * © Schellenberg + Benz, Zürich
 * schellenberg-benz.ch 
 * author: GOELDI | goeldi.eu
 */
var blokk, fadeCanvas, slideBlock, slider, slideLeft, curIndex, sliderCookie, intro, videoCanvas,videoRuns = false;
var Back2 = new Fx.Transition(function(pos, x){
	x = x && x[0] || 1.618;
	return Math.pow(pos, 4) * ((x + 1) * pos - x);
});
window.addEvent('domready', function() {
/**********************
 * THE LOG
 */	
/*/
	document.body.adopt(
	new Element('div', {
			id: 'console',
			html:'Ich bin die Konsole',
			style:'position:absolute;width:200px;top:0;right:0;z-index:3000;opacity:0.8;background-color:black;color:green;font-size:12px;font-family:courier,sans-serif;'
		}));
	console = $('console');
	var log = function(nameit) {
		console.adopt(new Element('p',{html:nameit}));
	}
	//*/
	//*
	var log = function(gotonirvana) {
		
	}
//*/	
	
	/*************************
	 * FUNCTIONS
	 */
	/** slideshow */
	function slideShow() {
		if (slider) {
			var sliderButtons = $('slider-buttons');
			if (sliderButtons) {
				var left = sliderButtons.getChildren()[0];
				var right = sliderButtons.getChildren().getLast();
				right.setStyle('opacity', 0.2);
				left.setStyle('opacity', 0.2);
				var maxIndex = slider.getElements('li').length - 1;
				
				var fadeButtonright = new Fx.Tween(right, {
					duration : 400,
					property : 'opacity'
				});
				var fadeButtonleft = new Fx.Tween(left, {
					duration : 400,
					property : 'opacity'
				});
				var shiftImage = new Fx.Tween(slider, {
					duration: 2000,
					property: 'margin-left',
					transition: Back2.easeOut,
					link: 'cancel'
				});
				left.addEvents({
					'click': function(){
						if (videoRuns) return;
						var newIndex = (curIndex == 0) ? maxIndex : (curIndex - 1);
						shiftImage.start((curIndex * -960),(newIndex * -960));
						curIndex = newIndex;
						Cookie.write(sliderCookie,curIndex);
					},
					'mouseenter': function(){
						if (videoRuns) return;
						fadeButtonleft.start('0.2','0.6');
					},
					'mouseleave': function(){
						if (videoRuns) return;
						fadeButtonleft.start('0.6','0.2');
					}
				});
				right.addEvents({
					'click': function(){
						if (videoRuns) return;
						var newIndex = (curIndex == maxIndex) ? 0 : (curIndex + 1);
						shiftImage.start((curIndex * -960),(newIndex * -960));
						curIndex = newIndex;
						Cookie.write(sliderCookie,curIndex);
					},
					'mouseenter': function(){
						if (videoRuns) return;
						fadeButtonright.start('0.2','0.6');
					},
					'mouseleave': function(){
						if (videoRuns) return;
						fadeButtonright.start('0.6','0.2');
					}
				});
			}
		}
	}
	
	// video start
	function videos() {
	   if (videoCanvas) {
	   		log(videoCanvas.get('class'));
	   		log($('video-container'));
	   	   videoCanvas.fade('hide');
	   	   videoCanvas.setStyle('display','block');
	   	   var jwpPlayer;
		   $(videoCanvas).addEvent('click:relay(div.video-stop)', function(event) {
		   		log('hello stop');
	   			new Fx.Tween(videoCanvas, {
	   				property:'opacity'
	   			}).start(1,0).chain(function() {
	   				jwpPlayer.stop();
	   				videoCanvas.getChildren().destroy();
	   				videoCanvas.adopt(new Element('div.video-stop')).adopt(new Element("div#video-container")).setStyle('display','none');
	   			});
	   			videoRuns = false;
		   });
		   
		   $$('div.video-start').addEvent('click', function(event) {
		   		log('hello start');
		   	jwpPlayer = jwplayer("video-container").setup({
			  	file: sb.webroot + "projects/"+event.target.get('rel')+"/"+event.target.get('name')+".mp4",
			    modes: [
			        { type: 'html5' },
			        { type: 'flash', src: sb.webroot+'jwp/player.swf' },
			        { type: 'download'}
			    ],
			    //autostart: true,
			    width: 540,
			    height:304,
			    skin: sb.webroot + 'jwp/glow/glow.zip',
			    events: {
				    onError: function(event) {
				    	log(event.message);
				    },
				    onReady: function(event){
				    	log('READY');
				    	jwpPlayer.play(true);
				    },
				    onPlay: function(event) {
				    	log('PLAY');
			    	}, 
			    	onComplete: function() {
			    		log('hello stop');
	   					new Fx.Tween(videoCanvas, {
	   							property:'opacity'
	   					}).start(1,0).chain(function() {
	   						jwpPlayer.stop();
	   						videoCanvas.getChildren().destroy();
	   						videoCanvas.adopt(new Element('div.video-stop')).adopt(new Element("div#video-container")).setStyle('display','none');
	   					});
	   					videoRuns = false;
			    	}
			    }
			  });
			  //if (Browser.ie) jwpPlayer.play();
			  videoRuns = true;
		      videoCanvas.setStyle('display','block');
		      videoCanvas.fade('in');
	   	});
	   }
   }
	
	/**
	 * init blokk and slider, blokk-tweener, go to current position of slideshow
	 */
	function init() {
		blokk = $('blokk');
		slider = $('slider');
		intro = $('intro');
		videoCanvas = $('video-canvas');
		videoRuns = false;
		// the blokk tweener instance
		if(blokk) {
			blokk.hasClass('no-subnav') ? slideLeft = 615 : slideLeft = 900;
			blokk.setStyle('width', slideLeft);
			slideBlock = new Fx.Tween(blokk, {
				duration : 1000,
				property : 'left',
				link:'ignore'
			});
		} else {
			slideBlock = null;
		}
		// cookie for memorizing last slideshow position
		if (slider) {
			sliderCookie = slider.get('rel')+'ImgIndex';
			curIndex = Cookie.read(sliderCookie) ? Cookie.read(sliderCookie).toInt() < slider.getChildren('li').length ? Cookie.read(sliderCookie).toInt() : 0 : 0;
			slider.setStyle('margin-left',curIndex*-960);
		}
		// the intro text scrolling
		if (intro) {
			var maxY = null;
			var cY = 0;
			var stepY = 120;
			var frameH = intro.getStyle('height').toInt();
			var introDown = document.id('intro-down');
			var introUp = document.id('intro-up');
			
			var fadeButtonUp = new Fx.Tween(introUp, {
				duration : 400,
				property : 'opacity'
			});
			var fadeButtonDown = new Fx.Tween(introDown, {
				duration : 400,
				property : 'opacity'
			});
			
			var introScroller = new Fx.Scroll(intro, {
				onComplete: function() {
					if (cY >= maxY) fadeButtonDown.start('0.6','0.2'); 
					if (cY <= 0) fadeButtonUp.start('0.6','0.2');
				},
				link:'cancel',
				transition: Back2.easeOut,
				duration:1000
			});
			
			introDown.addEvents({	
				'click': function() {
					maxY = maxY || document.id('introtext').getSize().y - frameH;
					log(maxY);
					var newY = (cY + stepY) > maxY ? maxY : cY + stepY;
					if (cY < maxY) introScroller.start(0, newY);
					cY = newY;
				},
				'mouseenter': function() {
					maxY = maxY || document.id('introtext').getSize().y - frameH;
					if (cY < maxY) fadeButtonDown.start('0.2','0.6');
				},
				'mouseleave': function() {
					maxY = maxY || document.id('introtext').getSize().y - frameH;
					if (cY < maxY) fadeButtonDown.start('0.6','0.2');
				}
			});
			
			introUp.addEvents({
				'click': function() {
					maxY = maxY || document.id('introtext').getSize().y - frameH;
					var newY = (cY - stepY) < 0 ? 0 : cY - stepY;
					if (cY > 0) introScroller.start(0, newY);
					cY = newY;
				},
				'mouseenter': function() {
					maxY = maxY || document.id('introtext').getSize().y - frameH;
					if (cY > 0) fadeButtonUp.start('0.2','0.6');
				},
				'mouseleave': function() {
					maxY = maxY || document.id('introtext').getSize().y - frameH;
					if (cY > 0) fadeButtonUp.start('0.6','0.2');
				}
				
			});
		}
	}
	
	/**
	 * do fade in canvas, prepare slideshow (loading images)
	 */
	function entering() {
		if (slider) {
			slider.getElements('li img').each(function(imag) {
				if(imag.get('rel')) {
					imag.setProperty('src', imag.get('rel'));
				}
			});
		}
		
		fadeCanvas.start(0,1).chain(function() {
			if(slideBlock) {
				slideBlock.start(-(slideLeft), 0);
			}
		});
		
	}
	
	/**
	 * 
	 */
	function changeStatus(aidi) {
		if (!slideBlock) {
    		fadeCanvas.start(1,0).chain(function(){
			canvasRequest.post('action=canvas&id='+aidi);
			navRequest.post('action=nav&id='+aidi);
			});
    	} else {
	    	slideBlock.start(0,-(slideLeft)).chain(function() {
	    		//alert (typeof(navRequest.post));
				fadeCanvas.start(1,0).chain(function(){
				canvasRequest.post('action=canvas&id='+aidi);
				navRequest.post('action=nav&id='+aidi);
				});
			});
		}
	}
	
	
	/**********************
	 * DONE ONLY FIRST TIME (global elements not destroyed by AJAX)
	 */
	//*
	var History = window.History; 
    
    History.Adapter.bind(window,'statechange',function(){ 
        var State = History.getState(); 
        //History.log(State.data, State.title, State.url);
        changeStatus(State.data.id);
        
    });
	//*/
	// the canvas tweener instance
	fadeCanvas = new Fx.Tween('canvas', {
		duration : 1000,
		property : 'opacity',
		link:'cancel'
	});
	init();
	entering();
	slideShow();
	videos();

	
	/**********************
	 * AJAX CALLED WHEN LINK CLICKED
	 */
	
	var navRequest = new Request.HTML({
        url: sb.webroot + 'ajax.php',
        onSuccess: function(response){
            var n = $('nav');
        	n.getChildren().destroy();
            n.adopt(response);
            
        }
    });
    
	var canvasRequest = new Request.HTML({
        url: sb.webroot + 'ajax.php',
        encoding: 'utf-8',
        onSuccess: function(response){
        	var c = $('canvas');
        	c.getChildren().destroy();
            c.adopt(response);
            init();
			entering();
			slideShow();
			videos();
        }
    });
    
    var hans = $$('#nav,#canvas,#head');
    // site change
    hans.addEvent('click:relay(a.intern)', function(event,anchor) {
    	event.preventDefault();
    	if (History.enabled) {
    		Cookie.write('s-b-currentSite','home');
    		History.pushState({id:''+anchor.get('id')}, "Schellenberg + Benz, Zürich", anchor);
    	} else {
    		Cookie.write('s-b-currentSite',anchor.get('id'));
    	}
    	
    	changeStatus(anchor.get('id'));
    	
   });
   

   
   
});

