
/**
 * KARE
 *   Main
 */

var KARE = {};

/**
 * Main
 */

KARE.Main = function() {
	
	var Locale;
	var language
	
	var resizeTimer;
	var data = {};
	
	var searchFieldFocused = false;
	
	function setup() {
		// png fix
		if ($.fn.pngFix !== undefined) {
			$(document).pngFix({ blankgif: getBaseURL() + 'gfx/helper/blank.gif' });
		}
		$(window).bind('resize', function() {
			if (resizeTimer) clearTimeout(resizeTimer);
			resizeTimer = setTimeout(resizeAlign, 100);
		});
		resizeTimer = setTimeout(resizeAlign, 100);
		
		if($(".fbLikeBoxContainer").val() != undefined) {

			$(".fbLikeBoxContainer").hover(function(){
				$(this).stop().animate({'height':'425px'},500);
			},function(){
				$(this).stop().animate({'height':'267px'},500);
			});
			
		}
		
		if($("#horScrollSlider").val() != undefined)
		{
			activateHorScrollSlider();
		}
		if($("body").hasClass('cms'))
		{
			$(".container_ajaxTextfield").each(function(){
				var inputField = $($(this).find("input"));
				var saveButton = $($(this).find("a.ajaxLinkSave"));
				var loadingIcon = $($(this).find("img.loaderIcon"));
				var requestAjaxTestField;
				inputField.bind('keypress',function(ev){
					saveButton.show();
				});
				inputField.bind('mousedown',function(ev){
					if(ev.button == 2) {
						saveButton.show();
					}
				});
				saveButton.bind('click',function(ev){
					ev.preventDefault();
					saveButton.hide();
					loadingIcon.show();
					requestAjaxTestField = $.ajax({
						cache: false,
						dataType: 'json',
						type: 'POST',
						url: '/ajax/?a=saveTextField',
						data:{value:'asdfqwerfgjh'},
						error: function(obj, msg, e){
							//console.log('error: ' + msg);
						},
						success: function(json){
							console.log(json);
							//saveButton.show();
							loadingIcon.hide();
						}
					});
				});
			});
			
			var ajaxRequestImageSource;
			var lastMouseX;
			var lastMouseY;
			$(".cmsImageDescription").each(
					function()
					{
						$(this).mouseover(
							function()
							{
								$('#toolTip').empty();
								$('#toolTip').append('<img src="/gfx/icon/loading.gif" width="28" height="28" alt="loading" title="loading" />');
								if(ajaxRequestImageSource)
								{
									ajaxRequestImageSource.abort();
								}
								ajaxRequestImageSource = $.ajax({
									cache: false,
									dataType: 'json',
									type: 'GET',
									url: '/ajax/?a=getImageSourceByID&b='+parseInt($(this).attr('id')),
									error: function(obj, msg, e){
										//alert('error: ' + msg);
									},
									success: function(json){
										$('#toolTip').empty();
										$('#toolTip').append('<img id="toolTipImage" src="'+json.result+'" height="200" alt="Image" title="Image" />');
										$('#toolTipImage').hide();
										$('#toolTipImage').load(
												function()
												{
													$('#toolTipImage').fadeIn();
													$(".cmsImageDescription").each(
															function()
															{
																$(this).mousemove();
															}
													);
												}
										);
									}
								});
							}
						);
						$(this).mousemove(function(e){
					        $("#toolTip").show();
					        if(isNaN(e.pageX))
					        {
					        	e.pageY = lastMouseY;
					        	e.pageX = lastMouseX;
					        } else {
					        	lastMouseY = e.pageY;
					        	lastMouseX = e.pageX;
					        }
					        if(!isNaN(parseInt($("#toolTip img").height())))
					        {
						        $("#toolTip").css({
						           top: (e.pageY - 10 - parseInt($("#toolTip img").height())) + "px",
						           left: (e.pageX + 5) + "px"
						        });
					        }
					    });
						$(this).mouseout(function(e){
							ajaxRequestImageSource.abort();
					        $("#toolTip").hide();
					        $('#toolTip').empty();
					    });
					}
			);
		}
		if($("body").hasClass('catalog_list') || $("body").hasClass('trendshow_list') || $("body").hasClass('trendshow') || $("body").hasClass('catalog') || $("body").hasClass('shop_news') || $("body").hasClass('shop_offers') || $("body").hasClass('shop_team') || $("body").hasClass('team_detail'))
		{
			activateBottomSwitchLayer()
		}
		if($("body").hasClass('trendshow'))
		{
			activateTrendshowFlash();
		}
		if($("body").hasClass('catalog'))
		{
			//activateCatalogFlash();
		}
		if($("#languageSelector > p > #selectCountry").length != 0)
		{
			$("#languageSelector > p > #selectCountry").change(function()
			{
				document.location.href = '/cms/cms_switch_language/'+$("#languageSelector option:selected").val()+'/';
			});
		}
		if($("#pageLanguageSelector").val() != undefined)
		{
			$("#pageLanguageSelector").bind('click', toggleLanguageSelector);
		}
		if($("#textA").val() != undefined)
		{
			$("#images").cycle(
			{ 
				fx:    "fade", 
				speed:  3000
			});
		}
		
		if($("#scrollLayerA").val() != undefined)
		{
			activateSlider();
		}
		
		if($(".linkAddBasket").val() != undefined)
		{
			$(".linkAddBasket").bind('click',function()
			{
				$("#form_add_product").submit();
			});
		}
		
		if($("body").hasClass('login'))
		{	
			$('#subButton').hover(
			    function(){$(this).attr('src','/gfx/button/button_retailer_login_submit_h.gif')},function(){$(this).attr('src','/gfx/button/button_retailer_login_submit.gif')}
			)
		}
		
		if($("#wordSearch").val() != undefined)
		{
			$("#wordSearch").click(function(){
				$("#formularExtendedSearch").submit();
				return false;
			});
		}
		
		if($("body").hasClass('leaflet'))
		{	
			$("#linkOrder").bind('click', leafletOrder);
			$("#linkRefresh").bind('click', leafletRefresh);
			$("#linkQuickAdd").bind('click', leafletQuickAdd);
		}
		
		if($("#printButton").val() != undefined)
		{
			$("#printButton").bind('click', printPage);
		}
		
		if($("#imageSwitchLinkLeft").val() != undefined)
		{
			$("#imageSwitchLinkRight").bind('click', switchDetailImageRight);
			$("#imageSwitchLinkRight").bind('click', function(){window.clearInterval(window.slideShowInterval)});
			$("#imageSwitchLinkLeft").bind('click', switchDetailImageLeft);
			$("#imageSwitchLinkLeft").bind('click', function(){window.clearInterval(window.slideShowInterval)});
			if(document.more_images_ar.length > 1)
			{
				$("#productDetailImage").bind('click', switchDetailImageRight);
				$("#productDetailImage").bind('click', function(){window.clearInterval(window.slideShowInterval)});
				$("#productDetailImage").css("cursor", "pointer");
			}
			startProductSlideShow();
		}
		
		$("#leafletForm").submit(function(){
			if($("#leafletAction").val() == '') {
				$("#leafletAction").val('refresh');
			}
		});
		
		$("#fieldQuickSearch").bind('focus',function(){
			if(!searchFieldFocused)
			{
				$("#fieldQuickSearch").attr("value","");
				searchFieldFocused = true;
			}
			/*$('#searchExtendedContainer').stop().animate({'height':'35px'},500,null,function(){
				//console.log('Extended search opened');
			});*/
			$('#searchExtendedClose').click(function(ev){
				ev.preventDefault();
					$('#searchExtendedContainer').stop().animate({'height':'0px'},500,null,function(){
					//console.log('Extended search closed');
				});
			});
		});
		
		if($("#buttonShowMe").val() != undefined)
		{
			$("#buttonShowMe,#buttonHideMe").click(function(){
				if($('#detailContainer').height() > 1)
				{
					$('#contentHeader').css('visibility','visible')
					$('#contentHeader').stop().animate({opacity:'1'},800);
					$('#detailContainer').stop().animate({height:'0px'},800);
					$("#buttonShowMe").attr('src','/gfx/button/button_show.gif');
					$('#detailContent').fadeOut();
				} else {
					$('#contentHeader').stop().animate({opacity:'0'},800,null,function(){$('#contentHeader').css('visibility','hidden')});
					$('#detailContainer').stop().animate({height:'603px'},800,null,function(){});
					$('#detailContent').fadeIn(800);
					$("#buttonShowMe").attr('src','/gfx/button/button_hide.gif');
				}
			});
		}
		
		if(document.doSwitchBottomLayer == "true")
		{
			switchBottomLayerB();
		}
		
		if($("#productsHolder").val() != undefined)
		{
			var obj = $('#productsHolder img');
			obj.load(function(){
				//run function for all images again and again because of images which are allready in page and who do not fire the load event
				obj.each(
					function(){
					    var div = $(".highlight", $(this).parent().parent()[0]);
					    div.show();
					    div.css({'margin-left':($(this).width() - 57) + 'px'});
					    var div = $(".new", $(this).parent().parent()[0]);
					    div.show();
					    div.css({'margin-left':($(this).width() - 57) + 'px'});
					}
			    )
			});
			//run once manually for case that all images are cached
			obj.each(
				function(){
				    var div = $(".highlight", $(this).parent().parent()[0]);
				    div.show();
				   	div.css({'margin-left':($(this).width() - 57) + 'px'});
				    var div = $(".new", $(this).parent().parent()[0]);
				    div.show();
				   	div.css({'margin-left':($(this).width() - 57) + 'px'});
				}
		    )
		}
		
		if($("#productDetailImage").val() != undefined)
		{
			$('#productDetailImage').load(function(){				
			    var div = $(".highlight", $(this).parent().parent()[0]);
			    div.show();
			    div.css({'margin-top':'-10px','left':(65 + $(this).width() / 2) + 'px'});
			    var div = $(".new", $(this).parent().parent()[0]);
			    div.show();
			    div.css({'margin-top':'-10px','left':(65 + $(this).width() / 2) + 'px'});
			});
			$('#productDetailImage').each(
				function(){				
			    	var div = $(".highlight", $(this).parent().parent()[0]);
			    	div.show();
			    	div.css({'margin-top':'-10px','left':(65 + $(this).width() / 2) + 'px'});
			    	var div = $(".new", $(this).parent().parent()[0]);
			    	div.show();
			    	div.css({'margin-top':'-10px','left':(65 + $(this).width() / 2) + 'px'});
				}
			);
		}
		
		if($(".searchThumb").val() != undefined)
		{
			var obj = $('.searchThumb');
			obj.load(function(){
				//run function for all images again and again because of images which are allready in page and who do not fire the load event
				obj.each(
					function(){
						var pos = $(this).position();
					    var div = $(".highlight", $(this).parent().parent()[0]);
					    div.show();
					    div.css({'top':(pos.top) + 'px'});
					    div.css({'left':(pos.left + $(this).width() - 20) + 'px'});
					    var div = $(".new", $(this).parent().parent()[0]);
					    div.show();
					    div.css({'top':(pos.top) + 'px'});
					    div.css({'left':(pos.left + $(this).width() - 20) + 'px'});
					}
			    );
			});
			//run once manually for case that all images are cached
			obj.each(
				function(){
					var pos = $(this).position();
				    var div = $(".highlight", $(this).parent().parent()[0]);
				    div.show();
				    div.css({'top':(pos.top) + 'px'});
				    div.css({'left':(pos.left + $(this).width() - 20) + 'px'});
				    var div = $(".new", $(this).parent().parent()[0]);
				    div.show();
				    div.css({'top':(pos.top) + 'px'});
				    div.css({'left':(pos.left + $(this).width() - 20) + 'px'});
				}
		    )
		}
		
		if($(".leafletThumb").val() != undefined)
		{
			var obj = $('.leafletThumb');
			obj.load(function(){
				//run function for all images again and again because of images which are allready in page and who do not fire the load event
				obj.each(
					function(){
					    var div = $(".highlight", $(this).parent().parent()[0]);
					    div.show();
					    div.css({'margin-left':(39 + $(this).width() / 2) + 'px'});
					    var div = $(".new", $(this).parent().parent()[0]);
					    div.show();
					    div.css({'margin-left':(39 + $(this).width() / 2) + 'px'});
					}
			    )
			});
			//run once manually for case that all images are cached
			obj.each(
				function(){
				    var div = $(".highlight", $(this).parent().parent()[0]);
				    div.show();
				   	div.css({'margin-left':(39 + $(this).width() / 2) + 'px'});
				    var div = $(".new", $(this).parent().parent()[0]);
				    div.show();
				   	div.css({'margin-left':(39 + $(this).width() / 2) + 'px'});
				}
		    )
		}
		
		if($("#productCategories").val() != undefined)
		{
			addAdvancedSearch();
		}
		
		if($("#productsPerPageSelector").val() != undefined)
		{
			$("#productsPerPageSelector").click(function(ev){
				ev.preventDefault();
				ev.stopPropagation()
				if($('#productsPerPage').css('margin-top') == "-20px")
				{
					$('#productsPerPage').animate({marginTop:'0px'});
					$("#productsPerPageArrow").attr('src','/gfx/button/arrow_red_black_up.gif');
					$(document).bind('click',closeProductsPerPageSelector);
				} else {
					closeProductsPerPageSelector();
				}
			});
			
			 $(".pppVal").click(function(ev){
			 	ev.preventDefault();
			 	$('#iconLoading').css('visibility','visible');
			 	$.ajax({
					cache: false,
					dataType: 'json',
					type: 'GET',
					url: '/ajax/?a=setProductsPerPage&b=' + $(this).attr('id'),
					error: function(obj, msg, e){
						//console.error(obj, msg, e);
						//alert('error: ' + msg);
					},
					success: function(json){
						var tmpDate = new Date();
						var hrefAr = document.location.href.split("#");
						hrefAr = hrefAr[0].split("?");
						var hrefStr = hrefAr[0];
						
						document.location.href = hrefStr+'?ran='+tmpDate.getTime();
					}
				});
			 });
		}
		
		if($("body").hasClass('trendshow'))
		{
			$("#groupTeaserContainer .teaser").bind('mouseout',function(){
				$(this).find('a,p').stop().animate({opacity: '1'},300);
			});
			$("#groupTeaserContainer .teaser").bind('mouseover',function(){
				$(this).find('a,p').stop().animate({opacity: '0'},300);
			});
		}
		
		checkBottomLayerSwitch();
		
		/*if($("#totalSum").val() != undefined) {
			var request = $.ajax({
				cache: false,
				dataType: 'json',
				type: 'GET',
				url: '/ajax/?a=getTotalSum',
				error: function(obj, msg, e){
					request.abort();
					$("#totalSum").empty().text('Error');
				},
				success: function(json){
					$("#totalSum").empty().text(json.result);
				}
			});
		}*/
		//$("#totalSum").empty();
		
		//Add to basket icon on product lists
		$('.priceAddContainer .iconAdd').click(function(ev){
			ev.preventDefault();
			addToBasketFromProductList(this,data.basePath);
		});
		
	}
	
	function addToBasketFromProductList(icon,basePath) {
		console.log(basePath);
		var prodHrefAr = $(icon).parent().next().attr('href').split('/');
		$(icon).unbind();
		$(icon).fadeOut();
		jQuery.ajax({
			cache: false,
			type: 'POST',
			url: basePath+'add_basket/'+prodHrefAr[6]+'/'+prodHrefAr[7]+'/',
			dataType: 'json',
			data: 'referer=productlist',
			success: function(data){
				//console.log('done');
			},
			error: function(er) {
				//console.log('error');
			} 
		});
	}
	
	function closeProductsPerPageSelector()
	{
		$(document).unbind('click',closeProductsPerPageSelector);
		$('#productsPerPage').animate({marginTop:'-20px'});
		$("#productsPerPageArrow").attr('src','/gfx/button/arrow_red_black_down.gif');
	}
	
	function startProductSlideShow()
	{
		if(document.more_images_ar.length >= 2)
		{
			window.slideShowInterval = window.setInterval("KARE.Main.switchDetailImageRight()", 3000)
		}
	}
	
	function addAdvancedSearch()
	{
		
		//$("#productCategories").selectbox();
		//$("#productGroups").selectbox();
		if($("#productCategories").val() == "new" || $("#productCategories").val() == "bargain")
		{
			$("#productGroups").hide();
			$("#searchWordAnd").hide();
		}
		$("#productCategories").change(function(){
			console.log('asdf');
			if($("#productCategories").val() == 0)
			{
				$("#productGroups").hide();
				//$('#productGroupsContainer .jquery-selectbox').hide();
				var basePathAr = data.basePath.split("/");
				var shopID = basePathAr[basePathAr.length - 2];
				$.ajax({
					cache: false,
					dataType: 'json',
					type: 'GET',
					url: '/ajax/?a=getAllCategories&b=' + data.language + "&d=" + shopID,
					error: function(obj, msg, e){
						//console.error(obj, msg, e);
						//alert('error: ' + msg);
					},
					success: function(json){
						//$('#productGroupsContainer .jquery-selectbox').unselectbox();
						$("#productGroups").removeOption(/./);
						$("#productGroups").addOption({'0':''});
						$("#productGroups").addOption(json, false);
						$("#productGroups").show();
						$("#searchWordAnd").show();
						getWordWebService(data.language,"word_all_product_groups", $("#productGroups option:eq(0)"));
					}
				});
			} else {
				if($("#productCategories").val() == "new" || $("#productCategories").val() == "bargain")
				{
					$("#productGroups").hide();
					$("#searchWordAnd").hide();
				} else {
					$("#productGroups").hide();
					//$('#productGroupsContainer .jquery-selectbox').hide();
					var basePathAr = data.basePath.split("/");
					var shopID = basePathAr[basePathAr.length - 2];
					$.ajax({
						cache: false,
						dataType: 'json',
						type: 'GET',
						url: '/ajax/?a=getSubGroups&b=' + $("#productCategories").val() + "&d=" + data.language + "&e=" + shopID,
						error: function(obj, msg, e){
							//console.error(obj, msg, e);
							//alert('error: ' + msg);
						},
						success: function(json){
							//$('#productGroupsContainer .jquery-selectbox').unselectbox();
							$("#productGroups").removeOption(/./);
							$("#productGroups").addOption({'0':''});
							$("#productGroups").addOption(json, false);
							getWordWebService(data.language,"word_all_product_groups", $("#productGroups option:eq(0)"));
							$("#searchWordAnd").show();
						}
					});
				}
			}
		});
	}
	
	function getWordWebService(_language, _word, _target)
	{
		var basePathAr = data.basePath.split("/");
		var shopID = basePathAr[basePathAr.length - 2];
		$.ajax({
			cache: false,
			dataType: 'json',
			type: 'GET',
			url: '/ajax/?a=getWord&b=' + _language + "&c=" + _word + "&d=" + shopID,
			error: function(obj, msg, e){
				//console.error(obj, msg, e);
				//alert('error: ' + msg);
			},
			success: function(json){					
				_target.text(json.word);
				$("#productGroups").show();
				//$("#productGroups").selectbox();
			}
		});
	}
	
	function checkBottomLayerSwitch()
	{
		$("#switchBottomLayerB").click(switchBottomLayerB);
	}
	
	function switchBottomLayerB()
	{
		if(parseInt($("#bottomLayerB").css("top")) == 0)
		{
			$("#bottomLayerB").animate({top:"-140px"}, 1000);
		} else {
			$("#bottomLayerB").animate({top:"0px"}, 1000);
		}
	}
	
	var currentMoreImageCount = 0;
	
	function switchDetailImageRight()
	{
		if(currentMoreImageCount == document.more_images_ar.length-1)
		currentMoreImageCount = -1;
		$("#productDetailImage").attr('src',document.more_images_ar[++currentMoreImageCount]);
		$("#moreImagesCurrent").html(currentMoreImageCount+1);
	}
	function switchDetailImageLeft()
	{
		if(currentMoreImageCount == 0)
		currentMoreImageCount = document.more_images_ar.length;
		$("#productDetailImage").attr('src',document.more_images_ar[--currentMoreImageCount]);
		$("#moreImagesCurrent").html(currentMoreImageCount+1);
	}
	
	function leafletOrder()
	{
		$("#linkOrder").css('visibility','hidden');
		$("#linkRefresh").css('visibility','hidden');
		$("#linkQuickAdd").css('visibility','hidden');
		$("#loadingOrder").css('display','block');
		$("#leafletAction").val("order");
		$("#leafletForm").submit();
	}
	
	function leafletRefresh()
	{
		$("#linkOrder").css('visibility','hidden');
		$("#linkRefresh").css('visibility','hidden');
		$("#linkQuickAdd").css('visibility','hidden');
		$("#loadingOrder").css('display','block');
		$("#leafletAction").val("refresh");
		$("#leafletForm").submit();
	}
	
	function leafletQuickAdd()
	{
		if($("#quick_add_article_number").val() != "")
		{
			$("#formQuickAdd").submit();
		}
	}
	
	function printPage()
	{
		window.print();
	}
	
	function activateCatalogFlash()
	{		
		var flashvars = {basePath:data.basePath,topVar:data.topVar,categories:encodeURIComponent('[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"},{"id":"6"},{"id":"7"},{"id":"8"},{"id":"9"},{"id":"10"}]')}
		var params = {wmode:"transparent", menu: "false"};
		var attributes = {id: "myDynamicContent", name: "myDynamicContent"};
		var so = swfobject.embedSWF("/swf/product_overview.swf", "flashA", "100%", "462", "9.0.0", null, flashvars, params, attributes);
		if(swfobject.hasFlashPlayerVersion("9.0.0"))
		{
			$("#groupListContainer").hide();
		}
	}
	
	function activateTrendshowFlash()
	{
		if($("#flashB").val() != undefined)
		{
			var flashvars = {trendshowPath:data.basePath+'products/trendshow/', suffix:document.suffix, basePath:data.basePath}
			var params = {wmode:"transparent", menu: "false"};
			var attributes = {id: "myDynamicContent", name: "myDynamicContent"};
			var so = swfobject.embedSWF("/swf/trendshow_overview.swf", "flashB", "908", "462", "9.0.0", null, flashvars, params, attributes);
			if(swfobject.hasFlashPlayerVersion("9.0.0"))
			{
				$("#groupListContainer").hide();
			}
		}
		if($("#flashA").val() != undefined)
		{
			var flashvars = {trendshowPath:data.basePath+'products/trendshow/',topVar:data.topVar,trendshowID:document.flashID, basePath:data.basePath}
			var params = {wmode:"transparent", menu: "false"};
			var attributes = {id: "myDynamicContent", name: "myDynamicContent"};
			var so = swfobject.embedSWF("/swf/trendshow_"+document.flashID+".swf", "flashA", "100%", "462", "9.0.0", null, flashvars, params, attributes);
			{
				$("#groupListContainer").hide();
			}
		}
	}
	
	function activateBottomSwitchLayer()
	{
		if($("#labelB").val() == undefined)
		{
			$("#bottomLayerA").show();
			$("#arrowB").hide();
		} else {
			var timeOut;
			$("#labelA,#arrowA,#bottomLayerA").hover(function() {
														$("#bottomLayerB,#arrowB").hide();
														$("#bottomLayerA,#arrowA").show();
														clearTimeout(timeOut);
													},
													function() {
														timeOut = setTimeout("closeLayer()",300);
													});
													closeLayer = function()
													{
														$("#bottomLayerB,#arrowB").show();
														$("#bottomLayerA,#arrowA").hide();
													}
		}
	}
	
	
	
	function activateHorScrollSlider()
	{
		if($("#productsHolder").width() <= $("#horScrollContainer").width())
  		{
  			$("#horScrollSlider").hide();
  		} else {
			$(".slider").slider(
	  		{
	  			slide: function()
	  			{
	  				var maxScroll = $("#productsHolder").width() - $("#horScrollContainer").width();
	  				var percentToAmount = (maxScroll/100)* $(".slider").slider("value"); 
	  				$("#productsHolder").css({'left':-percentToAmount+'px'});
	  			},
	  			change: function()
	  			{
	  				var maxScroll = $("#productsHolder").width() - $("#horScrollContainer").width();
	  				var percentToAmount = (maxScroll/100)* $(".slider").slider("value"); 
	  				$("#productsHolder").css({'left':-percentToAmount+'px'});
	  			}
	  		});
	  		$("#horScrollContainer").mousewheel(function(event, delta) 
	  		{
	  			if(isNaN($(".slider").slider("value"))) $(".slider").slider("moveTo", 0);
	  			$(".slider").slider("moveTo", $(".slider").slider("value") - (delta * 2));
			})
			$("#horScrollSlider .arrowLeft").bind('click', function(){
				$(".slider").slider("moveTo", $(".slider").slider("value") - 5);
			});
			$("#horScrollSlider .arrowRight").bind('click', function(){
				$(".slider").slider("moveTo", $(".slider").slider("value") + 5);
			});
		}
	}
	
	//SLIDER SPECIFIC FUNCTION
	function activateSlider()
	{
		$("#sliderA").hide();
  		/*if($("#textA")[0].scrollHeight <= $("#scrollLayerA")[0].scrollHeight - 15)
  		{
  			$("#sliderA").hide();
  		} else {
  			
	  		$("#sliderA").slider(
	  		{
	  			slide: function()
	  			{
	  				var maxScroll = $("#textA")[0].scrollHeight - $("#scrollLayerA")[0].scrollHeight + 20; // + 20 because of padding
	  				var percentToAmount = (maxScroll/100)* $("#sliderA").slider("value"); 
	  				//$("#textA").animate({scrollTop: percentToAmount}, .01);
	  				$("#textA").scrollTop(percentToAmount);
	  			},
	  			change: function()
	  			{
	  				var maxScroll = $("#textA")[0].scrollHeight - $("#scrollLayerA")[0].scrollHeight + 20; // + 20 because of padding
	  				var percentToAmount = (maxScroll/100)* $("#sliderA").slider("value"); 
	  				$("#textA").scrollTop(percentToAmount);
	  			}
	  		});
	  		//:MOUSEWHEEL SUPPORT
	  		$("#scrollLayerA").mousewheel(function(event, delta) 
	  		{
	  			if(isNaN($("#sliderA").slider("value"))) $("#sliderA").slider("moveTo", 0);
	  			$("#sliderA").slider("moveTo", $("#sliderA").slider("value") - delta * 8);
			})
		}*/
	}
	
	var footerLoginOpen = false;
	var footerIsMoving = false;
	var footerLanguageOpen = false;
	
	function toggleLanguageSelector()
	{
		if(!footerIsMoving)
		{
			if(footerLoginOpen) toggleFooterLogin();
			footerIsMoving = true;
			$("#retailerLoginMask").css({'display':'block'});
			var gotoPos = parseInt($("#languageSelectorContainer").css("top")) == 0 ? 50 : 0;
			$("#languageSelectorContainer").animate({top:+gotoPos+'px'},null,toggleLanguageSelectorDone)
			footerLanguageOpen = true;
		}
	}
	function toggleLanguageSelectorDone()
	{
		if(parseInt($("#languageSelectorContainer").css("top")) != 0)
		{
			if(!footerLoginOpen) $("#retailerLoginMask").css({'display':'none'});
			footerLanguageOpen = false;
		}
		footerIsMoving = false;
	}
	
	function resizeAlign() {
		//Simulate min-width for all contents
		if($(window).width() < 908)
		{
			$("body").css("background-position","-186px 0px");
			$("#logoContainer").css({'width':'908px'});
			$("#logoFillContainer").css({'width':'908px'});
			$("#mainNavContainer").css({'width':'908px'});
			$("#mainContentContainer").css({'width':'908px'});
			$("#footerContainer").css({'width':'908px'});
			$("#logoLink").css({'left':'454px'});
		} else {
			$("body").css("background-position","center top");
			$("#logoContainer").css({'width':'100%'});
			$("#logoFillContainer").css({'width':'100%'});
			$("#mainNavContainer").css({'width':'100%'});
			$("#mainContentContainer").css({'width':'100%'});
			$("#footerContainer").css({'width':'100%'});
			$("#logoLink").css({'left':'50%'});
		}
	}
	
	function getBaseURL() {
		return getData('baseURL');
	}
	
	// data
	
	function initData(obj) {
		
		obj = $.extend({
			baseURL:   '/',
			language:  'en'
		}, obj);
		
		data = obj;
	}
	
	function getData(key) {
		return data[key] !== undefined ? data[key] : null;
	}
	
	function setData(key, value) {
		var changed = (getData(key) !== value);
		
		data[key] = value;
		
		return changed;
	}
	
	function getLanguage() {
		return getData('language');
	}
	
	function init() {
		
		$(function(){
			setup();
		});
		
		Locale = KARE.Locale;
		
		Locale.init();
		
		return this;
	}
	
	return {
		init: init,
		initData: initData,
		getBaseURL: getBaseURL,
		getLanguage: getLanguage,
		switchBottomLayerB: switchBottomLayerB,
		switchDetailImageRight:switchDetailImageRight,
		activateSlider:activateSlider
	};
	
}();

