/*--------------------------------------------------------------
 *	project: Vorwerk, 2010
 *	created: 2010-02-22
 *	last changed: 2011-02-09 Daniel Fitzpatrick
 *	author: Patricia Ross, triplesense
 --------------------------------------------------------------- */

// WICHTIG: jQuery statt jQuery verwenden (wegen Magento)

function initEnhancements(){
	// activate functions
	jQuery.fn.css3workarounds();
	jQuery.fn.tooltipTitle();
	jQuery.fn.zebraTable();
	jQuery.fn.faqToggle();
	jQuery.fn.toggleDetails();
	jQuery.fn.lightbox();
	jQuery.fn.animateImages();
	jQuery.fn.initTabs();
	jQuery.fn.topAnchor();
	jQuery.fn.imagegallery({autostart:true});
	jQuery.fn.registerLightboxRoboter();
	jQuery.fn.disableSubmit();
	
	/* init tengelmann functions and scroll to top */
	if (jQuery('body.tengelmann').length > 0) {
		jQuery.fn.setDomain();
		jQuery.fn.resizeFrame();
		setTimeout('jQuery.fn.resizeFrame()', 500);
		window.top.scrollTo(0,0);
	}

	// activate equal height for teaser with separator
	jQuery('.home .teaser.image-text.thumb-left.no-bg').equalHeight();
	jQuery('.overview .teaser.image-text.thumb-left.no-bg').equalHeight();
	jQuery('.detailpage-subnav .teaser.image-text.thumb-left.no-bg').equalHeight();
	jQuery('.detailpage-tabnav .teaser.image-text.thumb-left.no-bg').equalHeight();
	jQuery('.col-50 .teaser.text-only.no-bg').equalHeight();
	jQuery('.col-33 .teaser.text-only.no-bg').equalHeight();
	jQuery('.col-25 .teaser.text-only.no-bg').equalHeight();	
}

jQuery(document).ready(function() {	
	initEnhancements()
});

/* -------------------------------------------------------------
 *	Disable input button after form submit
 * ------------------------------------------------------------- */
jQuery.fn.disableSubmit = function() {
	$("form").submit(function() {
		var myform = $(this);
		if (myform.attr("submittstate") == "1")
			return false;
		myform.attr("submittstate", "1");
	})
}

jQuery.fn.registerLightboxRoboter = function() {
	if (jQuery('#video-box-robot').length > 0) {
		jQuery('#video-box-robot-late2011 .close').click(function() {
			jQuery('#player').html('');
		});
		jQuery('#exposeMask').live('click', function() {
			jQuery('#player').html('');
		});		
	}
}

jQuery.fn.openYoutubeRoboter = function() {
	// setting the videoEmbedCode manually as JS-variable
	var videoHtml = '';
	videoHtml += '	<object style="height: 390px; width: 640px">';
	videoHtml += '		<param name="movie" value="https://www.youtube.com/v/1x2tTRog2vY?version=3&enablejsapi=1&playerapiid=ytplayer&feature=player_embedded">';
	videoHtml += '		<param name="allowFullScreen" value="true">';
	videoHtml += '		<param name="allowScriptAccess" value="always">';
	videoHtml += '		<embed src="https://www.youtube.com/v/1x2tTRog2vY?version=3&enablejsapi=1&playerapiid=ytplayer&feature=player_embedded" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="360" id="myytplayer">';
	videoHtml += '	</object>';
	jQuery('#player').html(videoHtml);
	jQuery('#anchor-video-box-robot-late2011').trigger("click");
}

jQuery.fn.resizeFrame = function() {
	jQuery("iframe",window.parent.document).attr("height",jQuery("body.tengelmann #content-area").height() + 10);
	jQuery("#slider",window.parent.document).hide();
	jQuery("div#contentframe",window.parent.document).css({"min-height": "0"});
}

jQuery.fn.setDomain = function(){
	/* as described in https://developer.mozilla.org/en/document.domain */
	document.domain = 'vorwerk.com'; /* static - only for tengelmann */
};

/* -------------------------------------------------------------
 *	Scroll to top
 * ------------------------------------------------------------- */
jQuery.fn.topAnchor = function() {
	
	function positionButton() {
		$(".button-top").css({"top": (($(window).height()/2)-($(".button-top").height()/2))});
	}
	positionButton();
	$(window).resize(function() {
		positionButton();
	})
	$('.button-top a').click(function(e){
    e.preventDefault();
    $(this).blur()
    window.scroll(0,0)
  })
}

/* -------------------------------------------------------------
 *	Styling
 * ------------------------------------------------------------- */
// CSS3 Workarounds for IE
jQuery.fn.css3workarounds = function() {
	jQuery('.breadcrumb li:nth-child(2)').addClass('first-link');
	jQuery('h2:first-child').addClass('first');
};

