// Utils Module ///////////////////////////////////

var MKRAFT = MKRAFT || (function(global, $){
	var namespace = function (ns_string, global) {
			var parts = ns_string.split('.'),
				parent = global || window,
				l = parts.length,
				i;
			
			for (i = 0; i < l; i += 1) {
				parent = parent[parts[i]] || (parent[parts[i]] = {});
			}
			
			return parent;
		},
		log = function(value){
			if(typeof console !== "undefined") console.log(value);
		};
	return {
		namespace: namespace,
		log: log
	}
}(window, jQuery));

/* Tweening Funktion to write
var TWEEN = (function(global){
	var inited = false,
		open = false,
		minHeight=34,
		maxHeight=371,
		instance,
		interval,
		startTime,
		totalTime,
		initialValue,
		deltaValue,
		log = function( value ){
			if(console) console.log(value);
		},
		getTimer = function(){
			return new Date().getTime();
		},
		ease = function(t, b, c, d){
			//return c * ((t = t / d - 1) * t * t + 1) + b;
			if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
			return c / 2 * ((t -= 2) * t * t + 2) + b;
		},
		move = function(){			
			var time = getTimer() - startTime;			
			instance.height = ease(time, initialValue, deltaValue, totalTime);
			if(time>totalTime) clearInterval(interval);
		},
		animate = function( value, duration ){
			clearInterval(interval);
			
			startTime = getTimer();
			totalTime = duration;
			initialValue = Number(instance.height);
			deltaValue = value - initialValue;
			
			interval = setInterval(move, 33);
		};
}(window));
*/

// Module FLATLIFT ////////////////////////////////