/**
 * Locale
 */

KARE.Locale = function() {
	var data = {};
	
	function translate(key, params) {
		var str = key;
		
		if (data[key] !== undefined) {
			str = data[key];
		} else {
			//console.warn('KARE.Locale.translate() key not found -> ' + key);
		}
		
		if (params !== undefined) {
			for (var i = 0; i < params.length; i++) {
				str = str.replace(new RegExp('%' + (i + 1)), params[i]);
			}
		}
		
		return str;
	}
	
	function initData(obj) {
		data = obj;
	}
	
	function getData() {
		return data;
	}
	
	function init() {
		return this;
	}
	
	return {
		init: init,
		initData: initData,
		getData: getData,
		t: translate
	};
}();

KARE.Main.init();

/**
 * Array
 */

Array.prototype.exists = function(x) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] === x) {
			return i;
		}
	}
	return false;
};

if(!window.jQuery){throw("jQuery must be referenced before using the 'onImagesLoad' plugin.");}
/*
 * jQuery 'onImagesLoaded' plugin v1.1.0
 * Fires callback functions when images have loaded within a particular selector.
 *
 * Copyright (c) Cirkuit Networks, Inc. (http://www.cirkuit.net), 2008.
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * For documentation and usage, visit "http://includes.cirkuit.net/js/jquery/plugins/onImagesLoad/1.1/documentation/"
 */
