var gup = {
	
	/**
	 * Die init Funktion wird sofort nach dem laden der Seite aufgerufen und kann benutzt werden um wichtige Dinge zu initialisieren
	 */
	init : function() {
		var printNotices;
		var gupInit = gupInit || null;
		if( gupInit ) {
			for(var i=0, len=gupInit.length; i<len; i++) {
				gupInit[i]();
			}
		}
		
		gup.flyouts.init(); // Flyout Navi
		gup.initializeDropdown(); // Account Navi
		
		if($("a.gallerylink").length > 0) {
			LazyLoader.load(resourceUrl+"fancybox/jquery.fancybox-1.3.1.css");
			LazyLoader.load(resourceUrl+"fancybox/jquery.fancybox-1.3.1.pack.js", gup.initializeFancybox);
		}
		
                var cover1 = document.getElementById("coverflow-basketball"),
                    cover2 = document.getElementById("coverflow-motorsport");
		if(cover1 || cover2) {
			LazyLoader.load(resourceUrl+"uploadify/swfobject.js", function() {
                            cover1 && gup.initializeCoverflow("basketball");
                            cover2 && gup.initializeCoverflow("motorsport");
                        });
		}	
		
		if(document.getElementById("more-products-to-add")) {
			gup.initializeMultipleProductAdding("more-products-to-add");
		}
		
		printNotices = $(".print-notice");
		if(printNotices.length) {
			printNotices.each(function() {
				gup.initPrintNotice(this);
			});
		}
		
		gup.defaultValues(["f-search-param"]);
		
		// lade die gespeicherten Varianten in das gup Array
		gup.articleListVariants = window.articleListVariants || [];
		window.articleListVariants = null;
		gup.articleVariants = window.articleVariants || [];
		window.articleVariants = null;
	},
	
	/* Init des Coverflows in der Seite "Sportsponsoring" */
	initializeCoverflow : function(name) {
		var flashvars = {
			path: resourceUrl+"coverflow/",
                        xml: "data-"+ name +".xml",
			backgroundColor: "0x000000",
			labelColor: "0xFFFFFF"
		};
		var params = {
			loop: "false",
			menu: "false",
			quality: "best",
			scale: "noscale",
			salign: "tl"
		};
		var attributes = {
                    id: "coverflow-" + name,
                    name: "coverflow-" + name
                };
		swfobject.embedSWF(resourceUrl+"coverflow/coverflow.swf", "coverflow-"+name, "625", "235", "10.0.0", null, flashvars, params, attributes);
	},
	
	/* Objekt das die Flyout Navigation verwaltet */
	flyouts : {
		init : function() {
			$(".flyout").each(function() {
				var flyout = $(this);
				var parent = flyout.parent();
				var lists = flyout.find("ul").length;
				//var listsWidth = parseInt(flyout.find("ul:first").css("width"), 10); // --- fuer Opera-Fix rausgenommen
				var linkWidth = parseInt(flyout.prev().css("width"), 10);
				var arrow = flyout.find(".arrow-flyout");
				
				arrow.css("left", (linkWidth / 2 - 6) + "px");
				
				// Fix fuer Opera
				listsWidth = 154;
				var calcWidth = (lists * listsWidth + (lists - 1) * 10);
				//opera.postError("Width:" + calcWidth + " - lists:" + lists + " - listsWidth:" + listsWidth);

				flyout.css("width", calcWidth + "px"); /* 10px margin zwischen listen */
				
				parent.hover(function() {
					$(this).find("> a").addClass("flyout-hover");
					flyout.show();
				}, function() {
					$(this).find("> a").removeClass("flyout-hover");
					flyout.hide();
				});
			});
		}
	},
	
	/* defaultValues akzeptiert ein Array von ids von input Feldern
	   und setzt einen Standardwert wenn nichts eingegeben wird.
	   Bei Klick innerhalb des Inputs wird der Standardwert gelöscht und der
	   User kann selbst etwas eingeben */
	defaultValues : function(ids) {
		var curInput;
		for(var i=0, len=ids.length; i<len; i++) {
			curInput = $("#"+ids[i]);
			if(curInput.length) {
				curInput
					.data("value", curInput.attr("value"))
					.focus(function() {
						if(curInput.data("value") === this.value)
							this.value = "";
					})
					.blur(function() {
						if(this.value === '')
							this.value = $(this).data("value");
					});
			}
		}
	},
	
	/* Hier wird die Fancybox initialisiert */
	initializeFancybox : function() {
		$("a.gallerylink").fancybox({
			'overlayShow'		:  	true,
			'overlayOpacity'	:	0.7,
			'overlayColor'		:	'#000'									
		});
	},
	
	/* Init des Dropdowns für den Account */
	initializeDropdown : function() {
		$(".dropdown").next().click(function() {
			var $this = $(this);
			var dd = $this.prev();
			
			if(dd.is(":visible")) {
				$this.find("a").removeClass("active");
				dd.slideUp("normal");
			}
			else {
				$this.find("a").addClass("active");
				dd.slideDown("normal");
			}
			return false;
		});
	},
	
	/* diese Funktion erweitert die Detailseite damit man gleichzeitig mehrere Varianten eines Produktes in den Warenkorb
	   legen kann
	*/
	curAddingIndex: 0,
	initializeMultipleProductAdding: function(id) {
		gup.curAddingIndex = 0;
		var plusLink = $("#"+id);
		
		plusLink.click(function() {
			var index = ++gup.curAddingIndex;
			var nextEl = plusLink.next();
			var clone = nextEl.clone();
			
			clone
				.find(".amount-to-basket")
				.attr("name", "amounts["+index+"]")
				.attr("id", "amount"+index)
				.prev()
				.attr("for", "amount"+index);
				
			clone
				.find(".size")
				.attr("name", "sizes["+index+"]")
				.attr("id", "size"+index)
				.prev()
				.attr("for", "size"+index);
			
			nextEl.prepend('<span class="btn-small remove-additional-product"><a class="btn bigfs" href="#" title="diesen Posten löschen">&nbsp;&ndash;&nbsp;</a></span>');
				
			nextEl.find(".remove-additional-product").click(function() {
				$(this).parent().remove();
				return false;
			});
			
			nextEl.before(clone);
			
			clone.find(".amount-to-basket").val("").focus();
			
			return false;
		});
	},
	
	/* gib Meldung aus, falls ein Kunde vergisst den Aktualisieren Button zu drücken! */
	updateRequired: false,
	protectUpdates: function(formId, label, iconPath) {
		var updateButton = '<div class="upd-btns"><span class="btn-small"><a href="#" class="btn" title="'+label+'"><img src="'+iconPath+'" alt="refresh" class="btn-image"></a></span></div>',
			updateInput = '<input type="hidden" name="updateBtn" value="'+label+'">';
		
		var onUpdateClick = function() {
			$("#"+formId).submit();
			$(this).remove();
			return false;
		};
		
		$(".fld-amount input:text, .names-nr")
			.focus(function() {
				$(this).data("val", this.value);
			})
			.keyup(function() {
				var input = $(this);
				if(input.data("updateButtonShowed") !== true) {
					if(input.data("val") != this.value) {
						var offset = input.offset(),
							xPos = offset.left + input.outerWidth(),
							yPos = offset.top,
							xPosOffset, yPosOffset;
						
						gup.updateRequired = true;
						
						$(updateInput).appendTo("#"+formId);
						
						var btn = $(updateButton).appendTo("body").click(onUpdateClick);
						
						xPosOffset = input.hasClass("names-nr") ? -35 : 4;
						yPosOffset = input.hasClass("names-nr") ? input.outerHeight()+20 : 0;
						
						btn.css({
							left: xPos + xPosOffset + "px",
							top: yPos + yPosOffset + "px"
						})
						.fadeIn();
							
						input.data("updateButtonShowed", true);	
					}
				}
			});
			
			
		var onNextStep = function() {
			if(gup.updateRequired) {
				var msg = "<strong class='like-headline like-paragraph'>Bitte klicken Sie den \"aktualisieren\" Knopf, sonst gehen Ihre Änderungen verloren!</strong>";
				LazyLoader.load(resourceUrl+"fancybox/jquery.fancybox-1.3.1.css");
				LazyLoader.load(resourceUrl+"fancybox/jquery.fancybox-1.3.1.pack.js", function() {
					$.fancybox(msg, {
						'autoDimensions'	:	false,
						'width'				:	400,
						'height'			:	40,
						'overlayShow'		:  	true,
						'overlayOpacity'	:	0.7,
						'overlayColor'		:	'#000',
						'padding'			:	20
					});
				});
				return false;
			}
			return true;
		};
		$("#cart-navi-address").click(onNextStep);
		$("#nextstep").submit(onNextStep);
	},

	/* Varianten - Platzierung ein-/ausblenden */
	switchVariants : function(s,id) {
		var el, selectList,
			attrib = "display", showVal = "inline-block", hideVal = "none";
		
		for(var x=1; x<=(s=='v'?5:3); x++){
			el = document.getElementById(s + x);
						
			if(x<=id || id==4)
				el.style[attrib] = showVal;
				
			else{
				selectList = el.getElementsByTagName("select")[0];
				selectList.selectedIndex = 0; // reset
				gup.updatePrices(selectList); // update des Gesamtpreises
				el.style[attrib] = hideVal;
			}
		}
	},	
	
	/* Selectlisten - Bestimmten Eintrag anzeigen */
	/* id kann ein DOM Knoten oder ein ID String sein */
	changeListIndex : function(id, index) {
		var list;
		if( typeof id === "string" && (list = document.getElementById(id)) ) {
			list.selectedIndex = index >= list.options.length ? list.options.length-1 : index;
		}
		else if( id.nodeType && id.nodeType === 1 ) {
			id.selectedIndex = index >= id.options.length ? id.options.length-1 : index;
			list = id;
		}
		return list;
	},
	
	/* Plausibilitätsprüfung für die verschiedenen T-Shirt Bedruckungsvarianten */
	validateTShirtLayout : function() {
		var visibleLists = gup._getVisibleLists(document.getElementById("spnlogo")),
			msg = "<strong class='like-headline like-paragraph'>Folgende Fehler müssen Sie noch korrigieren:</strong><ul style='list-style:disc inside none;'>",
			error = false,
			liquiMolyLogo = false;
			logoCount = 0;
		for(var i=0, len=visibleLists.length; i<len; i++) {
			// wurden Platzierungen leer gelassen?
			//if( visibleLists[i].options[visibleLists[i].selectedIndex].value == "0" ) {
			//	msg += "<li>Es fehlt noch mindestens eine Platzierung!</li>";
			//	error = true;
			//}
			// ist mindestens ein Liqui-Moly Logo vorhanden?
			if( visibleLists[i].options[visibleLists[i].selectedIndex].text == "Liqui Moly Logo" ) {
				liquiMolyLogo = true;
				logoCount += 1;
			}
		}
		
		// sind für vorn und hinten Varianten ausgewählt worden?
		if( $("#spnlogo :radio:checked").length != 2 ) {
			msg += "<li>Bitte wählen Sie jeweils eine Variante für Vorne und Hinten aus!</li>";
			error = true;
		}
		
		if( !liquiMolyLogo ) {
			msg += "<li>Platzieren Sie das Liqui Moly Logo entweder vorn oder hinten!</li>";
			error = true;
		}
		
		if( logoCount > 1){
			msg += "<li>Sie dürfen maximal EIN LIQUI MOLY Logo platzieren!</li>";
			error = true;
		}
		
		if(error) {
			msg += "</ul>";
			LazyLoader.load(resourceUrl+"fancybox/jquery.fancybox-1.3.1.css");
			LazyLoader.load(resourceUrl+"fancybox/jquery.fancybox-1.3.1.pack.js", function() {
				$.fancybox(msg, {
					'autoDimensions'	:	false,
					'width'				:	390,
					'height'			:	80,
					'overlayShow'		:  	true,
					'overlayOpacity'	:	0.7,
					'overlayColor'		:	'#000',
					'padding'			:	20
				});
			});
			return false;
		}
		
		oxid.popup.load();
		return true;
	},
	// sucht alle Listen die im Augenblick nicht ausgeblendet sind
	_getVisibleLists : function(searchContainer) {
		var searchTarget = searchContainer || document.getElementById("content-main"),
			allLists = searchTarget.getElementsByTagName("select"),
			ret = [],
			attrib = "display", hideVal = "none";;
			
		for(var i=0, len=allLists.length; i<len; i++) {
			if( allLists[i].parentNode.style[attrib] != hideVal && allLists[i].parentNode.style[attrib] != "" ) {
				ret.push(allLists[i]);
			}
		}
		
		return ret;
	},
	
	/* Automatische Preisupdates bei Änderung der Bedruckungsvarianten */
	updatePrices : function(selectList) {
		var priceEl = document.getElementById("test_product_price_bottom"),
			actPrice, newPrice,
			add = gup._parsePrice(selectList.options[selectList.selectedIndex].text), // Preis der zum Gesamtpreis dazugerechnet werden soll
			remove; // Preis der vom Gesamtpreis weggerechnet werden muss, bevor der neu ausgewählte preis dazugerechnet werden kann
		
		remove = gup._updatedPrices.getAddedPriceFrom(selectList) || "+0,00"; // muss etwas weggerechnet werden?
		if( remove !== "+0,00" ) // drehe das vorzeichen um
			remove = gup._changeSign(remove);
		
		gup._updatedPrices.push({list: selectList, addedPrice: add}); // füge diese liste dem array hinzu
		
		// Berechnung des neuen Gesamtpreises
		if( priceEl ) {
			actPrice = gup._parsePrice(priceEl.innerHTML);
			
			newPrice = ("" + actPrice + remove + add).replace(/,/g, ".");
			newPrice = eval(newPrice);
			priceEl.innerHTML = gup._kaufm(newPrice) + " &euro;";
		}
	},
	_updatedPrices : [], // hier wird gespeichert welche liste schon mal genutzt wurde um den gesamtpreis zu berechnen
	_priceRegExp : /[+-]?([0-9]+)(\.|,)([0-9][0-9])/, // regulärer ausdruck um einen preis aus einem string zu extrahieren
	_parsePrice : function(strPrice) {
		var p = strPrice.match(gup._priceRegExp);
		return p ? p[0] : "+0,00";
	},
	_kaufm : function(x) { // kaufmännisches runden auf zwei stellen hinter dem komma
		var k = (Math.round(x * 100) / 100).toString();
		k += (k.indexOf('.') == -1)? '.00' : '00';
		var p = k.indexOf('.');
		return k.substring(0, p) + ',' + k.substring(p+1, p+3);
	},
	_changeSign : function(number) {
		var sign = number.substr(0,1);
		if(sign === "+")
			number = number.replace("+", "-");
		else if(sign === "-")
			number = number.replace("-", "+");
		return number;
	},
	
	// Varianten-Details mit AJAX laden
	loadVarDetails : function(url){
		if($.support.opacity)
			$('#content-main > *').css('opacity','0.5');
			
		$("#zoom").remove(); // lösche altes zoom bild
		
		$('#content-main').append('<img src="http://www.liqui-moly-teamshop.de/out/primoteamsport/img/ajax-loader.gif" width="31" height="31" id="ajaxloader"/>')
			.load(url + ' #content-main > *, #zoom',
				  null,
				  function(responseText){
					if($.support.opacity)
						$(this).find('> *').css('opacity','1');
						
					// binde neues zoom bild ein
					$(this).find("#zoom").appendTo("body");
					oxid.popup.addResizer('zoom_img','zoom',10,37);
					// zoomPics muss neu aufgebaut werden, weil inline-scripts rausgeschmissen werden
					curZoomKey = 1;
					$(".zoomPicTmp").each(function(i){
						var file = $(this).text(); 
						if(file.length)
							zoomPics[i+1] = file;
						});
					
					gup.initializeMultipleProductAdding("more-products-to-add");
					
				  });
	},

	// Tooltip für Variantenbild im Warenkorb
	imagePreview : function(){	
			
		var xOffset = 10;
		var yOffset = -190;

		$("a.preview").hover(function(e){
			this.t = this.title;
			this.title = "";
			var c = (this.t != "") ? "<br/>" + this.t : "";
			$("body").append("<p id='preview'><img src='"+ this.name +"' alt='Image preview' />"+ c +"</p>");								 
			$("#preview")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.fadeIn("fast");						
		},
		function(){
			this.title = this.t;	
			$("#preview").remove();
		});	
		$("a.preview").mousemove(function(e){
			$("#preview")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px");
		});			
	},
	
	// Inizialisiert einen Beflockungshinweis
	initPrintNotice : function(el) {
		var link = $('<a href="#" title="" class="print-notice-link"></a>'),
			xOffset = 10,
			yOffset = 10;
		el = $(el);
		
		// verstecken und link einfügen
		el
			.hide()
			.wrap(link)
			.css({
				position: "absolute",
				right: "-10px",
				top: "0px"
			});
		
		el.parent().hover(function() {
			$(this).find(".print-notice").fadeIn("fast");
		}, function() {
			$(this).find(".print-notice").fadeOut("fast");
		});
	},
	
	// WIRD NICHT MEHR BENÖTIGT---------------------------------------------------------------------------------------------------------------------
	// Variantenumschalten in der Artikelliste / Produktübersichtsseite)
	articleListVariants : [], // Array um alle Varianten zu speichern (wird in der init Methode gefüllt)
	updateProductDesc : function(selectId) {
		var articleListVariants = gup._getArticleListVariants(selectId),				// Hole alle Varianten eines bestimmten Produkts
			container = document.getElementById(articleListVariants.parentId),			// Containerknoten des Produkts
			selectList = document.getElementById(selectId),								// Dropdown der Varianten
			titleEl = getElementsByClass("h3", container, "strong")[0].firstChild,		// a-Tag im Titel
			artnumEl = getElementsByClass("value", container, "span")[0],				// span-Tag der Artikelnummer
			moreInfoEl = getElementsByClass("actions", container, "div")[0].firstChild,	// a-Tag des "mehr Info" Links
			pictureEl = getElementsByClass("picture", container, "a")[0],				// a-Tag des Bildes
			variant = articleListVariants.variantList[selectList.selectedIndex];		// Objekt mit allen Eigenschaften der ausgewählten Variante
		
		while( titleEl.nodeType === 3 ) // wenn es ein textknoten ist, nimm das folgende Element
			titleEl = titleEl.nextSibling;
			
		while( moreInfoEl.nodeType === 3 )
			moreInfoEl = moreInfoEl.nextSibling;
			
		titleEl.href = variant.link;
		titleEl.innerHTML = variant.title;
		artnumEl.innerHTML = variant.artnum;
		moreInfoEl.href = variant.link;
		pictureEl.href = variant.link;
	},
	_getArticleListVariants : function(selectId) {
		for(var i=0, len=gup.articleListVariants.length; i<len; i++) {
			if( gup.articleListVariants[i].selectId == selectId )
				return gup.articleListVariants[i];
		}
	}

};