var FLATLIFT = (function(global, $){
		
	///////////////////////////
	
	// Sevice Methods
	
	var log = MKRAFT.log;
	
	// Init Methods
	
	var lang,
		getLang = function(){
			return $('#mNav').attr('class');
		},
		init = function(){
			//$('#main .col').hyphenate();
			
			// Init Modules
			FLATLIFT.showroom.init();
			FLATLIFT.products.init();
			initTracker();
			
			// Links
			$('a').live('click', handleLink);
			//$('a').address();  
			   
			// Init internal
			initNavigation();
			initContent();
			
			currentPath = cropPathname(window.location.pathname);
			serverPath = window.location.protocol+"//"+window.location.host;
			log("serverpath: "+serverPath);
			
			$.address.init(handleAddressInit)
			$.address.externalChange(handleAddressChange);
		},
		pageTracker,
		initTracker = function(){
			try{
				global.pagetracker = pageTracker = global._gat._getTracker("UA-2579749-3");
				pageTracker._anonymizeIp();
				pageTracker._trackPageview();
			} catch(err) {}
			   log("init pageTracker: "+pageTracker);
			/*try{
				global.pagetracker = pageTracker = global._gat._getTracker("UA-2579749-22");
				pageTracker._trackPageview();
			} catch(err) {}
			log("init pageTracker: "+pageTracker);*/		
			
		},
		onNaviOver = function(){
			jQuery('#mNav > ul > li > ul').not(jQuery('ul',this)).hide();
			jQuery('ul', this).show();

			if( jQuery.contains(this, $('#pLink')[0] ) ){
				FLATLIFT.products.show();
			} else {
				FLATLIFT.products.hide();
			}
			
			return false;
		},
		onNaviLeave = function(){
			jQuery('#mNav > ul > li > ul').not(jQuery('ul.active',this)).hide();
			jQuery('#mNav > ul > li > ul.active').show();

			/*if( jQuery.contains(this, $('#pLink')[0] ) )*/ FLATLIFT.products.hide();
			
			return false;
		},
		initNavigation = function(){	// Hauptnavigation
			jQuery('#mNav > ul > li').live("mouseover", onNaviOver);
			jQuery('#kontaktleiste').mouseover(onNaviLeave);
			jQuery('#header').mouseleave(onNaviLeave);
			/*jQuery('#pLink').live("mouseover", function(){
				onNaviOver();
				FLATLIFT.products.show();
				return false;										
			});*/
		},
		initContent = function( context ){
			var newLang = getLang();
			log("checkLang: "+newLang+" != "+lang+" => "+currentPath);
			
			if(newLang != lang){
				if(!lang){
					lang = newLang;
				} else {
					window.location.href = currentPath;
					return;
				}
			}
			
			initScrollPane(context);
			initFeatureList(context);
			$(".scroll", context).scrollable();
			FLATLIFT.showroom.activateLinks();
		},
		initFeatureList = function(context){
			$.featureList(
				$("#relV .tabs li a", context),
				$("#relV .output li", context), { start_item : 0	}
			);
			$.featureList(
				$("#vTools .tabs li a", context),
				$("#vTools .output li", context), {
					transition_interval : "0",
					start_item : 0				
				}
			);
			$("#relV .tabs li a", context).click(function(){
				//$('body').scrollTo( $('#main'), 800 );
				$('body').scrollTo( 0, 800 );
			});
		},
		initScrollPane = function(context){	// jScrollPane
			var maxWidth = 990;
			var ulWidth = 0;
			//$.each($('.varianten ul li'), function(i, li) {
			$('.varianten ul li', context).each(function(i, li) {
				ulWidth += $(li).width();
			});
			if (ulWidth > maxWidth) {
				$('.varianten ul li:last-child', context).css('margin-right','56px');
			}
			//$('.varianten').jScrollPane({showArrows: true,arrowScrollOnHover: true,animateScroll: true});
			
			var pane = $('.varianten', context);
			pane.jScrollPane({
				showArrows: true,
				animateScroll: true,
				arrowScrollOnHover: true
			});
			var api = pane.data('jsp');
	
			if ($('.varianten li a', context).hasClass("active")) {
				$('.varianten li a.active', context).bind(
					'load',
					function() {
						// Note, there is also scrollToX and scrollToY methods if you only
						// want to scroll in one dimension
						var targetElementSelectorString = $('.active',this);
						
						$pane[0].scrollTo(targetElementSelectorString);
						return false;
					}
				);
			}
			
			var w = 0;
			$(".varianten ul li", context).each(function() {
				w += $(this).width();
			});
			   
			if (w < maxWidth)
				$('<div class="varFiller"></div>', context).appendTo('.varianten ul').css('width', (maxWidth-w)+'px');
		};
	
	// Some Methods
	
	var handleLink = function(){
			if( $(this).hasClass('noAjax') ||
				this.href.indexOf('javascript:') != -1 ||
				this.href.indexOf('mailto:') != -1 ){
				return true;
			}
			
			var href = $(this).attr("href");
			log("loadLink "+href);
			
			loadSite(href, this.target);
			return false;
		},
		currentPath,
		serverPath,
		cropPathname = function( pathname ){
			return pathname.replace(/[\/\s]*$/g, "").replace(/^\s*/g, "");
		},
		addressEventToString = function(event){
			return "[AddressEvent value:"+event.value+", path:"+event.path+", pathNames:"+event.pathNames+", parameterNames:"+event.parameterNames+", parameters:"+event.parameters+", queryString:"+event.queryString+"]";
		},
		handleAddressInit = function(event){
			//for(var i in event) log(i+" => "+event[i]);
			log("init: "+addressEventToString(event));
		},
		handleAddressChange = function(event){
			
			// Overwriteds the init Method
			handleAddressChange = function(event){
				log("change: "+addressEventToString(event));
				loadSite( cropPathname(event.value) );
			}
			
			if(cropPathname(event.path) == "/" || cropPathname(event.path) == ""){
				log("startPath blank");
				return;
			}
			log("startPath "+cropPathname(event.path));
			
			handleAddressChange(event);
			
		},
		handleSiteRequest = function(responseText, textStatus, XMLHttpRequest){
			log("handleSiteRequest(responseText, "+textStatus+", "+XMLHttpRequest+")");
			
			if(textStatus!="success"){
				log("loadError");
				return;
			}
			
			// Change body id
			
			var searchText = '<body id="',
				iStart = responseText.indexOf('<body id="'),
				iEnd,
				id = 'b00';
				
			if(iStart!=-1){
				iStart += searchText.length;
				iEnd = responseText.indexOf('"', iStart);
				id = responseText.substring(iStart, iEnd);
			}
			
			FLATLIFT.showroom.toggle( responseText.indexOf('class="home"')!=-1 );
			
			$('body').attr('id', id);
			//log('body id:'+id+' | isHome:'+( responseText.indexOf('class="home"')!=-1 ));
			//"body "+$('body', responseText)[0]+" id "+$('body', responseText).attr('id') );
			//$('body').attr('id', $('body', responseText).attr('id'));
			
			// Change Content
			
			$('#main').replaceWith( $('#main', responseText) );
			//$('#navi').replaceWith( $('#navi', responseText) );
			
			initContent($("#main")[0]);
			
			// Change Title
			
			var t = responseText.match(/<title>(.*)<\/title>/);
			//$("title").html(t[1]); // Doesn't work in IE
			global.document.title = t[1];
		},
		loadSite = function(href, target){	
			//log("FLATLIFT.loadSite("+href+", "+target+");");
			if(!href || href=="") return;
			
			var i = href.indexOf(serverPath);
			if(i!=-1 && i<5) href = href.substring(i+serverPath.length);
			
			href = cropPathname(href);
			if(!target || target==="_self" ){
				//global.location.href = href;
				
				if(href==currentPath) return;
				log("loadSite: "+currentPath+" => "+href);
				currentPath = href;
				
				$.address.value(href);
				FLATLIFT.products.hide();
				$('#navi').load(href+' #navi>*', handleSiteRequest);
				if(pageTracker) pageTracker._trackPageview(href);
			} else {
				var newSite = global.open(href, target);
				newSite.focus();
			}
		};
	
	
	// public methods
	
	return {
		init: init,
		initContent:initContent,
		log: log,
		getLang:getLang,
		loadSite: loadSite
	}
}(window, jQuery));

// Module FLATLIFT.showroom ///////////////////////

