/**
 **************************************************
 * Hettich / hettich.hdlab2.de
 * userfunctions.bn.js
 *
 * @author:HDNET GmbH & Co. KG
 * @version:2.0
 * @updated:2011-04-08 (BN)
 **************************************************
**/

/* BEN: Dirty bugfix for shadowbox issues with domready */
(function() {
	Shadowbox.__isLoaded = false;
	Shadowbox.__onLoad = function() {};
	var load = Shadowbox.load;
	Shadowbox.load = function() {
		load();
		Shadowbox.__isLoaded = true;
		Shadowbox.__onLoad();
	};
	var open = Shadowbox.open;
	Shadowbox.open = function(options) {
		Shadowbox.__isLoaded ? open(options) : Shadowbox.__onLoad = function() { open(options) };
	}
})()
/* :NEB */



$(document).ready(function() {
	
	/* Enable suckerfish for navMain */
	$('#navMain>li').hover(
		function() {
			/* BEN: As we got a transparent png as bg and use opacity as a part of the transition -> All IEs break */
			/* BEN: Using an alternate bg now */
			$('>ul',this).stop(true,true).fadeIn();
			//$('>ul',this).slideDown();
			
			// Enable Cufon only for de & en!
			if ($('html').attr('lang').toLowerCase() == 'de' || $('html').attr('lang').toLowerCase() == 'en') {
				// BEN: As of 2011-01-18 Cufon shall be killed. Degeneration of the visuals step2
				/*Cufon.replace($('>a',this), {
					color:'#333',
					textShadow:'#fff 1px 1px'
				});*/
			}
		}, 
		function() {
			$('>ul',this).stop(true,true).fadeOut();
			//$('>ul',this).slideUp();
			
			// BEN: As of 2011-01-18 Cufon shall be killed. Degeneration of the visuals step2
			//Cufon.refresh('#navMain>li:not(.act)>a');
		} 
	);
	/* Enable hoverClass for IE6 */
	if ($.browser.msie && $.browser.version < 7) {
		$('#navMain>li').hoverClass ('hover');
		$('#navLang>li').hoverClass ('hover');
	}
	
	
	
	/* Newsticker on home */
	// Special positioning
	$('#page.home .columnGroup .column').eq(0).css('position','relative').height($('#page.home .columnGroup').eq(0).height());
	$('#page.home .columnGroup .column').eq(0).find('.news.latest').css({
		position:'absolute',
		bottom:'16px'
	});
	
	// Scrollpane
	$('.scrollPane').jScrollPane({
		verticalGutter:5,
		horizontalGutter:5,
		animateScroll:true,
		animateDuration:500,
		animateEase:'swing'
	});
	$('.scrollPane').hover(function(){
		$(this).find('.jspVerticalBar').stop().css({
			'visibility':'visible',
			'opacity':0
		}).animate({
   			opacity:1
		},500)
	},function(){
		$(this).find('.jspVerticalBar').stop().animate({
   			opacity:0
		},500,function(){
			$(this).css({
				visibility:'hidden',
				opacity:0
			})
		})
	});
	
	
	
	/* Random image on home */
	$('.randomImage').each(function(){
		var count = $(this).find('img').length; //$.log(count);
		var rand = Math.floor(Math.random()*count); //$.log(rand);
		var selected = $(this).find('img').eq(rand); //$.log(selected);
		$(selected).fadeIn(1000);
	});
	
	
	
	// Equalize heights for location records
	$('.ext.contactInformation .locations li').equalizeHeights();
	
	
	
	// Enable Cufon only for de & en!
	if ($('html').attr('lang').toLowerCase() == 'de' || $('html').attr('lang').toLowerCase() == 'en') {
	
		// BEN: As of 2011-01-18 Cufon shall be killed. Degeneration of the visuals step2
		/*
		//Enable Cufon: ul#navMain
		Cufon.replace('#navMain>li:not(.act)>a', {
			color:'#fff',
			textShadow:'#333 1px 1px'
		});
		Cufon.replace('#navMain>li.act>a', {
			textShadow:'#fff 1px 1px'
		});
		Cufon.replace('#navMain>li>ul>li>a', {
			textShadow:'#fff 1px 1px',
			hover:true
		});
		// Enable Cufon: ul#navSub
		Cufon.replace('#navSub a', {
			//textShadow:'#fff 1px 1px'
		});
		// Enable Cufon: h1
		Cufon.replace('h1');
		
		// Enable Cufon: h2
		Cufon.replace('h2');
		
		// Enable Cufon: h3
		Cufon.replace('h3');
		
		// Enable Cufon: Menu of subpages to these pages
		Cufon.replace('ul.page51 li');
		*/
	}
	
	/* BEN: Adust the height of the module-headers if they are different in number of lines */
	/* AH: Added the class "h3.moduleHeader" to the selectors… */
	$('.moduleGroup').each(function() {
		var that = $(this);
		var max = 0;
		if (that.find('h3.moduleFooter, h3.moduleHeader').length > 1) {
			that.find('h3.moduleFooter, h3.moduleHeader').each(function(i) {
				var h = $(this).height();
				if (h > max ) {
					max = h;
					//$.log(max);	
				}		
			});
			that.find('h3.moduleFooter, h3.moduleHeader').each(function() {
				var h = $(this).outerHeight();
				if (h < max ) {
					$(this).height(max-5).css('padding-top','11px');	
				} else {
					$(this).height(max);
				}
			});
		}
		resizeModuleGroup(this);
	});	

	/* Force all modules to the same height */
	/*$('.moduleGroup').each(function() {
		resizeModuleGroup(this);
	});*/
	
	/* Force all list-items in press.detail to the same height */
	$('.press.detail .imageArea li').equalizeHeights();
	
	/* Adjust heights of items in mediaCenter */
	$('.mediaCenter.list .results li').each(function() {
		$(this).find('div.img').css('height',$(this).height());
	});;
	
	/* Accordion */
	if ($('div.accordion').length > 0) {
		var count = $('div.accordion').length;//$.log(count);
		// The last accordion item defines the space to next CEs
		$('div.accordion:last').css('margin-bottom','20px');
		// If just one accordion item is available open it by default
		if (count == 1) {
			$('div.accordion').find('div.linkbox').show();
		}
		else {
			$('div.accordion').each(function() {
				$(this).find('h3.trigger').click(function(e) {
					e.preventDefault();
					if (!$(this).hasClass('act')) {
						$('h3.trigger').removeClass('act');
						$('div.accordion .linkbox').stop(true,true).slideUp();
						$(this).addClass('act').next('div.linkbox').stop(true,true).slideDown();
					}
				});
			});
		}
	}
	
	/* Gallery */
	if ($('div.gallery').length > 0) {
		// If there are previewImages cycle them
		if ($('div.gallery .previewImages').length > 0) {
			// Hide normal gallery
			$('div.gallery ul.images').hide();
			$('div.gallery .previewImages>ul').cycle({
				fx:'fade',
				timeout:5000,
				speed:2500
			});
		// If not show the first image of the gallery
		} else {
			$('div.gallery ul.images li.first').show();
		}
		$('div.gallery div.controls').appendTo('div.columnGroup .column:last').wrap('<div class="gallery" />').find('li').hover(function() {
			$(this).find('.hover').stop(true,true).fadeIn(300);
		},function() {
			$(this).find('.hover').stop(true,true).fadeOut(300);
		}).click(function() {
			// Hide previewImages
			$('div.gallery .previewImages').remove();
			// Show normal gallery
			$('div.gallery ul.images').show();
			var item = $(this).index();
			$('div.gallery ul.images li').each(function(i) {
				//$.log(item+':'+i);
				if (item == i) {
					$(this).stop(true,true).fadeIn(600);
				} else {
					$(this).stop(true,true).fadeOut(600);
				}										
			});
			$(this).siblings().find('.act').hide().end().end().find('.act').show();
		});
	}
	
	/* navLang */
	//$('#navLang li#curLang span').text($('#navLang li.act').text()).parent().find('li.act').remove();
	$('#navLang>li').hover(
		function() {
			/* BEN: As we got a transparent png as bg and use opacity as a part of the transition -> All IEs break */
			/* BEN: Using an alternate bg now */
			$('>ul',this).stop(true,true).fadeIn();
		}, 
		function() {
			$('>ul',this).stop(true,true).fadeOut();
		}
	);
	
	/* Shadowbox */
	Shadowbox.init({
		// BEN: Removing canvas from this list to garantuee Cufon is working properly
		troubleElements:['select','object','embed'],
		skipSetup:true
	});
	
	// BEN: Quickfix for IE6: Take only a.mov
	/*if ($.browser.msie && $.browser.version < 7) {
		Shadowbox.setup('a.mov',{
			autoplayMovies:true,
			width:848,
			height:480,
			flashVars:{'stretching':'none'}
		});		
	} else {*/
		var els = $('a.mov, li.media a, ul.media li.inherit a');
		if (els.length > 0) {
			Shadowbox.setup(els,{
				autoplayMovies:true,
				width:848,
				height:480,
				flashVars:{'stretching':'none','image':'fileadmin/templates/img/jwplayer-preview.jpg'}
			});
		}
	/*}*/
	
	/* Temporary shadowbox teaser on home */
	if ($('a#interzum').length > 0) {
		var lang = $('a#interzum').attr('rel');
		if(lang == 'en' || lang == 'de' || lang == 'es' || lang == 'it') {
			Shadowbox.open({
				content:'<a style="border:0;" href="http://arcitech.hettich.com/index_'+lang+'.html" target="_blank"><img style="width:100%" src="/fileadmin/webspecial/a_'+lang+'.jpg" /></a>',
				player:'html',
				title:'',
				width:800,
				height:600/*,
				options:{
					onFinish: function(el){
						$('#sb-player a').click(function(e){
							Shadowbox.close();	
						})
					}
				}*/
			});				
		} else {
			Shadowbox.open({
				content:'<a style="border:0;" href="http://arcitech.hettich.com/index_en.html" target="_blank"><img style="width:100%" src="/fileadmin/webspecial/a_en.jpg" /></a>',
				player:'html',
				title:'',
				width:800,
				height:600
			});				
		}
		/* Old teaser */
		/*Shadowbox.open({
			content:'fileadmin/content/swfs/interzum.swf',
			player:'swf',
			title:'',
			autoplayMovies:true,
			width:800,
			height:600,
			options:{flashVars:{'language':lang}}
		});*/
	}
	
	/* Leaflet */
	$('div.mediaCenter a.add, div.mediaCenter a.remove, div.mediaCenter a.show').live('click',function(e) {
		e.preventDefault();	
		
		var url = $(this).attr('href');
		// Additional parameter to prevent IEs from caching the request
		var hash = Math.random()*99999;
		
		$('div#leaflet').addClass('loading');
		$.ajax({
			type: 'POST',
			url: url,
			async: true,
			cache: false,
			data: {'rand':hash,'no_cache':1},
			success: function(data) {
				var html = $(data).find('.leaflet').html();
				$('div#leaflet').html(html);
				$('div#leaflet').removeClass('loading');		 
			}
		});
	});
	
	/* Expositions */
	$('table.expositions').each(function() {
		$(this).find('th').each(function(i) {
			switch (i) {
				case 0:
					$(this).css('width',115);
					break;
				case 1:
					$(this).css('width',60);
					break;
				case 2:
					$(this).css('width',100);
					break;
				case 3:
					$(this).css('width',35);
					break;
				case 4:
					$(this).css('width',45);
					break;
				case 5:
					$(this).css('width',80);
					break;
				case 6:
					$(this).css('width',50);
					break;
				case 7:
					$(this).css('width',115);
					break;
				default:
					break;
			}
		});
		$(this).find('tbody tr:odd').css('background-color','#fafafa');
		$(this).find('tbody tr:even').css('background-color','#fefefe');
	});
});

