var hl;
Event.observe(window, 'load', function() {

	$$(".options a").invoke("observe","mouseover",function(event){
		var el = Event.element(event);
		var hl = new jhAction(el);
	});

	var click = new jhView();

});

var jhView = Class.create({
	initialize: function(){
		this.wrapper 	= $("content");
		this.duration	= 0.5;
		$$(".options a").invoke("observe","click",this.loadPage.bind(this));
		$("homepage").observe("click",this.loadPage.bind(this));
	},
	inPageLinks: function(){
		$$(".sitelinks a").invoke("observe","click",this.loadPage.bind(this));
		if($("directLink") != null) $("directLink").observe("click",this.loadSinglePage.bind(this));
	},
	loadSinglePage: function(event){
		Event.stop(event);
		this.element	= Event.element(event);
		this.page = "wizard";
		
		new Ajax.Request("pages/loader.php",{
			parameters: "page="+this.page,
			onComplete:function(t){
				var resp = t.responseText;
				this.crossfade(resp);
			}.bind(this)
		});
	},
	loadPage: function(event){
		Event.stop(event);
		this.element	= Event.element(event);
		if(this.element.tagName == "SPAN") this.element = this.element.up()
		this.page		= this.element.className;
		
		
		new Ajax.Request("pages/loader.php",{
			parameters: "page="+this.page,
			onComplete:function(t){
				var resp = t.responseText;
				this.crossfade(resp);
			}.bind(this)
		})
	},
	observeHomeLink: function(){
		$$(".options a").invoke("observe","click",this.loadPage.bind(this));
		
		$$(".options a").invoke("observe","mouseover",function(event){
			var el = Event.element(event);
			var hl = new jhAction(el);
		}.bind(this));
	},
	crossfade: function(resp){
		new Effect.Fade(this.wrapper,{duration:this.duration,
			afterFinish: function(){
				this.wrapper.update(resp);
				new Effect.Appear(this.wrapper,{duration:this.duration});
				$$(".choices a").invoke("observe","click",this.showForm.bind(this));
				
				$$(".trucks a").invoke("observe","click",this.showTruck.bind(this));
				this.openSelector 	= false;
				this.currentItem	= $("minitruck");
				
				$$("a.enlarge").invoke("observe","click",this.showGallery.bind(this));
				
				if(this.page == "jungheinrich") this.observeHomeLink();
				
				this.inPageLinks();
			}.bind(this)
		});
	},
	showGallery: function(event){
		Event.stop(event);
		var el = Event.element(event);
		this.gallery = new jhGallery(el)
	},
	showTruck: function(event){
		Event.stop(event);
		var element = Event.element(event);
		
		// update selector
		$$(".trucks a").invoke("removeClassName","active");
		element.addClassName("active");
		
		// load div name
		this.newItem = $(element.href.split("#").last().gsub("-","").toLowerCase());
		
		new Effect.Fade(this.currentItem,{duration:0.5});
		new Effect.Appear(this.newItem,{duration:0.5,delay:0.5});
		this.currentItem = this.newItem;			
	},
	showForm: function(event){
		Event.stop(event);
		$$(".choices a").each(function(el){
			el.removeClassName("active");
			el.up().writeAttribute("style",false);
		});
		var element = Event.element(event);
		element.addClassName("active");
		
		$$(".choices li").each(function(el){
			if(el.down().hasClassName("active")) return;			
			new Effect.Fade(el,{duration:0.4,from:1, to:0.5})
		}.bind(this))
		
		$("adid").value = element.innerHTML;
		
		this.formid	= $('gezienForm');
		
		if(!$("form").hasClassName("opened")){
			new Effect.BlindDown("form",{duration:this.duration,
				afterFinish: function(){
					new Effect.ScrollTo(this.formid,{duration:this.duration,delay:0.25})
					
					$$(".filled").invoke("observe","focus",function(event){
						var el = Event.element(event);
						el.removeClassName("filled");
						el.value = "";
						el.stopObserving("focus");
					})
					$("offerte").observe("change",this.showOfferteField.bind(this));
				}.bind(this)
			});
			$("form").addClassName("opened");
		}
		
		$("verstuurForm").observe("click",this.checkForm.bind(this));
	},
	showOfferteField: function(){
		$('offerteWrapper').toggle();
	},
	checkForm: function(event){
		Event.stop(event);
		var element		= Event.element(event);
		
		var inputs 		= this.formid.getInputs('text');
		var form_values = this.formid.serialize(true);
		var reg 		= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		
		var missed 		= false;
		var falseMail	= false;
		var av			= false;
		
		var mailCheck 	= "";
		var fieldCheck	= "";
		var avCheck		= "";
		
		inputs.each(function(i){

			if(i.hasClassName("req") && i.hasClassName("email") && reg.test($F(i)) == false){
				i.addClassName("missed");
				falseMail 	= true;
				mailCheck 	= "- Het ingevulde email adres is niet geldig<br />";
			}
			else if(i.hasClassName("req") && $F(i) == ""){
				i.addClassName("missed");
				missed 		= true;
				fieldCheck 	= "- Niet alle velden in het formulier zijn ingevuld<br />";
			}
			else if(i.hasClassName("filled")){
				i.addClassName("missed");
				missed 		= true;
				fieldCheck 	= "- Niet alle velden in het formulier zijn ingevuld<br />";
			}
			else i.removeClassName("missed");

		});	
		if($("av").checked == false){
			av 		= true;
			avCheck = "- Je bent nog niet akkoord gegaan met de algemene voorwaarden<br />";
		}
		
		if(missed == true || falseMail == true || av == true){
			var pos = $("verstuurForm").cumulativeOffset();
			var tt = new toolTip(fieldCheck+mailCheck+avCheck);
			tt.setPostion([pos[0]+50,pos[1]]);
			return false;
		}
		$("verstuurForm").disabled = true;
		new Ajax.Request('pages/handle_form.php',{
			parameters: form_values,
			onComplete: function(r){
				var resp = r.responseText;
				this.updateContents(resp);
			}.bind(this)
		});
	},
	updateContents: function(resp){
		// current height
		var wrapper = $("contentUpdater");
		var oh 		= wrapper.getHeight();
		var inner	= $("contentUpdater").down();
		
		wrapper.setStyle({height: oh+"px"});
		
		new Effect.Fade(inner,{duration:this.duration,
			afterFinish: function(){			
				inner.update(resp);
				var nh = inner.getHeight();			
				
				// resize bord to org size
				this.resizeBord(nh,oh,inner);
			}.bind(this)
		});

	},
	resizeBord: function(nh,oh,inner){
		new Effect.ScrollTo(inner,{duration:this.duration});
		new Effect.Appear(inner,{duration:this.duration});
		var yScale = (nh / oh) * 100;
		new Effect.Scale("contentUpdater", yScale, {scaleX: false, duration:this.duration, scaleContent: false});
	}
});