/** 
 *  Script lazy loader 0.5
 *  Copyright (c) 2008 Bob Matsuoka
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 */
 
Array.prototype.indexOf = function(item, i) {
	i || (i = 0);
    var length = this.length;
    if (i < 0) i = length + i;
    for (; i < length; i++)
      if (this[i] === item) return i;
    return -1;
}

var LazyLoader = {}; //namespace
LazyLoader.timer = {};  // contains timers for scripts
LazyLoader.scripts = [];  // contains called script references
LazyLoader.load = function(url, callback) {
	// handle object or path
	var classname = null;
	var properties = null;
	
	var executeCallback = function() {
        LazyLoader.scripts.push(url);
        callback();
    };
	
	// make sure we only load once
	if (LazyLoader.scripts.indexOf(url) == -1) {
		// note that we loaded already
		LazyLoader.scripts.push(url);
		
		var script;
		if (url.indexOf('.js') != -1) {
			script = document.createElement("script");
			script.src = url;
			script.type = "text/javascript";
		} else if (url.indexOf('.css') != -1) {
			script = document.createElement("link");
			script.rel = "stylesheet";
			script.media = "screen";
			script.type = "text/css";
			script.href = url;
		} else {
			alert('unsupported lazy loading');
		}
		
		document.getElementsByTagName("head")[0].appendChild(script);  // add script tag to head element
	   
		// was a callback requested
		if (callback) {    
			// test for onreadystatechange to trigger callback
			script.onreadystatechange = function () {
				if (script.readyState == 'loaded' || script.readyState == 'complete') {
					callback();
				}
			}                            
			// test for onload to trigger callback
			script.onload = function () {
				callback();
				return;
			}
			// safari doesn't support either onload or readystate, create a timer
			// only way to do this in safari
			if (($.browser.webkit && !navigator.userAgent.match(/Version\/3/)) || $.browser.opera) { // sniff
				LazyLoader.timer[url] = setInterval(function() {
					if (/loaded|complete/.test(document.readyState)) {
						clearInterval(LazyLoader.timer[url]);
						executeCallback(); // call the callback handler
					}
				}, 10);
			}
		}
	} else {
			if (callback) { executeCallback(); }
	}
}


gup.init();

/**
 * Erweiterungen von Protoypen und ein paar Helferfunktionen
 */

// diese Funktion sucht im Array ob diese select-liste schon mal genutzt wurde um ein update des Gesamtpreises
// durchzuführen und gibt dieses update zurück
Array.prototype.getAddedPriceFrom = function(list) {
	var a;
	for(var i=0, len=this.length; i<len; i++) {
		if(this[i].list === list) {
			a = this[i].addedPrice;
			this.splice(i, 1); // entferne die liste wieder aus dem array
			return a;
		}
	}
	return false;
};

// searchClass = Klasse die gesucht wird
// (optional) node = Knoten innerhalb dessen gesucht werden soll
// (optional) tag = Tag des gesuchten Elements
function getElementsByClass(searchClass,node,tag) {
	var classElements = [];
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (var i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
