(function(document,$) {
	$(document).ready(function() {
		// Print Preview Mode
		$('.print').previewprint();
	});
})(document, jQuery);


function OpenWin(theURL,winName,features) {
win = window.open(theURL,winName,features);
if(win!=null)win.focus();
}

jQuery(document).ready(function() {
	if (jQuery('.productCarousel').length) {
        jQuery(".productCarousel").each(function () {
            setHeights(".productCarouselSlides", ".productCarouselSlideItem ");
            if (jQuery(this).find("li").length > 4) {
                jQuery(this).find(".productCarouselSlides").jcarousel({
                    wrap: 'circular',
                    scroll: 4
                });
            }
            else {
                jQuery(this).css("margin", "0 0 20px 17px")
            }
        }); 
	}
 });



jQuery(document).ready(function(){
// show portal navigation
if (jQuery('#portalSites').length) {
jQuery('#portalSites').click(function(e){
	e.preventDefault();
	jQuery('.portalNavigationList').slideToggle('fast');
	jQuery(this).toggleClass('on');
});
}
	
// toggle masterHeaderNavigation
if (jQuery('#otherSites').length) {
jQuery('#otherSites').click(function(event){
	event.preventDefault();
	jQuery('.masterHeaderNavigation .masterHeaderWrapper').toggle();
	jQuery('.masterHeaderNavigation').toggleClass('masterHeaderNavigationHeight');
	jQuery(this).toggleClass('hover');
});
}

// toggle submenu
var configSubMenu = {    
	over: function () { 
		jQuery(this).find('.ico').clearQueue().animate({
			height: 24
		}, 'fast', function() {
			jQuery(this).parents('.submenu').find('a.submenuItem').addClass('open');
			jQuery(this).parents('.submenu').find('ul').animate({
				height: 'toggle'
			}, 'slow', function() {
			// Animation complete.
			});
		// Animation complete.
		});
	}, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: function(){
		jQuery(this).find('ul').clearQueue().animate({
			height: 'toggle'
		}, 'fast', function() {
			jQuery(this).parent().find('a.submenuItem').removeClass('open');
			jQuery(this).parent().find('a.submenuItem .ico').animate({
			height: 18
			}, 'fast', function() {
			// Animation complete.
			});
		// Animation complete.
		});
	} // function = onMouseOut callback (REQUIRED)    
};
jQuery(".submenu").hoverIntent(configSubMenu);

// show all online store @ homepage
if (jQuery('.showAllOnlineStores').length) { 
jQuery('.showAllOnlineStores a').click(function(e){
	e.preventDefault();
	jQuery('.storesOnlineExtra').slideToggle();
	jQuery(this).toggleClass('hover');
});
}

// ticker homepage
if (jQuery('#ticker').length) {
	jQuery('#ticker ul').cycle({
		fx: 'scrollUp', timeout: 5000, speed: 500, pause: true 
	});
}

// tabs homepage
if (jQuery('#productstabwindow').length) {
	jQuery('#productstabwindow').tabs();
}

// scrollbar slider homepage
if (jQuery('#scrollbar1').length) {
	jQuery('#scrollbar1').tinyscrollbar();
}

// clear default value input and textarea
//init(); ??????????????
	
// clear value submit for minor browsers
jQuery('.ie7 .header .search input.submit').val('');
jQuery('.ie6 .header .search input.submit').val('');
	
// send recipe to a friend
if (jQuery('a.mgm').length) {
jQuery('a.mgm').fancybox({
	'centerOnScroll':true,
	'hideOnOverlayClick':false,
	'showCloseButton':false
});
}
	
// tabs
if (jQuery('.tabbing').length) {
	jQuery('.tabbing').tabs();
	var today = new Date();
	jQuery('#weekmenu').tabs({selected:(today.getDay()-1)});
	jQuery('.storeHours table tr th#'+(today.getDay()-1)).parent().addClass('active');
}	
// filter search
if (jQuery('#filterResult').length) {
	jQuery('#filterResult .formLabel').click(function(){
		jQuery(this).parent().toggleClass('formFieldClosed');
	});
	jQuery('#filterResult .more').click(function(e){
		e.preventDefault();
		jQuery(this).parent().find('.more').hide();
		jQuery(this).parent().find('.less').show();
		jQuery(this).parent().find('.moreFilterResultValues').show();
	});
	jQuery('#filterResult .less').click(function(e){
		e.preventDefault();
		jQuery(this).parent().find('.less').hide();
		jQuery(this).parent().find('.more').show();
		jQuery(this).parent().find('.moreFilterResultValues').hide();
	});
}
// show more or less video formats
if (jQuery('.gallery').length) {
jQuery('.gallery .more').click(function(e){
	e.preventDefault();
	jQuery(this).parent().find('.more').hide();
	jQuery(this).parent().find('.less').show();
	jQuery(this).parent().find('.download li').show();
	//var h = jQuery(this).parent().height();
	jQuery(this).parent().height('auto');
});
jQuery('.gallery .less').click(function(e){
	e.preventDefault();
	jQuery(this).parent().find('.less').hide();
	jQuery(this).parent().find('.more').show();
	jQuery(this).parent().find('li.noDefault').hide();
	//jQuery(this).parent().height(h);
});
}

// media library vertical alignment images support IE7
jQuery('.ie7 .gallery ol li a img').each(function(index, element) {
	jQuery(this).css('margin-top',((jQuery(this).parent().height() - jQuery(this).height()) / 2)+'px');
});
	
// fancybox media
if (jQuery('a.gallery').length) {
jQuery('a.gallery').fancybox();
}
if (jQuery('a.movie').length) {
jQuery('a.movie').fancybox();
}
		
	// bookmarks / anchors
	setHeightAnchors();
	
	// foodPyramid
	if(jQuery('.foodPyramid').length > 0){
		foodPyramid();
	}
	
// style input type file
if (jQuery('input.inputUpload').length) {
jQuery("input.inputUpload").filestyle({ 
	image: "assets/img/btns/btn-browse.gif",
	imageheight : 26,
	imagewidth : 78,
	width : 270
});
}

// counting and limiting characters in textareas
if (jQuery('.textareaItem textarea').length) {
jQuery('.textareaItem textarea').keyup(function(){
	var maximum = parseInt(jQuery(this).attr('maxlength'));
	var amount = jQuery(this).val().length
	if(amount <= maximum){
		var formItem = jQuery(this).parent().parent();
		formItem.find('.formDesc p span').html((maximum - amount));
		if (amount == maximum) {
			formItem.find('.formDesc').addClass('formError');
		} else {
			formItem.find('.formDesc').removeClass('formError');
		}
		
	} else {
		jQuery(this).val(jQuery(this).val().substring(0,maximum));
		}
});
}
	
	if (jQuery('#sortbox').length) {
	jQuery('#sortbox').change(function(){  
	  var optionSelectedValue = $('#sortbox option:selected').val();  
	  top.location.href = optionSelectedValue;
    });
	}


	setHeights('.contentWidget', '.cell', '.contentWidget .cell');
	setHeights('.listBlocks ol', 'h2');
	setHeights('.listBlocks ol', 'h3');
    setHeights('.listBlocks ol', 'p.setHghtLst');
	setHeights('.universeWidget ol', 'h3');
	setHeights('.gallery', '.listBlock');
	setHeights('.doormatblocks', 'h2');
	setHeights('.doormatblocks', 'h3');
	setHeights('.doormatblocks', '.doormatBlock','.doormatblocks .cell .doormatBlock');
	setHeights('.sponsorMecenaatHighlights', 'h3');
	setHeights('.sponsorMecenaatHighlights', '.doormatBlock');
	setHeights('#articlesTeasers', '.artTeaserSmallContent', '#articlesTeasers .artTeaserSmallContent');
	setHeights('.equalHeightBoxes', 'h3');
	setHeights('.equalHeightBoxes', '.cell', '.popularThemeHighlighted .equalHeightBoxes .cell');
	setHeights('.productCarouselSlides', '.productCarouselSlideItem');
    setHeights('.nwsltrChecks', '.formItem');
    setHeights('.recipe .related', '.doosjes');
	
	if (jQuery('.lnkToUrl').length) {
	jQuery('.lnkToUrl').click(function(){
		var lnk = jQuery(this).data('url');
		goToLoc(lnk);
	});
	}
	
	if (jQuery('#storeLocator').length) {
	jQuery('#storeLocator').find('.controlsMoreOptions .lnk a').click(function(e){
		e.preventDefault();
		jQuery(this).parent().hide();
		if (!jQuery(this).parent().hasClass('less')){
			jQuery('.controlsMoreOptions .less').show();
			jQuery('#storeLocator').find('.moreSearchOptions').show();
			jQuery('#storeLocator').find('.storeLocatorMap').show();
			jQuery(jQuery('#map_canvas').gmap('get', 'map')).triggerEvent('resize');
			jQuery('#map_canvas').gmap('get', 'MarkerClusterer').fitMapToMarkers();
		}
		else {
			jQuery('.controlsMoreOptions .more').show();
			jQuery('#storeLocator').find('.moreSearchOptions').hide();
			jQuery('#storeLocator').find('.storeLocatorMap').hide();
		}
	})
	}
	
	if (jQuery('.inspirationCarouselImages').length) {
	jQuery('.inspirationCarouselImages').cycle({
		fx:      'scrollHorz',
		timeout:  4000,
		pauseOnPagerHover: true,
		pager: '.inspirationCarouselPager',
		pagerAnchorBuilder: function(idx, slide) { 
       	 return '<li><a href="#">&bull;</a></li>'; 
    	} 
	});
	}

});