MKRAFT.namespace("FLATLIFT.products");
FLATLIFT.products = (function(global, $){
	var baseHref,
		log = MKRAFT.log,
		holder,
		opened = false,
		init = function(){
			baseHref = $('#pLink')[0].href;
			$('#pLink').live("click", toggle);
			
			$('.ekat a').live("click", load);
			if(!$('#prodnavi').length){
				$("#header").append('<div id="prodnavi" style="display:none"></div>');
				load();
			}
			holder = $('#prodnavi');
			opened = holder.css('display')!='none';
			
			initProductImages();
		},
		load = function(href){
			if(typeof href != "string") href = (this.href==undefined)? baseHref : this.href;
			if(href) $("#prodnavi").load(href+" #prodnavi>*", initProductImages);
			return false;
		},
		show = function( href ){
			if(opened) return;
			
			jQuery("#pLink").addClass("hover");
			if(!href) href = baseHref;
			opened = true;
			//holder.stop().animate({display:"block", height:"auto"});//.slideDown();
			//holder.stop(true, true).slideDown();
			//holder.clearQueue().slideDown();
			holder.slideDown();
		},
		hide = function( href ){
			if(!opened) return;
			
			jQuery("#pLink").removeClass("hover");
			opened = false;
			holder.slideUp();
			//holder.stop(true, true).slideUp();
			//holder.stop().animate({ height: "hide" }, { queue: false, complete: function() { $(this).css("height", "auto"); } });
  			//holder.clearQueue().slideUp();
		},
		toggle = function(){
			if(opened) hide();
			else show();
			
			return false;
		},
		initProductImages = function(){
			//	Bildaustausch Produkthumbs
			$('#prodnavi .preview img').hide();
			$('#prodnavi ul li a').bind({
				mouseover: function() {
					var s = $(this).find('.tImg img').attr('src');
					if (s) {
						$('.preview').append('<img src="'+s+'" width="130" height="158">').show();
					}
				},
				mouseout: function() {
					$('.preview img').hide();
				}
			});
		};
		
	return {
		init:init,
		hide:hide,
		show:show
	}
}(window, jQuery));		  

// Module FLATLIFT.showroom ///////////////////////

MKRAFT.namespace("FLATLIFT.showroom");
FLATLIFT.showroom = (function(global, $){
	
	var inited = false,
		open = false,
		minHeight=34,
		maxHeight=371,
		instance,
		interval,
		startTime,
		totalTime,
		aimValue,
		initialValue,
		deltaValue,
		log = MKRAFT.log,
		getTimer = function(){
			return new Date().getTime();
		},
		ease = function(t, b, c, d){
			//return c * ((t = t / d - 1) * t * t + 1) + b;
			if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
			return c / 2 * ((t -= 2) * t * t + 2) + b;
		},
		move = function(){			
			var time = getTimer() - startTime;			
			//if(instance) instance.height = ease(time, initialValue, deltaValue, totalTime);
			//if(instance) 
			if(typeof instance != 'undefined') $(instance).attr("height", ease(time, initialValue, deltaValue, totalTime));
			if(time>=totalTime){
				clearInterval(interval);
				//instance.height = aimValue;
				if(typeof instance != 'undefined') $(instance).attr("height", aimValue);
			}
		},
		animate = function( value, duration ){
			clearInterval(interval);
			
			aimValue = value;
			startTime = getTimer();
			totalTime = duration;
			initialValue = Number($(instance).attr("height"));
			deltaValue = value - initialValue;
			
			interval = setInterval(move, 33);
		};
	
	return {
		init: function(){	// Flasheinbettung
			if(inited) return;
		
			instance = $('#showroom .srflash').flash({
				swf: '/_elements/flash/showroom.swf',
				width:989,
				height: open? maxHeight : minHeight,
				bgcolor: '#08090A',//'#5B686F',
				allowFullScreen: true,
				allowScriptAccess:"always",
				name:"showroomSwf",
				id:"showroomSwf",
				params:{
					allowfullscreen: true,
					allowScriptAccess:"always"
				},
				flashvars: {
					open:open,
					xmlPath:'/_elements/xml/showroom-'+FLATLIFT.getLang()+'.php'
				}
			});
			
			instance = $("#showroomSwf")[0];
			
			this.activateLinks();
			if(instance){
				$('#showroom').css({height:'auto'}).bind('mousewheel', function(event, delta) {
					 return false;
				});
			}
		},
		activateLinks:function(){
			if(instance) $('.akt-show').css({display:'block'});
		},
		toggle:function(value){
			
			if(value===undefined) value = !open;
			if(value===open) return;
			
			open = value;
			
			if(typeof instance != 'undefined'){
				//instance.toggle(open);
				if(value){
					animate(maxHeight, 1000);
				} else {
					animate(minHeight, 1300);
				}
				
				if(instance.toggle) instance.toggle(value);
			}
		},
		goto: function( id ){
			this.toggle(true);
			if(typeof instance != 'undefined'){
				//global.scrollTo(0,0);
				$("body").scrollTo(0,800);
				instance.goto( id );
			}
		},
		getInstance:function(){
			return instance;
		},
		isOpen:function(){
			return open;
		}
	}
	
}(window, jQuery));

// jQuery init //////////////////////////////

jQuery(document).ready(FLATLIFT.init);