// Zebra-Tables
jQuery.fn.zebraTable = function() {
	jQuery('table').each( function() {
		jQuery(this).find('tbody tr:even').addClass('row-even');
	} );
};

// Equal Height
jQuery.fn.equalHeight = function () {
	var height		= 0;
	var maxHeight	= 0;

	// Store the tallest element's height
	this.each(function () {
		height		= jQuery(this).outerHeight();
		maxHeight	= (height > maxHeight) ? height : maxHeight;
	});

	// Set element's min-height to tallest element's height
	return this.each(function () {
		var t			= jQuery(this);
		var minHeight	= maxHeight - (t.outerHeight() - t.height());
		var property	= jQuery.browser.msie && jQuery.browser.version < 7 ? 'height' : 'min-height';

		t.css(property, minHeight + 'px');
	});

};


/* -------------------------------------------------------------
 *	Tooltip 
 * ------------------------------------------------------------- */
jQuery.fn.tooltipTitle = function() {

	jQuery(".tooltip-title[title]").tooltip({
		effect: 'fade',
		position: "top center",
		offset: [-5, 0]
	});

};


/* -------------------------------------------------------------
 *	Lightboxes/Overlay
 * ------------------------------------------------------------- */
jQuery.fn.lightbox = function() {

	// default Lightbox/Overlay
	jQuery("a[rel]").overlay({
		mask: '#595552', 
		top: 124,
		preload: false,
		fixed: false,
		//for external sites
		onBeforeLoad: function() { 
		 // grab wrapper element inside content 
		 var wrap = this.getOverlay().find(".external-content"); 		 
		 // load the page specified in the trigger 
		 wrap.load(this.getTrigger().attr("href")); 
		}
	});

};

/* -------------------------------------------------------------
 *	Lightboxes/Overlay Service Center
 * ------------------------------------------------------------- */
jQuery.fn.lightboxSCS = function() {
	$("a[rel=#lightboxSCS]").trigger("click");
	jQuery.fn.imagegallerySCS({autostart:true});
}

/* -------------------------------------------------------------
 *	FAQ-Accordion
 * ------------------------------------------------------------- */
jQuery.fn.faqToggle = function() {
	// handle by TYPO3 specialelemnt / udo 05.05.2010
	//jQuery('.faq dt').addClass('inactive');
	//jQuery('.faq dd').hide();
	
	// FAQ-Accordion
	jQuery('.faq dt a').click( function(e) {
		var parent = jQuery(e.target).parent();
		parent.toggleClass('inactive');
        parent.next().toggle();
		return false;
    } );
};

/* -------------------------------------------------------------
 *	General Form-Accordion
 * ------------------------------------------------------------- */
jQuery.fn.toggleDetails = function() {
	if (jQuery(".form-optional").find("div.error").length > 0) {
		$(this).show();
		$(".form-details").toggleClass('inactive');
	} else jQuery(".form-details").next().hide();
	jQuery(".form-details").click(function(e) {
		e.preventDefault();
		$(this).toggleClass('inactive');
		$(this).next().toggle();
	})
}

/* -------------------------------------------------------------
 *	Image Gallery
 * ------------------------------------------------------------- */