function goToLoc(loc){
	window.location = loc;
}
	function callback(e) {
			setTimeout(function() {
				jQuery(e).removeClass('hover');
			}, 1500 );
		}


function setHeights(containerElement, elementTag, callback){
	var maximumHeight = 0;
	jQuery(containerElement).each(function(){
		var elements = jQuery(this).find(elementTag).toArray();
		//alert(elements);
		var heights = [];
		for (var i = 0; i < jQuery(elements).length; i++) {
        	heights.push(jQuery(elements[i]).height());
			var realHeight = heights[i];
			if(realHeight > maximumHeight){
				maximumHeight = heights[i];
			}
    	}
		jQuery(this).find(elementTag).height(maximumHeight);
		maximumHeight = 0;
	});
	setPositioned(callback);
}

function setPositioned(e) {
	jQuery(e).addClass('positioned');
	}


function setHeightAnchors(){
	if (jQuery('.anchors').length) {
	jQuery('.anchors').each(function(){
        var items = jQuery(this).find('li a .lnk');
		if(jQuery(this).find('img').size()==0){
			var h = 0;
			if(items.length > 0) {
				for (i = 0; i < items.length; i++){
					if(items.eq(i).height() > h){
						h = items.eq(i).height();
						}
					}
				jQuery(this).find('li a .lnk').height(h);
				jQuery(this).addClass('positioned');
			}
		}
    });
	}
	jQuery('.ie7 .anchors li a span.ico').append('<img src="assets/img/icons/arrow-anchor.png" />')
	jQuery('.ie6 .anchors li a span.ico').append('<img src="assets/img/icons/arrow-anchor.png" />')
}

