var $j = jQuery.noConflict();


var flh = {
	flashVersion: function() {
		if(navigator.plugins && navigator.plugins['Shockwave Flash']) {
			var s = navigator.plugins['Shockwave Flash'].description;
			return parseInt(s.match(/\d+/));
		}
		if(window.ActiveXObject) {
			try {
				var s = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
				return parseInt(s.GetVariable('$version').match(/\d+/));
			} catch(e) {}
		}
		return 0;
	},
	getHTML: function(movie, width, height, params) {
		var html = 	[
			'<embed src="~movie~" width="~width~" height="~height~" ~fparams~'
			+ ' type="application/x-shockwave-flash"'
			+ ' pluginspage="http://www.adobe.com/go/getflashplayer" />'
			,
			'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="~width~" height="~height~">'
			+ '<param name="movie" value="~movie~" />'
			+ '~fparams~'
			+ '</object>'
		];
		if(!movie.match(/\.swf\b/)) movie += ".swf";
		var useEmbed = navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length;
		var fparams = "";
		for(var p in params || {}) {
			if(useEmbed)
				fparams += p + '="' + params[p] + '" ';
			else
				fparams += '<param name="' + p + '" value="' + params[p] + '" />\n';
		}
		var h = useEmbed ? html[0] : html[1];
		return h.replace(/~(\w+)~/g, function($a, $b) { return eval($b); });
	},
	setHTML: function(elem, movie, width, height, params) {
		if(typeof(elem) == "string")
			elem = document.getElementById(elem);
		elem.innerHTML = flh.getHTML(movie, width, height, params);
	},
	writeHTML: function(movie, width, height, params) {
		document.write(flh.getHTML(movie, width, height, params));
	},
	fixHeight: function(element) {
		var hgt = element.offsetHeight;
		element.style.height = "100em";
		var ppe = element.offsetHeight / 100;
		var boxHeight = (hgt / ppe).toFixed(2);
		element.style.height  = boxHeight + "em";
		var c = 0;
		while(c++ < 1024 && element.offsetHeight > hgt) {
			boxHeight -= 0.01;
			element.style.height  = boxHeight + "em";
		}
	},
	hexColor: function(c) {
		if(c.match(/^rgb/)) {
			var m = c.match(/\d+/g);
			c = (m[0] << 16) | (m[1] << 8) | (m[2]);
		}
		if(!c.toString().match(/^#/))
			c = "#" + (c | 0x1000000).toString(16).substr(1);
		return c;
	},
	replaceHTML: function(element, fontSwf, fgColor, bgColor) {
		if(flh.flashVersion() < 7)
			return;
		fgColor = flh.hexColor(fgColor || 0);
		bgColor = flh.hexColor(bgColor || 0);
		var vars = [
			"text=" + encodeURIComponent(element.innerHTML),
			"fgColor=" + fgColor,
			"bgColor=" + bgColor
		];
		var p = {
			flashVars: vars.join("&"),
			align: "left",
			quality: "high",
			salign: "lt",
			bgcolor: bgColor,
			wmode: "opaque"
		}
		var h = flh.getHTML(fontSwf, "100%", "100%", p);
		return h;
	}
}





var App =
{
	formatPrice: function(n) {
		return n.toFixed(2).toString().replace(/\./g, ",");
	},
	calcSum: function(qty, price) {
		// price is either a sinlge number,
		// or block prices in form count1,value1,count2,value2 etc
		// where counts must be sorted ascending
		price = price.replace(/\s+/g, "");
		if(price.match(/^[0-9.]+$/)) {
			return App.formatPrice(qty * parseFloat(price));
		}
		price = price.split(",");
		for(var i = price.length - 2; i > 0; i -= 2) {
			if(qty >= parseInt(price[i]))
				break;
		}
		return App.formatPrice(qty * parseFloat(price[i + 1]));
	},
	qtyFieldChanged: function(fQty) {
		var qty  = parseInt(fQty.val()) || 1;
		fQty.val(qty);
		var fPrice = fQty[0].form.price;
		if(fPrice) {
			var sum = App.calcSum(qty, fPrice.value);
			var fSum = $j(".qsum", fQty.parent());
			if(fSum)
				fSum.html(sum);
		}
	},
	lame: function() {
		if($j.browser.msie && parseFloat($j.browser.version) < 7) return true;
		return false;
	}
}

var FancyTT =
{
	gap: -10,
	pos: function(e, obj) {
		return obj.css("left", e.pageX).css("top", e.pageY - obj[0].offsetHeight + FancyTT.gap);
	},
	init: function() {
		$j("a[rel]").each(function(e) {
			$j(this).removeAttr("title");
			$j(this).mouseover(function(e) {
				var o = $j(this.rel);
				if(!o[0])
					return;
				if(o.parent() != $j("body"))
					$j("body").append(o);
				FancyTT.pos(e, o.show());
				$j(this).mousemove(function(e) {
					FancyTT.pos(e, $j(this.rel));
				});
			});
			$j(this).mouseout(function(e) {
				$j(this.rel).hide();
			});
		});
	}
}

var LeistungsGraph = {
	init: function() {
		if(!$j("#aboutLgMap").length) return;
		$j("#aboutLgMap area").mouseover(function(e) {
			var s = this.id.split("_");
			$j("#aboutLgBox div").hide();
			$j("#algb_" + s[1]).show();
			$j("#aboutLgBox").show().stop().animate({ opacity: 1 });
			LeistungsGraph.pos(e);
		})
		$j("#aboutLgMap area").mouseout(function() {
			$j("#aboutLgBox").stop().animate({ opacity: 0 });
		})
		$j("#aboutLg").mousemove(function(e) {
			LeistungsGraph.pos(e);
		});
	},
	pos: function(e) {
		var o = $j("#aboutLg").offset();
		$j("#aboutLgBox").css("left", e.pageX - o.left).css("top", e.pageY - o.top + 5);
	}
}

var ServiceKomm =
{
	lock: false,
	speedIn: 80,

	init: function() {
		if(!$j("#eServiceKomm").length)
			return;
		$j("#eServiceKomm div").stop().hide();
		$j("#eServiceKomm h3").mouseover(function() {
			if(ServiceKomm.lock) return;
			ServiceKomm.lock = true;
			var p = $j(this).parent().find("div");
			$j("#eServiceKomm div").stop();
			p.slideDown(ServiceKomm.speedIn, function() {
				$j("#eServiceKomm div").stop().hide();
				$j("#eServiceKomm h3").removeClass("hover");
				p.show();
				p.parent().find("h3").addClass("hover");
				ServiceKomm.lock = false;
			});
		});
	}
}


var BookRotation = {
	width: 60,
	count: 7,
	speed: 250,
	timer: 0,

	init: function() {

		if(!$j("#ebrContent").length)
			return;

		$j("#ebrLeft").click(function() {
			var u = $j("#ebrContent ul");
			var c = BookRotation.count;
			u.animate({ left:-BookRotation.width * BookRotation.count },
				BookRotation.speed, "swing");
			while(c--)
				u.queue(function() {
					u.append(u.find("li:first"));
					u.dequeue();
				});
			u.queue(function() {
				u.css("left", 0);
				u.dequeue();
			});
		});
		$j("#ebrRight").mousedown(function() {
			var u = $j("#ebrContent ul");
			var c = BookRotation.count;
			u.css("left", -BookRotation.width * BookRotation.count);
			while(c--)
				u.queue(function() {
					u.prepend(u.find("li:last"));
					u.dequeue();
				});
			u.animate({ left:0 },
				BookRotation.speed, 'swing');
			u.queue(function() {
				u.css("left", 0);
				u.dequeue();
			});
		});
		$j("#ebrContent img").mouseover(function() {
			var id = '#' + this.id.replace(/img/, "div");
			var p = $j("#ebrPopup");
			var t = $j(this);
			var o = t.offset();

			p.find("div").hide();
			$j(id).show();

			p.css("left", o.left - $j("#gMain").offset().left);
			p.css("top", o.top + 2 + parseInt(t.css("height")));
			p.css("opacity", 1);
			p.stop().fadeIn(10);
		});
		$j("#ebrContent img").mouseout(function() {
			$j("#ebrPopup").stop().fadeOut(500);
		});
		$j("#ebrPopup").mouseout(function() {
			$j("#ebrPopup").stop().fadeOut(500);
		});
		$j("#ebrPopup").mouseover(function() {
			$j(this).stop().fadeIn(10);

		});
	}
}

var HistoryBar = {

	gap: 100,
	speed: 300,

	init: function() {
		if(!$j("#abhLeft").length)
			return;
		$j("#abhLeft").click(function() {
			var x = HistoryBar.adjust($j("#abhMid ul")[0].offsetLeft + HistoryBar.gap);
			$j("#abhMid ul").stop().animate({ left: x }, HistoryBar.speed, "swing");
		})
		$j("#abhRight").click(function() {
			var x = HistoryBar.adjust($j("#abhMid ul")[0].offsetLeft - HistoryBar.gap);
			$j("#abhMid ul").stop().animate({ left: x }, HistoryBar.speed, "swing");
		})
	},
	adjust: function(x) {
		var minx = $j("#abhMid").width() - $j("#abhMid ul").width();
		return Math.min(0, Math.max(x, minx));
	}
}



var QSearch =
{
	keyTimer: 0,
	keyDelay: 200,
	url: "",
	ajaxTimeout: 5000,
	showLoader: true,
	busy: false,
	lastEvent: "",

	cache: [],
	cacheSize: 6,

	enable: function(url, box, popup, results) {
		var o = {}
		for(var p in QSearch)
			o[p] = QSearch[p];
		o.url = url;
		o.box = box;
		o.popup = popup;
		o.results = results;

		$j(box).attr("autocomplete", "off");

		$j(box).keyup(function() { o.open()  });
		$j(document.body).click(function() { o.close() });
		$j(window).click(function() { o.close() });
		$j(popup).find(".closebox").click(function() { o.close(); return false; });

		return o;
	},
	open: function() {
		this.lastEvent = "key";
		if(!this.canOpen())
			return;
		clearTimeout(this.keyTimer);
		var me = this;
		this.keyTimer = setTimeout(function() { me.initRequest() }, this.keyDelay);
	},
	initRequest: function() {
		if(!this.canOpen())
			return;
		var val = $j(this.box).val().replace(/^\s+|\s+$/g, "");
		if(!val.length)
			return;
		this.ajaxQuery(val);
	},
	canOpen: function() {
		return !this.busy && this.lastEvent != "close";
	},
	setBusy: function(b) {
		this.busy = b;
		if(b)
			$j(this.box).addClass("wait");
		else
			$j(this.box).removeClass("wait");
	},
	ajaxQuery: function(val) {
		this.setBusy(1);

		var data = { ajax: 1 };
		data[$j(this.box).attr("name")] = val;

		var me = this;
		$j.ajax({
			url: this.url,
			cache: true,
			data: data,
			dataType: "html",
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				me.ajaxError(XMLHttpRequest, textStatus, errorThrown)
			},
			success: function(data, textStatus) {
				me.ajaxSuccess(data, textStatus);
			},
			timeout: QSearch.ajaxTimeout
		});
	},
	ajaxError: function(XMLHttpRequest, textStatus, errorThrown, searchStr, box, popup) {
		//alert(["ajax error", textStatus]);
		this.setBusy(0);
		this.close();
	},
	ajaxSuccess: function(data, textStatus) {
		this.setBusy(0);
		if(this.canOpen())
			this.show(data);
	},
	show: function(html) {
		$j(this.results).html(html);
		$j(this.popup).show();
	},
	close: function() {
		this.lastEvent = "close";
		$j(this.popup).hide();
	}
}


var GrayBooks = {
	initGroup: function(grp) {
		if(!$j("div." + grp).length)
			return;
		$j("div." + grp).hover(
			function() {
				$j("div." + grp + "On").hide();
				var id = this.id.replace(/egb_/, "egb_on_");
				$j("#" + id).css("top", $j(this).offset().top).show();
			},
			function() {
				$j("div." + grp + "On").hide();
			}
		);
		$j("div." + grp + "On").hover(
			function() { $j(this).show() },
			function() { $j(this).hide() }
		);
	},
	init: function() {
		GrayBooks.initGroup("eBoxGrayBook");
		GrayBooks.initGroup("eBoxGrayPbs");
	}
}


var HomePage = {
	init: function() {
		$j("div.homeAdBox").hover(
			function() {
				$j("div.homeAdPopup").removeClass("hover").hide();
				var id = this.id.replace(/^hadb_/, "hadp_");
				$j("#" + id).css("top", $j(this).offset().top).show();
			},
			function() {
				$j("div.homeAdPopup").hide();
			}
		);
		$j("div.homeAdPopup").hover(
			function() { $j(this).show() },
			function() { $j(this).hide() }
		);
		/*
		$j("div.gHomeBox").hover(
			function() { $j(this).addClass("hover") },
			function() { $j(this).removeClass("hover") }
		);
		*/
	}
}

var OneTwoThree = {
	boxDelay: 200,
	stepDelay: 5000,

	init: function() {
		//OneTwoThree.timer = setInterval(OneTwoThree.animate, OneTwoThree.stepDelay);
		$j(".slimbox > .but").click(function() {
			OneTwoThree.show($j(this).parent(), parseInt($j(this).text()) - 1);
			//clearInterval(OneTwoThree.timer);
			OneTwoThree.click = true;
		});
	},

	show: function(box, n) {
		$j(box).children(".but").removeClass("on");
		$j(box).children(".product").removeClass("on").hide();
		$j(box).children(".but:eq(" + n + ")").addClass("on");
		$j(box).children(".product:eq(" + n + ")").fadeIn(300, function() {
			$j(this).addClass("on");
		});
		$j(box)[0].pos = n;
	},

	animate: function() {
		OneTwoThree.all = $j.makeArray($j(".slimbox"));
		setTimeout(OneTwoThree.animateStep, 1);
	},

	animateStep: function() {
		var box = OneTwoThree.all.shift();
		if(!box || OneTwoThree.click)
			return;
		OneTwoThree.show(box, ((box.pos || 0) + 1) % 3);
		setTimeout(OneTwoThree.animateStep, OneTwoThree.boxDelay);
	}


}


$j(function() {

	FancyTT.init();

	$j("#gNavi li").hover(
		function() { $j(this).addClass("hover"); },
		function() { $j(this).removeClass("hover"); });
	if(!App.lame()) {
		$j("button").hover(
			function() { $j(this).addClass("hover"); },
			function() { $j(this).removeClass("hover"); });
	}

	$j("#sDetailsTabs > ul li").click(function() {
		var n = 0, o = this;
		try {
			$j("li", $j(o).parent()).each(function(e, p) {
				if(p == o) throw e;
				n++;
			});
		} catch(e) {}
		$j("#sDetailsTabs > ul li").removeClass("selected");
		$j(this).addClass("selected");
		$j(".sDetailsTabsContent").hide();
		$j(".sDetailsTabsContent:eq(" + n + ")").show();
	});
	$j("input.sQtyBtn").click(function(e) {
		var y = $j.browser.msie ? e.offsetY : (e.pageY - $j(this).offset().top);
		var midpos = 11;
		if(!isNaN(y)) {
			var f = $j(this).prevAll(":text");
			var n = (parseInt(f.val()) || 1) + ((y < midpos) ?  1 : -1);
			if(n < 1) n = 1;
			f.val(n);
			App.qtyFieldChanged(f);
		}
	});
	$j(".sQtyBox input").change(function(e) {
		App.qtyFieldChanged($j(this));

	});
	$j("#sSpecials div").hover(
		function() {
			$j(this).addClass("hover");
			if(App.lame())
				$j(".sPlistControl select").css("visibility", "hidden")
		},
		function() {
			$j(this).removeClass("hover");
			if(App.lame())
				$j(".sPlistControl select").css("visibility", "visible");
		}
	);
	$j("#kChangeAddress").click(function() {
		$j("#kAddressForm").show();
		return false;
	});
	$j("#gServiceBox a:first").click(function() {
		var box = $j("#gServiceBox ul");
		$j(this).toggleClass("on");
		$j(this).hasClass("on") ? box.show() : box.hide();
		return false;
	});
	$j("#sColorSelect img").click(function() {
		$j("#sColorSelectBox").val(this.title);
	});

	// patch 25.2.09 - kleine produktbilder verlinken
	// zeigt n-th Bild aus dem globalen PRODUKTBILDER Array
	// PRODUKTBILDER = ['url-fuer-hauptbild', 'url-fuer-zusatzbild-1', 'url-fuer-zusatzbild-2' usw]
	$j("#sDetailsImg").click(function() {
		$j("#sDetailsBigImg").show().find("img").attr("src", PRODUKTBILDER[0]);
		return false;
	});
	$j("#sDetailsViews img").click(function() {
		var e = this;
		$j("#sDetailsViews img").each(function(n) {
			if(e.src == this.src)
				$j("#sDetailsBigImg").show().find("img").attr("src", PRODUKTBILDER[n + 1]);
		});
		return false;
	});
	//ende



	$j("#sBuchZoom").click(function() {
		$j("#sBuchLeseprobe").show();
		return false;
	});
	$j("#sDetailsBigImg").click(function() {
		$j(this).hide();
		return false;
	});
	$j(".sLoginLink").click(function() {
		$j("#kLoginForm").toggle();
		$j("#kRegisterForm").toggle();
		return false;
	});
	$j(".closebox, .closeboxw").click(function() {
		$j(this).parent().hide();
		return false;
	});

	//QSearch.enable("dummies/_search.php", '#search_box', '#search_popup', "#sp_body");

	BookRotation.init();
	ServiceKomm.init();
	GrayBooks.init();
	HistoryBar.init();
	LeistungsGraph.init();
	HomePage.init();

	$j("#gBruttoNettoBox").click(
		function() { $j(this).toggleClass("on"); }
	);

	$j("div.schulungBox h3").toggle(
		function() { $j(this).parent().addClass("open") },
		function() { $j(this).parent().removeClass("open") }
	);

	$j("div.aboutKarriereList li h4").mouseover(
		function() {
			$j(this).parent().siblings().removeClass("open")
			$j(this).parent().addClass("open");
		}
	);

	$j("#emFaq li h4").click(function() {
		$j(this).parent().toggleClass("on");
	});

	$j("#gFaqBox li h3").click(function() {
		$j(this).parent().toggleClass("on");
	});

	$j("#gKalenderBox h3").click(function() {
		var t = $j(this).next("div");
		var h = t.children("p").is(":hidden");
		$j("#gKalenderBox p").hide();
		t.children("p")[h ? "show" : "hide"]();
	});

	$j("#aboutContactForm input[name=kontakt_art]").each(function() {
		if(this.checked)
			$j("#aboutContactType_" + this.value).show();
	});

	$j("#aboutContactForm input[name=kontakt_art]").click(function() {
		$j("#aboutContactType div").hide();
		$j("#aboutContactType_" + this.value).show();
	});

	$j("#searchAdd h2").click(function() {
		$j(this).parent().toggleClass("open");
	});

	OneTwoThree.init();


})