jQuery.fn.imagegallery = function(options) {
	if(typeof window.imagegalleries == 'undefined'){
		window.imagegalleries = [];		
	}
	jQuery('.image-gallery').each(function(i,gallery){
		if (!jQuery(gallery).is('.initated') && (jQuery(gallery).parent().parent().attr("id") != "lightboxSCS")) {
			
			// Initially set opacity on thumbs and add
			// additional styling for hover effect on thumbs
			jQuery(gallery).addClass('initated')
			jQuery(gallery).addClass('gallery-'+ i)
			jQuery(gallery).attr('rel', window.imagegalleries.length)
			var newgallery = {gallery: null, markup: jQuery(gallery)}
			window.imagegalleries.push(newgallery)
			
			jQuery(gallery).find('.gallery-content').css('display', 'block');
			var onMouseOutOpacity = 0.6;
			jQuery(gallery).find('.navigation ul.thumbs li').opacityrollover({
				mouseOutOpacity:   onMouseOutOpacity,
				mouseOverOpacity:  1.0,
				fadeSpeed:         'fast',
				exemptionSelector: '.selected'
			});
			
			// Initialize Advanced Galleriffic Gallery
			newgallery.gallery = jQuery(gallery).find('.navigation').galleriffic({
				delay:                     4000,
				numThumbs:                 8,
				preloadAhead:              0,
				enableTopPager:            false,
				enableBottomPager:         true,
				maxPagesToShow:            6,
				imageContainerSel:         '.gallery-'+ i +' .slideshow',
				controlsContainerSel:      '.gallery-'+ i +' .controls',
				captionContainerSel:       '.gallery-'+ i +' .caption-container',
				loadingContainerSel:       '.gallery-'+ i +' .loader',
				renderSSControls:          false, // play/pause
				renderNavControls:         false, // prev/next photo
				playLinkText:              'Play Slideshow',
				pauseLinkText:             'Pause Slideshow',
				prevLinkText:              '&lsaquo;',
				nextLinkText:              '&rsaquo;',
				nextPageLinkText:          '&rsaquo;&rsaquo;',
				prevPageLinkText:          '&lsaquo;&lsaquo;',
				enableHistory:             false,
				enableKeyboardNavigation:  false, // Specifies whether keyboard navigation is enabled
				autoStart:                 options.autostart,
				syncTransitions:           false,
				defaultTransitionDuration: 800,
				onSlideChange:             function(prevIndex, nextIndex) {
					// 'this' refers to the gallery, which is an extension of jQuery('#gallery-thumbs')
					this.find('ul.thumbs').children()
						.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
						.eq(nextIndex).fadeTo('fast', 1.0);
				},
				onPageTransitionOut:       function(callback) {
					this.fadeTo('fast', 0.0, callback);
				},
				onPageTransitionIn:        function() {
					this.fadeTo('fast', 1.0);
				}
			});
		};
	})
	
};

/* -------------------------------------------------------------
 *	Image Gallery Lightbox
 * ------------------------------------------------------------- */
/* replace */
jQuery.fn.imagegallerySCS = function(options) {
	if(typeof window.imagegalleries == 'undefined'){
		window.imagegalleries = [];		
	}
	jQuery('.lightbox .image-gallery').each(function(i,gallery){
		if (!jQuery(gallery).is('.initated')) {
			
			// Initially set opacity on thumbs and add
			// additional styling for hover effect on thumbs
			jQuery(gallery).addClass('initated')
			jQuery(gallery).addClass('gallery-'+ i)
			jQuery(gallery).attr('rel', window.imagegalleries.length)
			var newgallery = {gallery: null, markup: jQuery(gallery)}
			window.imagegalleries.push(newgallery)
			
			jQuery(gallery).find('.gallery-content').css('display', 'block');
			var onMouseOutOpacity = 0.6;
			jQuery(gallery).find('.navigation ul.thumbs li').opacityrollover({
				mouseOutOpacity:   onMouseOutOpacity,
				mouseOverOpacity:  1.0,
				fadeSpeed:         'fast',
				exemptionSelector: '.selected'
			});
			
			// Initialize Advanced Galleriffic Gallery
			newgallery.gallery = jQuery(gallery).find('.navigation').galleriffic({
				delay:                     4000,
				numThumbs:                 8,
				preloadAhead:              0,
				enableTopPager:            false,
				enableBottomPager:         true,
				maxPagesToShow:            6,
				imageContainerSel:         '.gallery-'+ i +' .slideshow',
				controlsContainerSel:      '.gallery-'+ i +' .controls',
				captionContainerSel:       '.gallery-'+ i +' .caption-container',
				loadingContainerSel:       '.gallery-'+ i +' .loader',
				renderSSControls:          false, // play/pause
				renderNavControls:         false, // prev/next photo
				playLinkText:              'Play Slideshow',
				pauseLinkText:             'Pause Slideshow',
				prevLinkText:              '&lsaquo;',
				nextLinkText:              '&rsaquo;',
				nextPageLinkText:          '&rsaquo;&rsaquo;',
				prevPageLinkText:          '&lsaquo;&lsaquo;',
				enableHistory:             false,
				enableKeyboardNavigation:  false, // Specifies whether keyboard navigation is enabled
				autoStart:                 options.autostart,
				syncTransitions:           false,
				defaultTransitionDuration: 800,
				onSlideChange:             function(prevIndex, nextIndex) {
					// 'this' refers to the gallery, which is an extension of jQuery('#gallery-thumbs')
					this.find('ul.thumbs').children()
						.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
						.eq(nextIndex).fadeTo('fast', 1.0);
				},
				onPageTransitionOut:       function(callback) {
					this.fadeTo('fast', 0.0, callback);
				},
				onPageTransitionIn:        function() {
					this.fadeTo('fast', 1.0);
				}
			});
		}
		
	})
	
};


/* -------------------------------------------------------------
 *	Horizontal Slider (FAQ)
 * ------------------------------------------------------------- */
