/*
	jquery.config.js – 046 – 07.01.2011
*/
if(jQuery) (function($){
	
	// globals
	var options = { };
	var current;
	var offset = { };
	var height;
	var group;
	var timer;
	var layer;
	
	// public variables and methods
	$.extend({
		
		configurator: {
			
			defaults: {
				url: $.goin.defaults.ajaxConfigServiceUrl
				,selector: 'DIV#configurator' // der popup konfigurator der alle elemente beherbergt
				,triggers: 'DIV.bubble-clickable,.description A:not(.detail)' // klickbare elemente einzelener konfigurations gruppen
				,loader: 'DIV#loader'
			},
			
			
			// konfigurator initialisieren.
			init: function(elements, settings) {
				
				options = $.extend({}, $.configurator.defaults, settings);
				
				Cufon.replace("SPAN.sub-title", {fontSize:'16px'});
				
				/*
				$('#configurator A.detail IMG').hover(
					function() {
						this.src = this.src.replace( /\.png$/, '_hover.png' );
					},
					function() {
						this.src = this.src.replace( /_on\.png$/, '.png' );
					}
				);
				
				$("#configurator A.detail IMG").hover(function() {
					$(this).attr("src", $(this).attr("src").split(".").join("_hover."));
				  }, function() {
					$(this).attr("src", $(this).attr("src").split("_hover.").join("."));
				  });*/
				  
				// wechselt den Kunden Typ
				$('.client A').unbind('click').click(function() {
					// prüfen ob der warenkob leer ist
					if ($('#main-cart-button').hasClass('filled')) {
						var url=$(this).attr("ref");
						tb_show('', url, '');
						return false;
					} else {
						window.location.href = $(this).attr('href');
						return false;
					}
				});
				
				
				
				
				// unsichtbares html popup frame einmalig erzeugen
				$('.product-information').before($.configurator.format());
				
				// globaler ajax loading indikator
				$(options.selector)
					.before('<div id="loader"><img src="' + $.goin.defaults.ajaxLoadingImage + '" alt="Loading …" /></div>');
				var $loader = $('#loader');
				$loader.find('IMG')
					.ajaxStart(function() {$(this).show();})
					.ajaxStop(function() {$(this).hide();})
				.end();
				
				// in den warenkorb button
				$('DIV.cart-submit A').click(function(event) {
					var amount = Number(
						$(this).parent().find('INPUT').val()
					); 
					$.basket.defaults.SiteStat = $(this).attr('rel');
					$.basket.defaults.Url = $(this).attr('href');
					$.basket.add(amount);
					// notiz auf der produkt seite einblenden
					$('.page-product #submit-note').fadeIn('fast');
					$('DIV.currency').fadeOut('fast');
					return false;
				});
				// bestätigungsnotiz zunächst verstecken
				$('.page-product #submit-note').hide();
				
				
				// X auswahl zurücksetzen button
				$('DIV.unselect A').click(function() {
					$(options.selector).find('UL A').removeClass('active');
					// TODO AJAX UPDATE
					return false;
				});
				
			
				// popup overlay über die gesamte seite um den klickevent abzufangen
				// und das popup wieder zu schliessen.
				layer = $(options.selector).expose({
					onBeforeLoad:function(){ },
					onBeforeClose:function(){ $.configurator.hide(); },
					loadSpeed:'fast',
					color: '#333', 
					opacity: 0.0,
					api: true
				});
				
				$("A.close", options.selector).click(function(){
					layer.close();
					return false;
				});
				
				
				var $triggers = $(options.triggers);
				// verhalten der konfigurator elemente setzen
				$triggers
					// titel in rel attribute umwandeln
					.each(function() {
						var $this = $(this);
						$this.attr('rel', $this.attr('title')).attr('title','');
						if ($this.attr('href') != null) $this.attr('rel', $this.attr('href'));
				  })
					// klick event auf eine konfigurationseinheit
					.click(function() { 
						// hinweis notiz ausblenden
						$('DIV.jq-nbx').fadeOut('fast',function() { $(this).remove(); });
						current = this;
						offset = $(this).offset(); 
						height = $(this).height();
						$.configurator.show(this); 
						return false; 
					})
				.end();
				// Währungsumschaltung
				$('DIV.currency').find('A').click(function() {
					$.get(this.href, $.configurator.updateProdukt);
					return false;
				});
				//Montage ein/ausschalten
				$triggers.find('A.work').click(function() {
					$.get(this.href, $.configurator.updateProdukt);
					return false;
				});
				$('.bubble-disabled').find('A.work').click(function() {
					$.get(this.href, $.configurator.updateProdukt);
					return false;
				});
				
				
				// konfiguriertes element abwählen
				$triggers.find('A.remove').click(function() {
					$.get(this.href, $.configurator.updateProdukt);
					return false;
				});
				// auch inaktive bubbles können abwählbar sein
				$('.bubble-disabled').find('A.remove').click(function() {
					$.get(this.href, $.configurator.updateProdukt);
					return false;
				});
				
				// Konfiguration zurücksetzen Buttons
				var $buttons = $('BODY.page-product A.remove, BODY.page-product A.add');
				$buttons.each(function(){
					$(this).css('margin-top', String($(this).parent().height()/2)-7+'px');
				});
				
			},
			
			
			format: function() {
				var format = new String();
				format += '<div id="configurator" class="bubble-css ui-slider clear-block">';
				format += '<div class="cB">';
				format += '<div class="cBt"><div></div></div>';
				format += '<div class="inner clear-block">';
				format += '<div class="configurator-result">';
				format += '<ul><li></li></ul>';
				format += '</div>';
				format += '<div class="unselect"><a href="#">keine Auswahl</a></div>';
				format += '<a class="close" href="#"></a>';
				format += '<div class="slider"><div></div>';
				format += '<div class="handle"><div></div></div>';
				format += '</div>';
				format += '</div>';
				format += '<div class="cBb"><div></div></div>';
				format += '</div>';
				format += '</div>';
				return format;
			},
			
			
			// konfigurator verstecken
			hide: function() {
				// den timer zurücksetzen
				clearTimeout(timer);
				// alle elemente deselektieren
				$(options.triggers).removeClass('active');
				$(options.selector).hide(); // ergebnisbox verstecken
				// sicherstellen das der tooltip verschwindet
				$('.jq-tbx').fadeOut('fast');
				
				//if (layer.isLoaded()) layer.close();
			},
			
			
			// konfigurator anzeigen
			show: function() {
				
				// andernfalls ebenfalls alle elemente deselektieren
				$(options.triggers).removeClass('active');
				$(current).addClass('active'); // den geklickten neu selektieren
				$(options.selector)
				.hide(); // konfigurator verstecken

				$(options.loader)
					.css('top', (offset.top - 8 + height/2) - $('DIV.product-information').offset().top)
					.show(); // position setzen und status anzeigen
				
				layer.load();
				// entsprechende inhalte nachladen
				$.configurator.load($(current).attr('rel'));
			},
			
			
			// konfigurator inhalt laden
			load: function(url) {
				/*
					ajax laden der konfigurations elemente gruppe
					läd und öffnet das konfugurator popup fenster
				*/
				$.get(url, function(data) {
					
					var $configurator = $(options.selector);
					var $resultwidget = $configurator.find('.configurator-result');
					var $sliderwidget = $configurator.find('.inner');
					var $slider = $sliderwidget.find('.slider');
					
					$resultwidget.html(data);
					
					$configurator.show(); // IE6 BUG WORKAROUND
					// höhe des ersten bildes herausfinden
					// var _height = $sliderwidget.find('UL LI:first A IMG').attr("height") + 20 || 20;
					// hinterlegte höhe extrahieren
					var _height = Number($sliderwidget.find('UL').attr("title")) + 20 || 20;
					$configurator.hide(); // IE6 BUG WORKAROUND
					$sliderwidget.find('UL').attr("title", ""); // titel löschen
					$sliderwidget.css('height', _height);
					$slider.css('margin-top', _height-5);
					
					
					
					
					//var verticalOffset = offset.left;
					var topOffset = (offset.top + height/2)-($configurator.height()/2) + 3;
					$configurator
						.css('top', topOffset - $('DIV.product-information').offset().top) // position setzen
						.fadeIn('fast')
					.end();
					
					// den slider aktivieren
					$sliderwidget
						.attachConfSlider()
						.updateConfSliderContent()
					.end();
					
					
					///////////////////////////////////////
					// IE7 filter info abfrangen und setzen
					$configurator.removeClass('nofilter');
					$configurator.removeClass('hasfilter');
					if ($configurator.find('.filter').length) {
						$configurator.addClass('hasfilter');
						//$('BODY.browserIE7 DIV#configurator .slider.ui-slider').css('position','relative');
						//$('BODY.browserIE7 DIV#configurator .slider.ui-slider').css('bottom',"0px");
						$('BODY.browserIE7 DIV#configurator .slider.ui-slider').css('top', _height -23); 
						$('BODY.browserIE6 DIV#configurator .slider.ui-slider').css('top', _height -23); 
						//$('BODY.browserIE6 DIV#configurator .slider.ui-slider').css('margin-top',-_height);
					} else {
						$configurator.addClass('nofilter');
						$('BODY.browserIE7 DIV#configurator .slider.ui-slider').css('top', '45px'); 
						$('BODY.browserIE6 DIV#configurator .slider.ui-slider').css('top', '45px'); 
					}
					
					
					$.configurator.update();
				});
			},
			
			
			// produkt seitenbereich mit den ergebnissen der konfiguration aktualisieren
			updateProdukt: function(data) {
				// produkt seintenbereich mit ergebnisdaten aktualisieren
				$('.product-configurator').html(data);
				// thickbox für produktvergrösserung neu initialisieren
				tb_init('a.thickbox');
				// verhalten des konfigurators neu initialisieren
				$.configurator.init();
				// font replacements aktualisieren
				Cufon.refresh('BODY.page-product DIV.form-item A');
				Cufon.refresh('UL.menu LI');
				Cufon.refresh("h2:not(.node-title),h3");
				Cufon.refresh('BODY.page-product DIV.bubble-inner STRONG');
			},
			
			
			// verhalten der geladenen elemente aktualisieren
			update: function() {
				
				var popup = $(options.selector);
				var list = $('UL LI', popup);
				var link = $('A', list);
				
				/*
					klick event auf ein konfigurationselement innerhalb eines popups.
					schliesst das popup und läd das ergebnis der neuen konfiguration.
				*/
				link
					// tooltips aktivieren
					.tooltip()
					// klick event auf eines der geladenen elemente
					.click(function(event) {
						event.preventDefault();
						var $A = $(this);
						
						$.configurator.hide();
						layer.close();
						
						popup.fadeOut('fast', function(){
							var url;
							if ($.goin.defaults.local)
								url = "include/produkt-konfiguriert.html";//$.goin.defaults.ajaxConfigResultUrl;
							else 
								url = $A.attr('href');
							$.get(url, $.configurator.updateProdukt);
						});
						return false;
					});
				
				
				
				var $sliderwidget = $('.inner', popup);
				/*
					klick event auf die filter links einer konfigurationseinheit.
					filtert die elemente in einem konfigurator popup anhand der klassennamen.
				*/
				$('.filter A', popup).click(function(event) {
					event.preventDefault();
					var $this = $(this);
					// wenn der geklickte filter bereits aktiv ist nichts weiter tun
					if ($this.hasClass('active')) return;
					// andernfalls den zuvor aktiven filter zurücksetzen
					$this.parent().find('A').removeClass('active');
					var $items = list; //$(options.selector).find('UL LI');
					// sonderfall, wenn es sich um den show all filter handelt
					if ($this.hasClass('all')) {
						$items.stop().show();//'fast',function() { });
						clearTimeout(timer);
						timer = setTimeout(function(){
							clearTimeout(timer);
							$sliderwidget.updateConfSliderContent(); 
						},600);
						$this.addClass('active');
						return;
					}
					
					
					var filterClass = '.' + $this.attr('class');
					$items.each(function(index, obj) {
						var $L = $(this);
						$L[$L.is(filterClass) ? 'show' : 'hide']();//'fast'
						//if ($L.length == index) $sliderwidget.updateConfSliderContent(); 
					});
					
					
					clearTimeout(timer);
					timer = setTimeout(function(){
						clearTimeout(timer);
						$sliderwidget.updateConfSliderContent(); 
					},600);
					// geklickten filter aktiv setzen
					$this.addClass('active');
				});
				
				// wenn es sich um eine selectbox handelt
				if ($('.filter SELECT', popup).length) {
					$('.filter SELECT', popup).change(function(event) {
						
						event.preventDefault();
						var $this = $(this);
						
						var $items = list; //$(options.selector).find('UL LI');
						// sonderfall, wenn es sich um den show all filter handelt
						if ($this.val() == 'all') {
							$items.stop().show();//'fast'
							clearTimeout(timer);
							timer = setTimeout(function(){
								clearTimeout(timer);
								$sliderwidget.updateConfSliderContent(); 
							},500);
							return;
						}
						
						
						var filterClass = '.' + $this.val();//.attr('class');
						var amount = $items.length - 1;
						$items.each(function(index, obj) {
							var $L = $(this);
							$L[$L.is(filterClass) ? 'show' : 'hide']();//'fast'
							if (index >= amount) {
								clearTimeout(timer);
								timer = setTimeout(function(){
									clearTimeout(timer);
									$sliderwidget.updateConfSliderContent(); 
								},500);
							}
						});
						
					});
				}
				
				
			}
			
			
		}
	});
	
	$.fn.extend({
		configurator: function(options) {
			return this.each( function() {
				var $this = $(this);
			});
		}
	});
	

	/* init */
	$(function() {
		// konfigurator initialisieren
		$.configurator.init();
		// initiale hinweis box schliessen
		$('DIV.jq-nbx').click(function() { 
			$(this).fadeOut('fast',function() {
				$(this).remove();
			});
		});
		// workaround zur korrekten positionierung der hinweisbox innerhalb der html struktur
		$('DIV.main DIV.content DIV.jq-nbx').appendTo('DIV.container');
	});
})(jQuery);