function setAmountCharacters(textareaField){
	var maximum = parseInt(jQuery(textareaField).attr('maxlength'));
	var amount = jQuery(textareaField).val().length;
	if(amount <= maximum){
		var formItem = jQuery(textareaField).parent().parent();
		formItem.find('.formDesc p span').html((maximum - amount));
		if (amount == maximum) {
			formItem.find('.formDesc').addClass('formError');
		} else {
			formItem.find('.formDesc').removeClass('formError');
		}
	} else {
		jQuery(this).val(jQuery(this).val().substring(0,maximum));
		}
	}


function foodPyramid(){
	var name,
			pageName = $('.foodPyramid ul li.active a').attr('class').substr(3);

	$('#label' + pageName).addClass('active');

	$('#foodPyramidMap area').hover(function(){		
		name = $(this).attr('id').substr(6);
		if(name != pageName){
			$('#label' + pageName).removeClass('active').fadeOut('fast');			
		}
		$('#label' + name).stop(true, true).fadeIn('fast');
	},function(){
		$('#label' + pageName).addClass('active').fadeIn('fast');
		if(name != pageName){
			$('#label' + name).stop(true, true).fadeOut('fast');
		}
	});
}


/* ie-fixes.js */  
(function(document, $) {
	$(document).ready(function() {
		if (!$.browser.msie) return false;
	
		// Counter Image Gallery Bar in IE6
		if ($.browser.version == '6.0') $('img').attr('galleryimg', 'no');
		
		// Footer fix in IE 6
		if ($.browser.version == '6.0') $('#content .footer').prepend($(document.createElement('div')).attr('class','clearfix'));
	});
})(document, jQuery);

 
/* cooking.js */  
(function(document, $) {
	// Recipe Detail
	if (jQuery('.recipe h2.ingredients .servings').length) {
		$('.recipe h2.ingredients .servings').servings($('.ingredients ul'));
	}
	if (jQuery('.recipe .ratingWidget').length) {
	$('.recipe .ratingWidget').rating();
	}
})(document, jQuery); 
/* additional rating-script */