var jhGallery = Class.create({
	initialize: function(element){
		this.element		= element;
		
		this.overlay 		= new overlay();
		this.overlayBox		= this.overlay.overlayBox;
		this.wrapper		= this.overlay.wrapper;
		var h				= $("content").getHeight();
		this.overlay.fixHeight(h);
		this.pageCount		= 0;
		this.updateOverlay();
		
	},
	updateOverlay: function(){
		new Ajax.Request('pages/get_gallery.php',{
			//parameters: 'pid='+this.pid,
			onComplete: function (r){
				var resp = r.responseText;
				this.wrapper.update(resp);

				this.showItem(this.overlayBox,0.5);
				
				$$(".gallery img").invoke("observe","click",this.updateImg.bind(this));
				
				$$("#overlayBox .close").invoke("observe","click",function(event){
					Event.stop(event);
					this.overlay.closeOverlay();
				}.bind(this));

			}.bind(this)
		});
	},
	updateImg: function(event){
		this.img = Event.element(event);
		$$(".gallery img").invoke("removeClassName","active");
		this.img.addClassName("active");
		
		this.loadNewImg();
	},
	loadNewImg: function(){
		this.imgId 		= this.img.id.replace("img","");
		this.loadImg	= "images/imp/eje"+this.imgId +".jpg";
		$("updarteImg").src 		= this.loadImg
		//updarteImg
	},
	showItem: function(item2show,delay){
		var d = (delay == "") ? 0 : delay;
		new Effect.Appear(item2show,{duration:0.5, delay:d});
	},
});