// Horizontal Slider that shows dynamic FAQ content below the slider on Click 
jQuery.fn.horizontalslider = function() {

	// Alle vorhandenen Scroller sonderbehandeln
	handlescrollerhorizontal("#faqslider");
	
	/* -------------------------- FAQ -------------------------- */
	// get "product-*"-classname of one item and show corresponding div 
	showQuestions = function(selector) {
		var faqid = "."+jQuery(selector).attr("class").match(/product-\w*/)[0];
		if (jQuery(faqid).length>0) {
			jQuery(".faq-questions").hide();
			jQuery(faqid).fadeIn();
		}
		return false;		
	};
	// show faq questions of initially activated item (pageload)
	showQuestions(jQuery(".horizontal-slider .active"));
	// show faq questions of a clicked item
	jQuery(".horizontal-slider .item").click(function() {
        jQuery('.horizontal-slider .item').removeClass("active");
        jQuery(this).addClass("active");
		showQuestions(this);
	});

};

// Alle Scroller so umblättern, das sie den aktuell aktivierten (geklickten) Wert anzeigen 
function handlescrollerhorizontal(scroller_select) {
	
	jQuery(scroller_select).scrollable({
		keyboard: false,
		circular: false
	});
	
	if(myscrollerhorizontal = jQuery(scroller_select).data("scrollable")) {
		var pagenum=0;
		jQuery('.horizontal-slider .page').each(function(c1, pagediv) {
			jQuery.each(pagediv.children, function(c2, itemdiv) {
				var found = itemdiv.className.search(/active/);
				if(found != -1) {
					pagenum=c1;
				}  	  
			});
		});
		myscrollerhorizontal.move(pagenum, 0);
	}
  
};

/* -------------------------------------------------------------
 * Generic Horizontal Slider with dynamic Content
 * -------------------------------------------------------------
 * @param {String} slider_id	CSS ID of the slider div
 * @param (String) item_class	CSS classname of each slider item
 * @param (String) items_div	CSS classname pattern to match with item detail div
 * @param (String) items_div	CSS classname of each slider item detail div
 * @param (String) customfunc	(optional) custom function to be applied after each slider switch
 */
// Generic Horizontal Slider that shows dynamic content below the slider on Click
jQuery.fn.horizontalslider_dynamiccontent = function(slider_id, item_class, items_div, customfunc) {
	
	// Alle vorhandenen Scroller sonderbehandeln
	handlescrollerhorizontal(slider_id);
	
	var sliderobj = jQuery(slider_id);

	/* -------------------------- Items -------------------------- */
	// get classname of one item and show corresponding items div 
	showItems = function(selector) {

		var item_class_regex = new RegExp(item_class+'\\w*');
		var item_id = "."+jQuery(selector).attr("class").match(item_class_regex)[0];

		/* store active item class via data() */
		sliderobj.data('active_class',item_id);
		
		if (jQuery(item_id).length>0) {
			/* After hiding the items div... */
			jQuery(items_div).hide();
			/* Apply custom function */
			if (jQuery.isFunction(customfunc)) { customfunc(); }
			/* And show it */
			jQuery(item_id).fadeIn();
		}
		return false;
	};

	// show item-content of initially activated item (pageload)
	showItems(jQuery(".horizontal-slider .active"), item_class, items_div);
	// show item-content of a clicked item
	jQuery(".horizontal-slider .item").click(function() {
        jQuery('.horizontal-slider .item').removeClass("active");
        jQuery(this).addClass("active");
		showItems(this);
	});
	
};

/* -------------------------------------------------------------
 * Generic Horizontal Slider with dynamic Content per AJAX
 * -------------------------------------------------------------
 * @param {String} slider_id	CSS ID of the slider div
 * @param (String) item_class	CSS classname of each slider item
 * @param (String) items_div	CSS classname pattern to match with item detail div
 * @param (String) items_div	CSS classname of each slider item detail div
 * @param (String) customfunc	(optional) custom function to be applied after each slider switch
 */
// Generic Horizontal Slider that shows dynamic content below the slider on Click
jQuery.fn.horizontalslider_dynamiccontent_ajax = function(slider_id, item_class, items_div, customfunc) {
	
	// Alle vorhandenen Scroller sonderbehandeln
	handlescrollerhorizontal(slider_id);
	
	var sliderobj = jQuery(slider_id);

	/* -------------------------- Items -------------------------- */
	// get classname of one item and show corresponding items div 
	showItems = function(selector) {

		var item_class_regex = new RegExp(item_class+'\\w*');
		var item = "."+jQuery(selector).attr("class").match(item_class_regex)[0];
		var string_id_ajax = jQuery(selector).attr("class").match(item_class_regex)[0];
		var item_ajax = string_id_ajax.substr(1,2);
		
		/* store active item class via data() */
		sliderobj.data('active_class',item);
		
		if (jQuery(item).length > 0) {
			
			/* Apply custom function */
			if (jQuery.isFunction(customfunc)) { customfunc(); }
			
			/* Load and show it */
			jQuery.get(array_face[item_ajax], function(text){
				var matches = text.match(/<!-- inner-content-start -->([\s\S]*?)<!-- inner-content-end -->/gi);
				//alert(matches[0]);
				if(matches[0])
					jQuery(".face-details").html(matches[0]);
			});
		}
		return false;
	};

	// show item-content of initially activated item (pageload)
	showItems(jQuery(".horizontal-slider .active"), item_class, items_div);
	// show item-content of a clicked item
	jQuery(".horizontal-slider .item").click(function() {
		jQuery('.horizontal-slider .item').removeClass("active");
		jQuery(this).addClass("active");
		showItems(this);
	});
	
};