(function($){
    $.fn.onImagesLoad = function(options){
        var self = this;
        self.opts = $.extend({}, $.fn.onImagesLoad.defaults, options);

        self.bindEvents = function($imgs, container, callback){
            if ($imgs.length === 0){ //no images were in selection. callback based on options
                if (self.opts.callbackIfNoImagesExist && callback){ callback(container); }
            }
            else {
                var loadedImages = [];
                if (!$imgs.jquery){ $imgs = $($imgs); }
                $imgs.each(function(i, val){
                    $(this).bind('load', function(){
                        if (jQuery.inArray(i, loadedImages) < 0){ //don't double count images
                            loadedImages.push(i); //keep a record of images we've seen
                            if (loadedImages.length == $imgs.length){
                                if (callback){ callback(container); }
                            }
                        }
                    }).each(function(){
                        if (this.complete || this.complete === undefined){ this.src = this.src; } //needed for potential cached images
                    });
                    $(this).bind('error', function() {
                    	//KARE workaraound to catch load error and display alternative image
                    	this.src = 'http://www.kare.local/gfx/helper/no_image.gif';
                    });
                });
            }
        };

        var imgAry = []; //only used if self.opts.selectorCallback exists
        self.each(function(){
            if (self.opts.itemCallback){
                var $imgs;
                if (this.tagName == "IMG"){ $imgs = this; } //is an image
                else { $imgs = $('img', this); } //contains image(s)
                self.bindEvents($imgs, this, self.opts.itemCallback);
            }
            if (self.opts.selectorCallback){
                if (this.tagName == "IMG"){ imgAry.push(this); } //is an image
                else { //contains image(s)
                    $('img', this).each(function(){ imgAry.push(this); });
                }
            }
        });
        if (self.opts.selectorCallback){ self.bindEvents(imgAry, this, self.opts.selectorCallback); }

        return self.each(function(){}); //dont break the chain
    };

	//DEFAULT OPTOINS
    $.fn.onImagesLoad.defaults = {
        selectorCallback: null,        //the function to invoke when all images that $(yourSelector) encapsultaes have loaded (invoked only once per selector. see documentation)
        itemCallback: null,            //the function to invoke when each item that $(yourSelector) encapsultaes has loaded (invoked one or more times depending on selector. see documentation)
        callbackIfNoImagesExist: false//if true, the callbacks will be invoked even if no images exist within $(yourSelector).
                                       //if false, the callbacks will not be invoked if no images exist within $(yourSelector).
    };
})(jQuery);