/* carrousel.js */  
(function(document, $) {
	$(window).load(function() {
		/* Default Implementations */
		if (jQuery('.carrouselWidget').length) {
		$('.carrouselWidget .carrousel').carrousel({ autoStart: false, navigation: { position: 'right', collapsed: true } });
		}
		/* Custom Navigation */
		/* - Cooking/Recipes Top Page */
		/*$('.cooking .carrouselWidget .carrousel').each(function() {
			$carrousel = $(this);
			
			// Build External Navigation
			$nav = $(document.createElement('ul'))
				.attr('class', 'extNav');
				
			navItems = new Array();
				
			var navCount = 0;
			$carrousel.find('.item h2').each(function() {
				(function(navCount, $this) {
					navItems[navCount] = $(document.createElement('li'))
						.click(function() { $carrousel.carrousel('move', navCount); })
						.attr('class', navCount == 0 ? 'active' : '')
						.append($(document.createElement('a'))
							.html($this.html()));
						
					$nav.append(navItems[navCount]);
				})(navCount, $(this));
				navCount++;
			});
			$carrousel.before($nav);
			
			// Initialise Carrousel
			$carrousel.carrousel({ 
				autoStart: false, 
				navigation: { enabled: false }, 
				onMoveStart: function() { 
					
				},
				onMoveEnd: function(from, to) {
					$.each(navItems, function(index, item) { item.removeClass('active'); });
					$(navItems[to]).addClass('active');
				}
			});
		});*/
	});
})(document, jQuery);

// megamenu/megadropdown
(function(document, $) {
var configmegamenu = {    
	over: function () { 
				$(this).addClass("megaArrow");
				$(this).find(".megamenu").removeClass("hidden").addClass("unhidden");
	}, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: function(){
				$(this).removeClass("megaArrow");
				$(this).find(".megamenu").removeClass("unhidden").addClass("hidden");
	} // function = onMouseOut callback (REQUIRED)    
};
$("#siteNav").find("li").each(function () {$(this).hoverIntent(configmegamenu)});
})(document, jQuery); 