/* -------------------------------------------------------------
 *	Vorwerk Worldwide: Functions to handle brands and countries
 * ------------------------------------------------------------- */
jQuery.fn.handleBrandCountries = function() {
	

	/* Shows/hides a country group (consisting of countries) depending on the number of visible country items */
	function toggleCountryGroup(display,activeclass) {
		jQuery('.countries'+activeclass).each(function() {
			jQuery(this).find('.country-group').each(function() {
				var $countrygroup = $(this);
				var count_visible_items	= $countrygroup.find('li:visible').length;
				/* console.log(count_visible_items); */
				if (display == 'hide') {
					/* console.log($countrygroup); */
					if (count_visible_items == 0) {
						$countrygroup.slideUp();
					}
				} else {
					$countrygroup.slideDown();
				}
			});
		});
	}
	
	/* Shows/hides address items within all lightboxes based on filter (company|distributor) */
	function toggleLightboxAdresses(display,itemclass) {
		var address_item = jQuery('.worldwide .lightbox .address.'+itemclass);
		if (display == 'hide') {
			address_item.hide();
		} else {
			address_item.show();
		}
	}
	
	jQuery('.filter input:checkbox').click(function() {
		var $this = jQuery(this);
		var radio_checked = $this.is(':checked');

		/* prevent unchecking both checkboxes */
		if (jQuery('.filter input:checkbox').not(':checked').length == 2) { return false; }

		var activeclass = jQuery('#brandslider').data('active_class'); /* .brand-1 etc. */

		/* console.log(jQuery('.countries'+activeclass+' .country-group ul li.'+$this.attr('class'))); */
		
		items = jQuery('.countries'+activeclass+' .country-group ul li').filter(function(index) {
			/* only grab items that contain 1 class-value (company|distributor)  */
			/* console.log('classname='+this.className); */
			var regex = new RegExp($this.attr('class'));
			if (this.className.match($this.attr('class'))) {
				/* console.log(this.className.match(regex)); */
				if (this.className.split(" ").length == 1) {
					return true;
				}
			} else { return false; }
		});
		
		/* console.log(items); */
		
		if (items.length>0) {
			if (radio_checked) {
				items.fadeIn(function() {
					toggleCountryGroup('show',activeclass);
					toggleLightboxAdresses('show',$this.attr('class'));
				});
			} else {
				items.fadeOut(function() {
					toggleCountryGroup('hide',activeclass);
					toggleLightboxAdresses('hide',$this.attr('class'));
				});
			}
		}
	});

}



/* -------------------------------------------------------------
 *	Vertical Slider
 * ------------------------------------------------------------- */
jQuery.fn.verticalslider = function() {

	// Alle vorhandenen Scroller sonderbehandeln
	handlescrollervertical("#tabnavslider");
	
	// link to href of h4
	jQuery('.vertical-slider .item').click(function() {
        jQuery('.vertical-slider .item').removeClass("active");
        jQuery(this).addClass("active");
		location.href = jQuery('h4 a',this).attr("href");
		return false;
	});

};

// Alle Scroller so umblättern, das sie den aktuell aktivierten (geklickten) Wert anzeigen 
function handlescrollervertical(scrollervertical_select) {
	
	jQuery(scrollervertical_select).scrollable({
		keyboard: false,
		vertical: true,
		circular: false
	});
	
	if(myscrollervertical = jQuery(scrollervertical_select).data("scrollable")) {
		var pagenum=0;
		jQuery('.vertical-slider .page').each(function(c1, pagediv) {
			jQuery.each(pagediv.children, function(c2, itemdiv) {
			var found = itemdiv.className.search(/active/);
				if(found != -1) {
					pagenum=c1;
				}  	  
			});
		});
		myscrollervertical.move(pagenum, 0);
	}
  
};


/* -------------------------------------------------------------
 *	Scrollable Content
 * ------------------------------------------------------------- */