var jhAction = Class.create({
	initialize: function(element){
		this.effect = null;
		this.element	= element;
		if(this.element.tagName == "A") this.element = this.element.down()
		this.wrapper	= this.element.up();
		this.moveUp();
	},
	moveUp: function(){
		if(this.effect != null) this.effect.cancel();
		this.effect = new Effect.Move(this.element, { y: 130, mode: 'absolute',duration:0.25});
		this.observeMouseOut();
	},
	observeMouseOut: function(){
		document.observe('mouseover', function(event){
			var element = Event.element(event);
			if(element.tagName == "A") element = element.down()
			
			if (element.descendantOf(this.wrapper) == false){
				this.debug(this.wrapper.id);
				this.effect.cancel();
				this.moveDown();
				document.stopObserving('mouseover');
			}
		}.bind(this));
	},
	moveDown: function(event){
	
		this.effect = new Effect.Move(this.element, { y: 150, mode: 'absolute',duration:0.25,
			afterFinish: function(){
				this.element.writeAttribute("style",false);
			}.bind(this)
		});		
	},
	debug: function(val){
	//	$("debug").update(val).show();
	}
});

var toolTip = Class.create({
	initialize: function(tip) {
		if($('toolTip') == null){
			$$("body").first().insert(
		      new Element('div',{ id: 'toolTip' })
		    );
		}
		this.tip  	= tip;
		this.delay	= 5000;
		this.tipDiv = $('toolTip'); 
		this.tipDiv.hide();
		this.tipDiv.update(this.tip);
		this.showTip();
		this.timer = null;
		clearTimeout(this.timer);
	},
	showTip: function(){
		new Effect.Appear(this.tipDiv,{duration:0.3,delay:0.2});
		this.timer = setTimeout(function(){
			this.fadeTip();
		}.bind(this), this.delay );
	},
	fadeTip: function(){
		new Effect.Fade(this.tipDiv,{duration:0.3});
		this.timer = setTimeout( function(){
			this.tipDiv.remove();
		}.bind(this), 300);
	},
	cancelTip: function(){
    	if(!this.timer) return;
    	clearTimeout(this.timer);
    	this.tipDiv.remove();
  	},
	setPostion: function(pos){
		var x = pos[1];
		var y = pos[0];
		
		this.tipDiv.setStyle({
			position: 'absolute',
			top: (x)+'px',
			left: (y) + 'px',
			width: 'auto'
		});	
	}
});

var overlay = Class.create({
	initialize: 	function() {
		$$("body").first().insert(
	      new Element('div',{ id: 'overlay' })
	    );
		$$("body").first().insert(
	      new Element('div',{ id: 'overlayBox' }).update("<div class='middle'></div>") //<a href='#' id='closeOverlay'>sluiten</a>
	    );
		this.delay		= 2000;
		this.overlay 	= $('overlay'); 
		this.overlayBox	= $('overlayBox')
		this.overlayBox.hide();
		
		this.overlay.hide();
		this.showOverlay();
	},
	showOverlay: 	function(){
		var arrayPageSize = this.getPageSize();
		this.pageHeight = arrayPageSize[1];
		this.overlay.setStyle({ height: this.pageHeight + 'px' });
		
		var vph = document.viewport.getScrollOffsets() 
		this.overlayBox.setStyle({
			top : 210+"px"
		});
		
		new Effect.Appear(this.overlay,{duration:0.5, from:0.0, to:0.01});
		this.overlay.observe('click',this.closeOverlay.bind(this));
		
		this.wrapper = this.overlayBox.down(); 

	},
	showInner: 		function(){
		var overlayBoxHeight = this.overlayBox.getHeight();
		var marginTop = this.pageHeight - (overlayBoxHeight+400);
		
		var arrayPageScroll = document.viewport.getScrollOffsets();
        var posTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
		
		this.overlayBox.setStyle({ top: posTop+'px' });
		new Effect.Appear(this.overlayBox,{delay:0.6,duration:0.5});
	},
	updateOverlay: 	function(update){
		this.overlayBox.update(update);
		this.showInner();
	},
	fixHeight: function(height){
		this.overlayBox.setStyle({
			height:height+"px"
		});
	},
	closeOverlay: 	function(){
		new Effect.Fade(this.overlayBox,{duration:0.2, from:1, to:0.0});
		new Effect.Fade(this.overlay,{delay:0.2, duration:0.5, from:0.01, to:0.0});
		
		timer = setTimeout( function(){
			$('overlayBox').remove();
			$('overlay').remove();
		}, 600);
	},
	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];
		
	}
});