/**
	Slider an vorgegebenes Element hängen
*/
jQuery.fn.attachConfSlider = function() { 
	return this.each(function() { 
		var $outer = jQuery(this);
		var $inner = $outer.find('UL');
		$outer.find('.slider').slider('destroy');
		//inner.after('<div class="slider"><div></div><div class="handle"><div></div></div></div>');
		var contentWidth = 0;
		$inner.find('LI').each(function() {
			contentWidth += $(this).width();
		});
		
		orgContentWidth = contentWidth;
		
		// panel breite und position
		$outer.width( contentWidth > 520 ? 520 : contentWidth + 11);
		$('DIV#configurator').css('margin-left', (contentWidth < 520) ? String( 198 + (520-(contentWidth + 11)) )+'px' : '198px');
		// IE browser fix
		$('BODY.browserIE7 DIV#configurator').css('margin-left', (contentWidth < 520) ? String( (520-(contentWidth + 11)) )+'px' : '0');
		$('BODY.browserIE6 DIV#configurator').css('margin-left', (contentWidth < 520) ? String( (520-(contentWidth + 11)) )+'px' : '0');
		$('BODY.browserIE7 DIV#configurator .cBt').css('width',$outer.width()+ 6);
		$('BODY.browserIE7 DIV#configurator .cBb').css('width',$outer.width()+ 6);
		$('BODY.browserIE6 DIV#configurator .cBt').css('width',$outer.width()+ 6);
		$('BODY.browserIE6 DIV#configurator .cBb').css('width',$outer.width()+ 6);
		
		 
		
		var handle_pw =($outer.width() / orgContentWidth) * 100;
		var handle_w = ($outer.width() / 100) * handle_pw;
		
		// container breite subtrahieren
		contentWidth = contentWidth - $outer.width();
		
		jQuery('.slider', $outer).slider({
			min: 0,
			max: contentWidth,
			handle: '.handle',
			stop: function (event, ui) {
				$inner.animate({'left': ui.value * -1}, 500);
			},
			slide: function (event, ui) {
				$inner.css('left', ui.value * -1);
			}
		});
	});
}

/**
	Aktualisierte Slider Inhalte neu berechnen 
*/
jQuery.fn.updateConfSliderContent = function() { 
	return this.each(function() { 
		var $outer = jQuery(this);
		var $inner = $outer.find('UL');
		var $slider = $outer.find('.slider');
		var contentWidth = 0;
		$inner.find('LI:visible').each(function() {
			contentWidth += jQuery(this).width();
		});
		orgContentWidth = contentWidth;
		ow = $outer.width();
		 // container breite subtrahieren
		contentWidth = contentWidth - ow;
		// wenn alle elemente bereits sichtbar ist kein slider nötig
		if (0 > contentWidth) {
			$slider.hide();
		} else {
			$slider.show();
			
			var handle_pw =(ow / orgContentWidth) * 100;
			var handle_w = (ow / 100) * handle_pw;
			$('.handle').width( handle_w > 30 ? handle_w : 30 );
			
		}
		
		$slider.data("max.slider", contentWidth); 
		//$slider.data("value.slider",0 ); 
		//$slider.slider("value",0 ); 
		//$slider.slider("option","value",0 ); 
		$slider.slider('moveTo',0,0);
		//$.goin.debug("DONE");
	});
}