// Horizontal Slider that does not show any content below the Slider on Click
jQuery.fn.horizontalslider_noextracontent = function() {

	jQuery(".horizontal-content-slider").scrollable({
		keyboard: false,
		circular: false
	});

};


/* -------------------------------------------------------------
 *	Javascript IMG
 * ------------------------------------------------------------- */
var error="Das Copyright diese Bildes liegt bei Vorwerk. Bitte lesen Sie unseren Copyright-Hinweis im Impressum."
function disableclick(e) {
if (document.all) {
  if (event.button==2||event.button==3) {
      if (event.srcElement.tagName=="IMG"){
      alert(error);
      return false;
      }
  }
}
else if (document.layers) {
    if (e.which == 3) {
    alert(clickmessage);
    return false;
    }
}
else if (document.getElementById){
    if (e.which==3&&e.target.tagName=="IMG"){
    alert(error)
    return false
    }
  }
}

function disqualify(){
  for(i=0;i<document.images.length;i++){
    document.images[i].onmousedown=disableclick;
  }
}

if (document.all){
document.onmousedown=disableclick
}
else if (document.getElementById){
document.onmouseup=disableclick
}
else if (document.layers){
  //disqualify()
}

/* Image animation */
function loopThroughImages(options){
	var imagecontainer = options.container;

	if(!imagecontainer.is('.animating')){	
		imagecontainer.addClass('animating')
		imagecontainer.attr('rel', options.count)
		
		var firstimage = imagecontainer.find('img')[0]
//		var speed = 900/imagecontainer.find('img').length;
		var speed = 100;
		function showPreviousImg(currImg){
			$(currImg).fadeIn(0).delay(speed).fadeOut(0,function(){
				if($(currImg).prev('img').length>0){			
					showPreviousImg($(currImg).prev('img'))
				}else{
					imagecontainer.attr('rel', parseInt(imagecontainer.attr('rel'))-1)
					if(imagecontainer.is('.mouseover') && parseInt(imagecontainer.attr('rel'))==0){
						imagecontainer.attr('rel', 1)
					} 
					if(parseInt(imagecontainer.attr('rel'))==0){
						$(currImg).fadeIn(0)
						imagecontainer.removeClass('animating')	
					}else{
						showNextImg($(currImg).next('img'))
					}
				}
		   })
		}
		
		function showNextImg(currImg){
			$(currImg).fadeIn(0).delay(speed).fadeOut(0,function(){
				if($(currImg).next('img').length>0){			
					showNextImg($(currImg).next('img'))
				}else{
					showPreviousImg($(currImg).prev('img'))
				}
		   })					
		}
		showNextImg(firstimage)
	}
}

jQuery.fn.animateImages = function() {
	$('.images.animated').each(function(i,presentation){
			
			var p = $(presentation)
			var pimgs = $(presentation).find('img');
			var loopindex = 0;
			var iteration = 0;
			var maxiterations =20;
			var initialanimation = true;
			var initialanimations = 3;
			var initialanimationCount = 0;
			
			if(!p.is('.initiated')){
				p.addClass('initiated')
				loopThroughImages({
					container: p,
					count: 3
				})
			}
			p.mouseenter(function(){
				p.addClass('mouseover')
				loopThroughImages({
					container: p,
					count: 1
				})
			})
			p.mouseleave(function(){
				p.removeClass('mouseover')
			})
		})
}

function open_url(url, opt){
	if (opt == 0) {// current window
		window.location.href  = url;
		return false;
	}else if (opt == 1){ // new window
		window.open(url);
		return false;
	}
}