/* table caption hack to fix width in chrome (and opera) */  
(function(document, $) {
	if(!$("html").hasClass("ie")){
		$('table').each(function(){
			var caption = $(this).find("caption");
			if(caption.length == 1){
				if ($.browser.opera) {
					caption.width($(this).outerWidth(true)-caption.css('padding-left') - caption.css('padding-left')); // css padding caption
				}
				else {
					caption.width($(this).outerWidth(true));
				}
			}
		});
	}
	else if ($.browser.version<9) {
		$("tbody tr:even").css("background-color", "#e1e2e2"); /* table tr hack support alternating colors */
	}
})(document, jQuery); 

// horizontal scrollbar products @ home (plugin)
	$(function() {
		$('.scroll-content .promoproduct').last().css('border',0);
		//scrollpane parts
		var scrollPane = $( ".scroll-pane" ),
			scrollContent = $( ".scroll-content" );
		
		//build slider
		var scrollbar = $( ".scroll-bar" ).slider({
			slide: function( event, ui ) {
				if ( scrollContent.width() > scrollPane.width() ) {
					scrollContent.css( "margin-left", Math.round(
						ui.value / 100 * ( scrollPane.width() - scrollContent.width() )
					) + "px" );
				} else {
					scrollContent.css( "margin-left", 0 );
				}
			}
		});
		
		//append icon to handle
		var handleHelper = scrollbar.find( ".ui-slider-handle" )
		.mousedown(function() {
			scrollbar.width( handleHelper.width() );
		})
		.mouseup(function() {
			scrollbar.width( "100%" );
		})
		.append( "<span class='ui-icon ui-icon-grip-dotted-vertical'></span>" )
		.wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();
		
		//change overflow to hidden now that slider handles the scrolling
		scrollPane.css( "overflow", "hidden" );
		
		//size scrollbar and handle proportionally to scroll distance
		function sizeScrollbar() {
			var remainder = scrollContent.width() - scrollPane.width();
			var proportion = remainder / scrollContent.width();
			var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );
			if (remainder==0) {
				scrollbar.parent().css({
					display: 'none'
				});
			}
			else {
				scrollbar.find( ".ui-slider-handle" ).css({
					width: handleSize,
					"margin-left": -handleSize / 2
				});
				handleHelper.width( "" ).width( scrollbar.width() - handleSize );
			}
			
		}
		
		//reset slider value based on scroll content position
		function resetValue() {
			var remainder = scrollPane.width() - scrollContent.width();
			var leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 :
				parseInt( scrollContent.css( "margin-left" ) );
			var percentage = Math.round( leftVal / remainder * 100 );
			scrollbar.slider( "value", percentage );
		}
		
		//if the slider is 100% and window gets larger, reveal content
		function reflowContent() {
				var showing = scrollContent.width() + parseInt( scrollContent.css( "margin-left" ), 10 );
				var gap = scrollPane.width() - showing;
				if ( gap > 0 ) {
					scrollContent.css( "margin-left", parseInt( scrollContent.css( "margin-left" ), 10 ) + gap );
				}
		}
		
		//change handle position on window resize
		/*$( window ).resize(function() {
			resetValue();
			sizeScrollbar();
			reflowContent();
		});*/
		//init scrollbar size
		setTimeout( sizeScrollbar, 10 );//safari wants a timeout
	});

/* SearchBox AutoComplete */
function GetAutocomplete(input, handler, template, language, field) {
    jQuery(input).autocomplete({
        source: function (request, response) {
            jQuery.ajax({
                url: handler,
                dataType: 'json',
                data: {
                    template: template,
                    language: language,
                    field: field,
                    query: request.term
                },
                success: function (data) {
                    response(data);
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {
            console.log(ui.item ?
					"Selected: " + ui.item.label :
					"Nothing selected, input was " + this.value);
        },
        position: { offset: "0 -15" },
		appendTo: ".roundInputWithButton",
		width: jQuery(this).parent().outerWidth()
    });
}