/**
 * Helper functions
**/

// Add a hover-class for IEs
$.fn.hoverClass = function(c) {
	return this.each(function() {
		$(this).hover(
			function() {$(this).addClass(c);},
			function() {$(this).removeClass(c);}
		);
	});
};

// Equalize height on a collction of elements
$.fn.equalizeHeights = function() {
	return this.css('min-height',0).css('min-height',Math.max.apply(this,$(this).map(function(i,e) {return $(e).outerHeight()+1}).get()));
}

// Detect flash
function getFlashVersion() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always'; }
			catch(e) { return '6,0,0'; }
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}
	}
	return '0,0,0';
}
 
/*
var version = getFlashVersion().split(',').shift();
if (version == 0) {
	alert('No flash');
} else if (version < 10) {
	alert('Lower than 10');
}else{
	alert('10 or higher');
}
*/

// Equal height for modules
function resizeModuleGroup(moduleGroupElement) {
	var groupHeight = jQuery(moduleGroupElement).height();
	if (jQuery(moduleGroupElement).children('.module').size() > 1) {
		jQuery(moduleGroupElement).children('.module').each(function() {
			var moduleHeaderHeight = jQuery(this).children('.moduleHeader').outerHeight(true);
			var moduleFooterHeight = jQuery(this).children('.moduleFooter').outerHeight(true);
			var moduleBodyWrapHeight = groupHeight - moduleHeaderHeight - moduleFooterHeight;
			jQuery(this).children('.moduleBodyWrap').height(moduleBodyWrapHeight + 'px');
		});
	}
}

// BEN: Helpful wrapper for logging, prevents IEs from throwing errors
jQuery.log = function(s) {
	if (window.console) {
		console.log(s);
	} else {
		// Only if really needed. It's quite annoying without a console...
		//alert(s);
	}
}