function localface_overview_pager(page) {
	
	var position_bg_0 = 0;
	var position_bg_1 = 0;
	var position_bg_2 = 0;
	var position_bg_3 = 0;
	var position_bg_4 = 0;
	
	switch(page) {
		
		case 0:		jQuery("#button-0").css({ backgroundPosition: "-23px 0px" });
					jQuery("#button-1").css({ backgroundPosition: "0px 0px" });
					jQuery("#button-2").css({ backgroundPosition: "0px 0px" });
					
					position_bg_0 = 0;
					position_bg_1 = 0;
					position_bg_2 = 0;
					position_bg_3 = 0;
					position_bg_4 = 0;
					
					jQuery("#localface-hover-face-0 h2").html(array_faces[0]["name"]);
					jQuery("#localface-hover-face-0 h3").html(array_faces[0]["text"]);
					jQuery("#localface-hover-face-0 .button-lookalike a").attr({'href' : array_faces[0]["link"]});
					
					jQuery("#localface-hover-face-1 h2").html(array_faces[1]["name"]);
					jQuery("#localface-hover-face-1 h3").html(array_faces[1]["text"]);
					jQuery("#localface-hover-face-1 .button-lookalike a").attr({'href' : array_faces[1]["link"]});
					
					jQuery("#localface-hover-face-2 h2").html(array_faces[2]["name"]);
					jQuery("#localface-hover-face-2 h3").html(array_faces[2]["text"]);
					jQuery("#localface-hover-face-2 .button-lookalike a").attr({'href' : array_faces[2]["link"]});
					
					jQuery("#localface-hover-face-3 h2").html(array_faces[3]["name"]);
					jQuery("#localface-hover-face-3 h3").html(array_faces[3]["text"]);
					jQuery("#localface-hover-face-3 .button-lookalike a").attr({'href' : array_faces[3]["link"]});
					
					jQuery("#localface-hover-face-4 h2").html(array_faces[4]["name"]);
					jQuery("#localface-hover-face-4 h3").html(array_faces[4]["text"]);
					jQuery("#localface-hover-face-4 .button-lookalike a").attr({'href' : array_faces[4]["link"]});
					
					break;
				
		case 1:		jQuery("#button-0").css({ backgroundPosition: "0px 0px" });
					jQuery("#button-1").css({ backgroundPosition: "-23px 0px" });
					jQuery("#button-2").css({ backgroundPosition: "0px 0px" });
					
					position_bg_0 = -570;
					position_bg_1 = -376;
					position_bg_2 = -283;
					position_bg_3 = -283;
					position_bg_4 = -376;
					
					jQuery("#localface-hover-face-0 h2").html(array_faces[5]["name"]);
					jQuery("#localface-hover-face-0 h3").html(array_faces[5]["text"]);
					jQuery("#localface-hover-face-0 .button-lookalike a").attr({'href' : array_faces[5]["link"]});
					
					jQuery("#localface-hover-face-1 h2").html(array_faces[6]["name"]);
					jQuery("#localface-hover-face-1 h3").html(array_faces[6]["text"]);
					jQuery("#localface-hover-face-1 .button-lookalike a").attr({'href' : array_faces[6]["link"]});
					
					jQuery("#localface-hover-face-2 h2").html(array_faces[7]["name"]);
					jQuery("#localface-hover-face-2 h3").html(array_faces[7]["text"]);
					jQuery("#localface-hover-face-2 .button-lookalike a").attr({'href' : array_faces[7]["link"]});
					
					jQuery("#localface-hover-face-3 h2").html(array_faces[8]["name"]);
					jQuery("#localface-hover-face-3 h3").html(array_faces[8]["text"]);
					jQuery("#localface-hover-face-3 .button-lookalike a").attr({'href' : array_faces[8]["link"]});
					
					jQuery("#localface-hover-face-4 h2").html(array_faces[9]["name"]);
					jQuery("#localface-hover-face-4 h3").html(array_faces[9]["text"]);
					jQuery("#localface-hover-face-4 .button-lookalike a").attr({'href' : array_faces[9]["link"]});
					
					break;
				
		case 2:		jQuery("#button-0").css({ backgroundPosition: "0px 0px" });
					jQuery("#button-1").css({ backgroundPosition: "0px 0px" });
					jQuery("#button-2").css({ backgroundPosition: "-23px 0px" });
					
					position_bg_0 = -1139;
					position_bg_1 = -752;
					position_bg_2 = -565;
					position_bg_3 = -565;
					position_bg_4 = -752;
					
					jQuery("#localface-hover-face-0 h2").html(array_faces[10]["name"]);
					jQuery("#localface-hover-face-0 h3").html(array_faces[10]["text"]);
					jQuery("#localface-hover-face-0 .button-lookalike a").attr({'href' : array_faces[10]["link"]});
					
					jQuery("#localface-hover-face-1 h2").html(array_faces[11]["name"]);
					jQuery("#localface-hover-face-1 h3").html(array_faces[11]["text"]);
					jQuery("#localface-hover-face-1 .button-lookalike a").attr({'href' : array_faces[11]["link"]});
					
					jQuery("#localface-hover-face-2 h2").html(array_faces[12]["name"]);
					jQuery("#localface-hover-face-2 h3").html(array_faces[12]["text"]);
					jQuery("#localface-hover-face-2 .button-lookalike a").attr({'href' : array_faces[12]["link"]});
					
					jQuery("#localface-hover-face-3 h2").html(array_faces[13]["name"]);
					jQuery("#localface-hover-face-3 h3").html(array_faces[13]["text"]);
					jQuery("#localface-hover-face-3 .button-lookalike a").attr({'href' : array_faces[13]["link"]});
					
					jQuery("#localface-hover-face-4 h2").html(array_faces[14]["name"]);
					jQuery("#localface-hover-face-4 h3").html(array_faces[14]["text"]);
					jQuery("#localface-hover-face-4 .button-lookalike a").attr({'href' : array_faces[14]["link"]});
					
					break;
	}
	
	jQuery("#localface-overview-face-0").animate({
		backgroundPosition: position_bg_0
	}, 1200);
	jQuery("#localface-overview-face-1").animate({
		backgroundPosition: position_bg_1
	}, 1200, function() {});
	jQuery("#localface-overview-face-2").animate({
		backgroundPosition: position_bg_2
	}, 1200, function() {});
	jQuery("#localface-overview-face-3").animate({
		backgroundPosition: position_bg_3
	}, 1200, function() {});
	jQuery("#localface-overview-face-4").animate({
		backgroundPosition: position_bg_4
	}, 1200, function() {});
}

jQuery.fn.localface_overview = function(canvas_class) {
	/* addendum: 09.02.2011 DFi binding to apply the button link to the entire container-div with the class "click-link" */
	jQuery(".click-link").click(function(){
		self.location.href = $(this).find('p.button-lookalike a').attr('href');
	});
	
	jQuery("." + canvas_class).each(function(c1, canvasdiv) {
		jQuery.each(canvasdiv.children, function(c2, itemdiv) {
			
			jQuery("#localface-overview-face-" + c2).mouseover(
				function () {
					jQuery("#localface-hover-face-" + c2).addClass('localface-hover-active');
				}
			);
			jQuery("#localface-overview-face-" + c2).mouseout(
				function () {
					jQuery("#localface-hover-face-" + c2).removeClass('localface-hover-active');
				}
			);
		});
	});
	localface_overview_pager(0);
	jQuery('.localface-overview-buttons span').each(function(i, b) {
		jQuery("#button-" + i).click(function() { localface_overview_pager(i); });
	});
};

/* tab dynamic enhancements */
jQuery.fn.initTabs = function() {
/*
	var curcontent= $('.content .inner-content').html();
	$('.content .inner-content').append(jQuery('<div class="stacked-content" rel="mega-tabs"><div class="stack ready initial active">'+  curcontent +'</div>'))
	$('.stacked-content').find('.initial').find('.product-presentation .images').removeClass('initiated').removeClass('animating')
	$('.stacked-content').find('.mega-tabs').remove()
	jQuery.fn.animateImages();
	jQuery.fn.imagegallery({autostart:true});
	$('.content .inner-content').children().each(function(i,el){
		if(!$(el).is('.stacked-content')){
			if($(el).find('.mega-tabs').length==0){
				$(el).remove()
			}
		}
	})

	jQuery('.mega-tabs a').each(function(i, tab){
		jQuery(tab).attr('rel',i)
		jQuery(tab).attr('rel',i)
		if(jQuery(tab).parents('li').is('.active')){
			jQuery(tab).addClass('initial')
			jQuery('.stacked-content').find('.initial').attr('rel',i)
		}else{
			jQuery('.stacked-content').append(jQuery('<div class="stack" rel="'+ i +'"></div>'))	
		}
		
		jQuery(tab).click(function(event){
								   
			event.preventDefault();
			var curtab = jQuery(this)
			jQuery('.mega-tabs li').removeClass('active')
			curtab.parents('li').addClass('active')
			
			var stacks = jQuery('.stacked-content');										  
			var stackcontainer = stacks.find('.stack[rel='+ curtab.attr('rel') +']');
			if(!stackcontainer.is('.ready')){
				stackcontainer.addClass('loading');
				jQuery.get(curtab.attr('href'), function(data) {
					stackcontainer.append(jQuery(data).find('.inner-content').children());
					stackcontainer.find('.mega-tabs').remove();
					jQuery.fn.animateImages();
					jQuery.fn.imagegallery({autostart:false});
 					stackcontainer.removeClass('loading');					
					stackcontainer.addClass('ready')
				});
			}
			
			stacks.find('.stack.active').removeClass('active');
			stackcontainer.addClass('active')
		})						  
	})
	
	jQuery('.mega-tabs a').each(function(i, tab){
		var curtab = jQuery(tab)
		var stacks = jQuery('.stacked-content');										  
		var stackcontainer = stacks.find('.stack[rel='+ curtab.attr('rel') +']');
		
		if(!stackcontainer.is('.ready')){	
			stackcontainer.addClass('loading');
			jQuery.get(curtab.attr('href'), function(data) {
					stackcontainer.append(jQuery(data).find('.inner-content').children());
					stackcontainer.find('.mega-tabs').remove();
					jQuery.fn.animateImages();
					jQuery.fn.imagegallery({autostart:false});
					stackcontainer.removeClass('loading');
					stackcontainer.addClass('ready')
			});
		}
	})
 */
}



