var log = function(s) { if(window.console) console.log.apply(console, arguments) }
var dir = function(s) { if(window.console) console.dir(s) }
var f = function(str) {
	var a = arguments;
	return str.replace(/\$([0-9])/g, function($0, $1) { return a[$1] });
};

(function () {
	var loc = location.href + "";
	
	var m = loc.match(/^(https?:\/\/)([^\/]+)(.*)$/);
	if(!m[3].match(/\/shop/))
		m[3] = "/shop" + m[3];

	if(!m[2].match(/\.home/))
		m[2] = "www.cosmopol-shop.com";
	
	var newloc = m[1] + m[2] + m[3];

	if(newloc != loc) {
		location.href = newloc;
		window.redir = 1;
	}
	
})();

var craster = function(page, fillMode)
{
	var fixTab = {
		top11:  "row=1 col=1",
		top12:  "row=1 col=2",
		top13:  "row=1 col=3",
		top21:  "row=2 col=1",
		top22:  "row=2 col=2",
		top23:  "row=2 col=3",
		
		stoerer: "row=-1 col=-2 colspan=1 rowspan=1",

		cats:   "row=2 col=1 colspan=1 rowspan=2",
		menu:   "row=1 col=4 rowspan=1 colspan=2",
		last:   "row=-1 col=-1 colspan=1 rowspan=1"
	};
	
	var SIZ = 155;
	var PAD = 3;
	
	var minCols = 5;
	var minRows = 3;

	var page = page || 1;
	
	if(page < 1) {
		page = Cosmopol.lastPage;
	}
	Cosmopol.lastPage = page;
	
	var timer = 0;
	var aniQue = [];
	var aniLen = 0;
   
	var calcFixed = function() {
		var f = [];

		$(".fix").each(function() {
			var t = {}
			fixTab[$(this).attr("id")].replace(/(\w+)=([+-]?\d+)/g, function($0, $1, $2) {
				t[$1] = parseInt($2) || 1;
			});
			if(!t.rowspan) t.rowspan = 1;
			if(!t.colspan) t.colspan = 1;
		   
			f.push({row: t.row, col: t.col, p: $(this)});
			
			$(this).css({
				width:  t.colspan * SIZ + (t.colspan - 1) * PAD,
				height: t.rowspan * SIZ + (t.rowspan - 1) * PAD
			});
		   
			for(var r = 1; r <= t.rowspan; r++)
				for(var c = 1; c <= t.colspan; c++)
					if(r > 1 || c > 1)
						f.push({row: t.row + r - 1, col: t.col + c - 1, p: 'none'});
		});
		return f;
	}
   
	var dummy = function(nDummy, title ) {
		var t = (title || "DD") + nDummy;
		t = "";
		if(!$("#dummy_" + nDummy).size()) {
			$("#main_content").append("<div id='dummy_" + nDummy + "' class='dummy'>" + t + "</div>");
		}
		return $("#dummy_" + nDummy);
	}
	
	var qanimate = function() {
		if(!aniQue.length)
			return;
		var p = aniQue.pop();
		aniLen *= 0.9
		var r = $(p[0]);
		r.animate(p[1], aniLen, qanimate);
	}
   

	var qanimateFast = function() {
		for(var i = 0; i < aniQue.length; i++) {
			var p = aniQue[i];
			var r = $(p[0]);
			r.css(p[1]);
		}
	}


	var layout = function(width, height) {
		var boxes = $(".box.show");
		var boxSize = SIZ + PAD;

		// geometry row, col
		var maxCol = Math.max(minCols, Math.floor(width / boxSize));
		var maxRow = Math.max(minRows, Math.floor(height / boxSize));

		var fixed = calcFixed();
	   
		// look if there's overflow for fixed
		$.each(fixed, function() {
			if(this.row > +maxRow) maxRow = +this.row;
			if(this.row < -maxRow) maxRow = -this.row;
			if(this.col > +maxCol) maxCol = +this.col;
			if(this.col < -maxCol) maxCol = -this.col;
		});

		var table = [];

		// place fixed elements
		$.each(fixed, function() {
			if(this.row < 0) this.row += maxRow + 1;
			if(this.col < 0) this.col += maxCol + 1;
			var i = (this.row - 1) * maxCol + this.col - 1;
			table[i] = this.p;
		});
	   
		$(".box, .fix, .dummy").each(function() {
			this.loc = null;
		});
	   
		var numCells = (maxRow * maxCol) - fixed.length;
		var numBoxes = boxes.size();
		var startPos = (page - 1) * numCells;
		
		if(fillMode && startPos > numBoxes - numCells)
			startPos = numBoxes - numCells;
		if(startPos < 0)
			startPos = 0;
		
		var numPages = Math.ceil(numBoxes / numCells);
		var curPage = Math.ceil(startPos / numCells);

		var blist = boxes.get(), pos = startPos, nDummy = 0;
	   
		for(var i = 0; i < maxRow * maxCol; i++) {
			if(table[i] === "none")
				continue;
			if(!table[i]) {
				table[i] = blist[pos++] || dummy(nDummy++);
			}
			var r = Math.floor(i / maxCol);
			var c = i % maxCol;
			$(table[i])[0].loc = ({
				left: c * boxSize,
				top:  r * boxSize
			});
		}

		aniQue = [];
		$(".box, .fix, .dummy").each(function() {
			var pos = { left: parseInt($(this).css("left")), top: parseInt($(this).css("top")) }
			var loc = this.loc;

			if(!loc && pos.top < 0) {
				return;
			}
			if(!loc) {
				loc = { left: pos.left, top: -300 }
				$(this).css({ top: -300}); // dont animate removed boxes
				return; 
			}
			if(pos.left == loc.left && pos.top == loc.top) {
				return;
			}
			if(pos.top < 0) {
				// new box
				$(this).css({
					left: loc.left,
					top: loc.top - 190
				});
			}
			aniQue.push([this, loc]);
		});
		
		aniLen = 1000 / aniQue.length
		//qanimate();
		qanimateFast();
	   
		
		//log([numCells, numPages, curPage]);
	   
		if(numPages < 2) {
			$("#pagenav, #pager").hide();
		} else {
			var loc = location.href.replace(/page(\d+)/g, "").replace(/\/$/, "");
			
			if(!loc.match(/#/))
				loc += "/#";
			if(!loc.match(/\/$/))
				loc += "/";
				
			var s = [];
			
			var prev = "", next = "";
			var len = 2;
			var first = Math.max(0, curPage - len);
			
			for(var i = 0; i < numPages; i++) {
				var href = i > 0 ? (loc + "page" + (i + 1)) : (loc);
				// s.push(i == curPage ? 
				// 	f("<b>$1</b>", i + 1) : 
				// 	f("<a href='$1'>&nbsp;$2&nbsp;</a>", href, i + 1)
				// );
				s[i] = href;
				
				if(i == curPage - 1) prev = href;
				if(i == curPage + 1) next = href;
				
			}
			
			//var nn = s.length;
			//if(nn > 5)
			//	s = [s[0], s[1], s[2], '...', s[nn - 3], s[nn - 2], s[nn - 1]];
			//$("#pager").html(s.join(" "));
			
			$("#pager input").val(curPage + 1);
			$("#pager span").html(numPages);
			
			if(prev.length)
				$("#pagenav a.prev").addClass("active").attr("href", prev);
			else
				$("#pagenav a.prev").removeClass("active").removeAttr("href");

			if(next.length)
				$("#pagenav a.next").addClass("active").attr("href", next);
			else
				$("#pagenav a.next").removeClass("active").removeAttr("href");
			$("#pagenav, #pager").show();
			
			$("#pager input").unbind().keyup(function(e) {
				var n = (parseInt(this.value.replace(/\D/g, '')) || 1) - 1;
				var loc = s[n];
				if(loc && loc != location.href)
					location.href = loc;
			});
			
			
		}
	   
		$("#main_content").css({
			width:	maxCol * boxSize + PAD,
			height: maxRow * boxSize + PAD
		});
	}

	layout(
		$(window).width() - 10, 
		$(window).height() - 80
	);

	$("#cats").show();

	
	
	
}


var Cosmopol = 
{
	zoomRemove: function() {
		$("#zoomBox, #zoomOver").remove();
	},
	
	
	zoomInit: function(bigImg) {
		Cosmopol.zoomRemove();
		
		if(!(bigImg + "").length) return;
	
		$("body").append("<div id='zoomBox'></div>");
		$("#zoomBox").css({visibility:"hidden"}).html("<img src='" + bigImg + "'/>");
		$("body").append("<div id='zoomOver'></div>");
		$("#zoomOver").css({opacity:0});
	
		$("#zoomBox img").load(function() {

			var cw = $("#zoomBox").width();
			var ch = $("#zoomBox").height();
			var zw = $("#zoomBox img").width();
			var zh = $("#zoomBox img").height();
			
			var img = $(".prodimg img");
			
			var iw = img.width();
			var ih = img.height();
			var ix = img.offset().left;
			var iy = img.offset().top;

			$("#zoomOver").css({left: ix, top: iy, width: iw, height: ih});
			
			var zb = $("#zoomBox")[0].style;
			var zi = $("#zoomBox img")[0].style;
			
			
			$("#zoomOver").mousemove(function(e) {
				var x = e.pageX;
				var y = e.pageY;
				
				zb.left = (x - (cw >> 1)) + "px";
				zb.top  = (y - (ch >> 1)) + "px";
				zb.visibility = "visible";

				zi.left = (((x - ix) / iw) * -(zw - cw)) + "px";
				zi.top  = (((y - iy) / ih) * -(zh - ch)) + "px";
			});
			$("#zoomOver").mouseleave(function(e) {
				$("#zoomBox").css({visibility: "hidden"});
			});
		});
	},
	
	showPopup: function(sel) {
		$("#dark").css("zIndex", 99).show();
		return $(sel).css("zIndex", 100).show();
	},
	
	
	socialLinksUpdate: function(url, title) {
		var urlR = encodeURIComponent(url);
		url = encodeURIComponent(url.replace(/#\//, ""));
		title = encodeURIComponent(title);
		
		var i = 0;
		$("#social1 div a").each(function() {
			this.href = (Cosmopol.socialLinks[i++] || "").replace(/_uuu_/g, url).replace(/_ttt_/g, title).replace(/_uuu#_/, urlR)
		});
		var i = 0;
		$("#social2 div a").each(function() {
			this.href = (Cosmopol.socialLinks[i++] || "").replace(/_uuu_/g, url).replace(/_ttt_/g, title).replace(/_uuu#_/, urlR)
		});
		var i = 0;
	},
	
	applyUrl: function(url) {
		var m;
		
		Cosmopol.zoomRemove();
		
		$("#cats ul li").removeClass("active");
		$("#menuitems p").removeClass("active");
		$("#dark").hide();
		$(".popup").hide();
		$(".findus .off").show();
		$(".findus .on").hide();
		$("#searchform :input").removeClass("disabled").removeAttr("disabled");
		
		Cosmopol.socialLinksUpdate("http://www.cosmopol-shop.com/shop", "Cosmopol: entdecke die Welt");
		
		
		if(!url.length)
			return false;
		
		
		if(m = url.match(/search\/(.+)/)) {
			var u = decodeURI(m[1]);
			u = u.replace(/\+/g, " ");
			u = u.replace(/\//g, "");
			$("#searchform input").val(u);
			return false;
		}
		
		if(url.match(/newsletter/)) {
			Cosmopol.showPopup("#newsletter_popup");
			$("#menu_newsletter").addClass("active");
			$("#newsletter_popup form").unbind().submit(function() {
				var v = $(this).find(":text").val();
				if(v.match(/@/))
					$("#newsletter_response").showLoader('white').load("?" + $(this).serialize());
				return false;
			});
			return true;
		}
		
		if(url.match(/abmelden/)) {
			Cosmopol.showPopup("#abmelden_popup");
			$("#menu_newsletter").addClass("active");
			$("#abmelden_popup form").unbind().submit(function() {
				var v = $(this).find(":text").val();
				if(v.match(/@/))
					$("#abmelden_response").showLoader('white').load("?" + $(this).serialize());
				return false;
			});
			return true;
		}
		
		if(url.match(/catalog/)) {
			var p = Cosmopol.showPopup("#prod_popup").find("div.content").showLoader("white");
			setTimeout(function() { 
				p.load(url + "?ajax=1", function() {
					Cosmopol.zoomInit(window.zoomBigImg);
					Cosmopol.socialLinksUpdate(location.href, $(this).find("h2").text());
				})
			}, 100);
			return true;
		}
		if(url.match(/checkout/)) {
			var p = Cosmopol.showPopup("#cart_popup").find("div").showLoader("white");
			setTimeout(function() { p.load(url + "?ajax=1&back=" + escape(location.href)) }, 100);
			$("#menu_cart").addClass("active");
			return true;
		}
		if(m = url.match(/category\/(\d+)/)) {
			$(".box").removeClass("show");
			$(".box.c" + m[1]).addClass("show");
			
			var cm = $("#cats ul a[rel=" + m[1] + "]");
			cm.parent().addClass("active");
			setTimeout(function() { Cosmopol.setTop(
				m[1], 
				cm.html(),
				false,
				/region/i.test(cm.parent().parent().closest("li").find("a").html())
			) }, 500);
			Cosmopol.emptySearch();
			return true;
		}
		if(m = url.match(/region\/(.+)/)) {
			var p = Cosmopol.showPopup("#region").find("div").showLoader("white");
			setTimeout(function() { 
				p.load("/shop/?ajax=1&region=" + m[1], function() { Cosmopol.regionInfoLoaded(m[1])})
			}, 100);
			return true;
		}
		if(url.match(/promo/) && $("#promo_popup").size()) {
			var p = Cosmopol.showPopup("#promo_popup").find("div").showLoader("white");
			setTimeout(function() { 
				p.load("/promo/index.php")
			}, 1000);
			return true;
		}

		if(m = url.match(/filter(.*)/)) {
			var filter = Cosmopol.parseFinderQuery(m[1]);
			Cosmopol.applyFinder(filter);
			return true;
		}

		if(m = url.match(/finder(.*)/)) {
			$(".findus .off").hide();
			$(".findus .on").show();

			Cosmopol.emptySearch();
			var filter = Cosmopol.parseFinderQuery(m[1]);

			$("#finder").show();
			
			if(!Cosmopol.finderLoaded) {
				$("#finder").load("/shop/?finder", function() {
					Cosmopol.initFinder(filter);
				});
				Cosmopol.finderLoaded = true;
			} else {
				Cosmopol.initFinder(filter);
			}

			$("#searchform :input").addClass("disabled").attr("disabled", "disabled");


			Cosmopol.applyFinder(filter);
			return true;
		}
		
	
		return false;
	},
		
	regionInfoLoaded: function(regionId) {

		var byCat = {}, byLand = {}, total = 0;
		var regionName = $("#cats a[rel=" + regionId + "]").text();
		
		$(".box").each(function() {
			var t = $(this);
			if(!t.hasClass("c" + regionId))
				return;
			total++;
			t.attr("className").replace(/c(\d+)/g, function($0, $1) {
				var id = parseInt($1);
				if(id == regionId || id == 2 || id == 30)
					return;
				byCat[id] = byCat[id] ? byCat[id] + 1 : 1;
			});
			var land = t.find(".land").text();
			if(land.length)
				byLand[land] = byLand[land] ? byLand[land] + 1 : 1;
		});
		
		$("#region_prod_region").html(f(
			"<a href='/shop/#/category/$1'>$2 ($3)</a>",
			regionId, regionName, total
		));
		
		var buf = [];
		for(var catId in byCat) {
			var txt = $("#cats a[rel=" + catId + "]").text();
			if(txt.length)
				buf.push(txt + "--" + catId);
		}
		var html = [];
		$.each(buf.sort(), function() {
			var p = this.split("--")
			html.push(f("<a href='/shop/#/filter/region=$1/category=$2'>$3 ($4)</a>",
				regionId, p[1], p[0], byCat[p[1]]));
		});
		$("#region_prod_cats").html(html.join(", "));


		var buf = [];
		for(var land in byLand) {
			buf.push(land);
		}
		var html = [];
		$.each(buf.sort(), function() {
			html.push(f("<a href='/shop/#/search/$1'>$1 ($2)</a>",
				this, byLand[this]));
		});
		$("#region_prod_land").html(html.join(", "));

		$(".region_name").html(regionName);
		
		var s = regionName.toLowerCase().replace(/\W+/g, "_");
		var m = s + "@cosmopol-shop.com";
		$("#region_mailto").attr("href", "mailto:" + m).text(m);
	},
		
		
	prevTop: -1,
	
	initFinder: function(filter) {
		
		var priceMax, price, dragging;
		
		function klassOn(cls) {
			if(!filter.klassList)
				return false;
			for(var i = 0; i < filter.klassList.length; i++)
				if(filter.klassList[i] == cls)
					return true;
			return false;
		}
		
		function updatePriceSlider() {
			price[0] = Math.min(priceMax, Math.max(price[0], 0));
			price[1] = Math.min(priceMax, Math.max(price[1], 0));
			
			if(price[0] > price[1])
				price[1] = price[0];
				
			var gap = 0;
			if(price[0] > price[1] - gap)
				price[0] = price[1] - gap;
			if(price[0] < 0) {
				price[0] = 0;
				price[1] = gap;
			}

			if(price[0] < 0 || price[1] < 0)
				price = [0, 0];

			$("#finder_price_0").text(price[0]);
			$("#finder_price_1").text(price[1]);
			
			var w = 196; //$("#regler div").width();
			
			var ax =  Math.floor(price[0] * w / priceMax);
			var bx =  Math.floor(w - (price[1] * w / priceMax));
			
			var pad = 5;
			if(ax >= w - pad) ax = w - pad;
			if(bx >= w - pad) bx = w - pad;
			
			$("#regler a.left").css('left', ax);
			$("#regler a.right").css('right', bx);
		}
		
		function dragPriceSlider(obj, index, e) {
			var x = e.pageX - obj.parent().offset().left;
			price[index] = Math.round(priceMax * (x / obj.parent().width()));
			updatePriceSlider(price)
		}
		
		function populateCatList(crit, from, to) {
			var html = [];
			$(from).each(function() {
				var a = $(this).find("a"), m = a.attr("href").match(/category\/(\d+)/);
				if(m)
					html.push(f("<li><a href='#$1' rel='$2'>$3</a></li>", crit, "c" + m[1], a.html()));
			});
			$(to).find("ul").remove();
			$(to).append("<ul>" + html.join("\n") + "</ul>");
		}
		
		function execFinder() {
			var f = {};
			
			
			$(".finder_sub").each(function() {
				var a = $(this).find("ol a");
				if($(this).find("ul a.on").size() > 0)
					a.removeClass("on");
				else
					a.addClass("on");
			})

			$("#popfind").find("a[rel].on").each(function() {
				var a = $(this), r = a.attr("href").substr(1);
				if(!f[r])
					f[r] = [];
				f[r].push(a.attr("rel").replace(/^(c|zg)/, ""));
			});

			if(price[0] > 0 || price[1] < priceMax)
				f.preis = [price[0] + "-" + price[1]];

			var url = [];
			for(var p in f)
				url.push(p + "=" + f[p].join(","))
			url = "#/finder/" + url.join("/");

			location.href = location.href.replace(/#.*/, '') + url;
			return;

			// var f = Cosmopol.parseFinderQuery(url);
			// Cosmopol.applyFinder(f);
			// craster(0);
			// $("#counter span").text($(".box:visible").length);

		}
		
		function showTab(id) {
			$("#popfind h2").removeClass("on");
			Cosmopol.finderActiveTabId = id;

			$("#popfind > div").each(function() {
				$(this).stop();
				if($(this).attr("id") != id) 
					return $(this).hide();
				if($.browser.msie)
					$(this).show();
				else
					$(this).stop().show().css({opacity:0}).animate({opacity:1}, 500);
				$(this).prev("h2").addClass("on");
			});
		}

		populateCatList("region", "#cats ul > li:eq(0) li", "#regio");
		populateCatList("category", "#cats ul > li:eq(1) li", "#catego");
		
		$.each(filter.klassList || [], function() {
			$("#popfind").find("a[rel='" + this + "']").addClass("on")
		});
		
		priceMax = 0;
		$(".box").each(function() {
			priceMax = Math.max(priceMax, Math.ceil(Cosmopol.getPrice($(this))));
		});

		price = filter.price || [0, priceMax];
		
		dragging = false;

		$().mouseup(function() {
			$().unbind("mousemove");
			if(dragging)
				execFinder();
			dragging = false;
		});
	
		$("#regler div a").mousedown(function(e) {
			var p = $(this), n = p.hasClass("left") ? 0 : 1;
			dragging = true;
			$().unbind("mousemove").mousemove(function(e) {
				dragPriceSlider(p, n, e);
			});
			e.preventDefault();
			return false;
		});
		
		$("#popfind").find("a[rel]").unbind().click(function() {
			$(this).toggleClass("on");
			execFinder();
			return false;
		});
		
		$("#popfind").find(".all").click(function() {
			$(this).parent().find("a").removeClass("on");
			execFinder();
			return false;
		});

		$("#popfind h2").mouseover(function() {
			if($(this).hasClass("on"))
				return;
			var p = $(this).next("div");
			showTab(p.attr("id"));
		});
		
		$(".closer").click(function() {
			Cosmopol.reset();
			
		})
		
		showTab(Cosmopol.finderActiveTabId || "finder_price")
		
		updatePriceSlider();
		//execFinder();
	},
	
	
	getTopImageNumber: function(s) {
		var imgs = [32, 33, 37, 38, 39, 40, 41, 42, 43, 44];
		for(var i = 0; i < imgs.length; i++)
			if(parseInt(s) == imgs[i])
				return imgs[i];
		return imgs[Math.floor(Math.random() * imgs.length)];
	},
	
		
   	setTop: function(s, text, dontAnimate, isRegion) {
		if(!text) text = "Entdecke die Welt";
		if(!text.match(/\s/)) text = "<br>" + text;
		$("#top12 h1").html(text);
		$("#top12 a").hide();
		
		if(isRegion)
			$("#region_link_" + s).show().
				attr("href", "#/region/" + s).
				html("Infos zur Region");
		
	
		s = Cosmopol.getTopImageNumber(s);
		if(s == Cosmopol.prevTop)
			return;
		Cosmopol.prevTop = s;
		
		if(dontAnimate) return;
		
		var a = [11, 13, 22, 22, 23];
		$.each(a, function() {
			if($.browser.msie) {
				$("#top" + this + " span").css("backgroundImage", f("url('/a5/img/tops/$1/$2.jpg')", s, this));
				return;
			}
			var div = $("#top" + this);
			div.append("<span></span>");
			div.find("span:last").css("backgroundImage", f("url('/a5/img/tops/$1/$2.jpg')", s, this)).hide().fadeIn("slow", function() {
				$(this).parent().find("span:first").remove();
			});
		});
	},
	
	searchTimer: 0,

	getPrice: function(box) {
		return parseFloat(box.find(".price").text().replace(/,/, ".").replace(/[^\d.]/g, ""));
	},

	matches: function(box, filter) {
		if(filter.price) {
			var p = Cosmopol.getPrice(box);
			if(p < filter.price[0] || p > filter.price[1])
				return false;
		}

		if(filter.klassRe) {
			var cls = box.attr("className");
			for(var i = 0; i < filter.klassRe.length; i++)
				if(!filter.klassRe[i].test(cls))
					return false;
		}

		return true;
		
		
	},

	emptySearch: function() {
		$("#searchform input").val("");
	},

	applySearch: function() {
		var s = $.trim($("#searchform input").val().toLowerCase().replace(/[\s\'\",.?!-]/g, " "));
		if(!s.length) {
			$(".box").addClass("show");
		} else {
			var s = s.split(" "), c = s.length;
			$(".box").removeClass("show");
			$(".box").each(function() {
				var t = $(this).find("input").val();
				for(var i = 0; i < c; i++)
					if(t.indexOf(s[i]) < 0)
						return;
				$(this).addClass("show");
			});
		}
	},
	
	doSearch: function() {
		$("#cats ul li").removeClass("active");
		location.href = (location.href + "").replace(/#.*/g, "#");
		Cosmopol.applySearch();
		craster(0);
		Cosmopol.setTop(0, "", true);
	},
	
	applyFinder: function(filter) {
		if(!filter)
			return $(".box").addClass("show");
		$(".box").removeClass("show");
		$(".box").each(function() {
			if(Cosmopol.matches($(this), filter))
				$(this).addClass("show");
		});
		$("#counter span").text($(".box:visible").length);
		craster(0);
		
	},
	
	parseFinderQuery: function(url) {
		var url = $.trim(url);
		var m = url.match(/\w+=[^\/]+/g);
		if(!m)
			return {};
		var filter = {
			klassList: [],
			klassRe: [],
			price: []
		}
		for(var i = 0; i < m.length; i++) {
			var s = m[i].split("=");
			switch(s[0]) {
				case "preis":
					var s = (s[1] + "-0").split("-");
					s[0] = parseInt(s[0]) || 0;
					s[1] = parseInt(s[1]) || 0;
					if(s[0] > 0 || s[1] > 0)
						filter.price = (s[0] < s[1]) ? [s[0], s[1]] : [s[1], s[0]];
					break;
				case "category":
				case "region":
					var s = s[1].split(","), c = [];
					for(var j = 0; j < s.length; j++)
						c.push("c" + s[j]);
					filter.klassList = filter.klassList.concat(c);
					filter.klassRe.push(new RegExp("\\b(" + c.join("|") + ")\\b"));
					break;
				case "fuer":
					var s = s[1].toLowerCase().split(","), c = [];
					for(var j = 0; j < s.length; j++)
						c.push("zg" + s[j]);
					filter.klassList = filter.klassList.concat(c);
					filter.klassRe.push(new RegExp("\\b(" + c.join("|") + ")\\b"));
					break;
				case "stock":
					var c = ["st" + parseInt(s[1])];
					filter.klassList = filter.klassList.concat(c);
					filter.klassRe.push(new RegExp("\\b(" + c.join("|") + ")\\b"));
					break;
				case "pc":
					var c = ["pc" + s[1]];
					filter.klassList = filter.klassList.concat(c);
					filter.klassRe.push(new RegExp("\\b(" + c.join("|") + ")\\b"));
					break;
			}
		}
		for(var p in filter)
			if(!filter[p].length)
				delete filter[p];
		return filter;
	},
	
	currLoc: '',
	prevLoc: '',
	lastLoc: '',


	canonLocation: function(loc) {
		loc = loc.replace(/^.+?\/\//, "");
		loc = loc.replace(/\/.+/, "");
		loc = loc.replace(/^www\./, "");
		
		if(!loc.match(/\.home/))
			loc = "www." + loc;
		return "http://" + loc + "/#/";
	},

	checkLocation: function() {
		var loc = location.href + "";
		
		if(loc == Cosmopol.lastLoc)
			return
		
		Cosmopol.lastLoc = loc;
		
		var newloc = loc;

		newloc = newloc.replace(/^https/, "http");
		if(!newloc.match(/#/)) {
			if(!newloc.match(/\/$/))
				newloc += "/";
			newloc += "#/";
		}
		
		if(!newloc.match(/\.home/)) {
			var m = newloc.split("//");
			if(m[1] && !m[1].match(/^www/))
				newloc = m[0] + "//www." + m[1];
		}
		
		if(newloc != loc) {
			location.href = newloc;
			return;
		}
		
		if(loc == Cosmopol.currLoc)
			return;
			
		var m = loc.match(/page(\d+)/);
		var page = m ? parseInt(m[1]) : 1;

		Cosmopol.prevLoc = Cosmopol.currLoc.length ? Cosmopol.currLoc : '';
		Cosmopol.currLoc = loc;

		var url = Cosmopol.currLoc.replace(/#\//g, "");
		url = url.replace(/page\d+/g, "");

		url = url.replace(/\?bid=.+/g, "");

		var ok = Cosmopol.applyUrl(url);
		if(!ok) {
			Cosmopol.applySearch();
			setTimeout(function() { Cosmopol.setTop(0) }, 500);
		}
		
		craster(page);
		Cosmopol.updateCartCount();
	},
	
	updateCartCount__: function() {
		$.get("checkout/cart/?countonly=1", function(s) {
			var m = s.match(/--(\d+)--/);
			$("#menu_cart b").html(m ? m[1] : '');
		});
	},
	
	updateStatusLoc: 0,

	updateCartCount: function() {
		if(Cosmopol.updateStatusLoc)
			return;
		Cosmopol.updateStatusLoc = 1;
		$.get("/shop/?status=1", function(s) {
			Cosmopol.updateStatusLoc = 0;

			var m = s.match(/--(\d+)--(\d+)--/);
			
			if(!m) return;
			
			$("#menu_cart b").html(parseInt(m[1]) ? m[1] : '');
			
			var n = parseInt(m[2]) || 0;
			$(".login" + (1 - n)).hide();
			$(".login" + (n)).show();
		});
	},
	
	
	
	reset: function() {
		location.href = location.href.replace(/#.*/, "#/");
		Cosmopol.emptySearch();
	},
	
	showStartInfo: function() {
		$("#startinfo").show();
		$("body").unbind().click(function() {
			$("#startinfo").hide();
			$("body").unbind();
		});
		
	},
	
	initAjaxLinks: function() {
		$("a.ajax").each(function() {
			this.href = (this.href || "").replace(/\/shop/, "/shop/#"); // #/
		});
	},
	
	initFrontpage: function() {
		if(window.redir)
			return;
		
		$.fn.showLoader = function(color) {
			return $(this).html("<img class='cosmoload' src='/a5/img/load_cosmo_" + color + ".gif' height='32' width='32' />");
		}

		//Cosmopol.initAjaxLinks();
		
		$("a.ajax").live("click", function() {
			var href = (this.href || "").replace(/\/shop/, "/shop/#")
			window.location.href = href;
			return false; 
		})

		$(".add_to_cart").live("click", function() {
			$('#ajaxcart').show().showLoader("brown");
			$.get(this.rel, function() {
				$('#ajaxcart').hide();
				Cosmopol.updateCartCount();
			});
			return false;
		});


		$(".add_to_cart_popup").live("click", function() {
			$('#ajaxcart_popup_feedback').show();
			$.get(this.rel, function() {
				$('#ajaxcart_popup_feedback').hide();
				$('#ajaxcart_popup_result').show();
				Cosmopol.updateCartCount();
			});
			return false;
		});

		
		$("#cats a").each(function() {
			var rel = $(this).attr("rel"), href = $(this).attr("href");
			if(rel == "30" || rel == "2")
				href = href.replace(/\/shop.+/, "/shop/#/");
			else
				href = href.replace(/\/shop.+/, "/shop/#/category/" + rel);
			$(this).attr("href", href);
		});


		if(1 || $.browser.msie) {
			$(".box").hover(
				function() {
					$(this).children(".fore").hide();
					$(this).children(".back").show();
				},
				function() {
					$(this).children(".fore").show();
					$(this).children(".back").hide();
				}
			);
		} else {
			$(".box").hover(
				function() {
					$(this).children(".fore").hide();
					$(this).children(".back").fadeIn();
				},
				function() {
					$(this).children(".fore").fadeIn();
					$(this).children(".back").hide();
				}
			);
		}
		
		$("#top11").click(function() {
			Cosmopol.reset();
		});
			
			
		$("#searchform input").keydown(function(e) {
			if(e.keyCode == 13)
				return false;
		});

		$("#searchform input").keyup(function(e) {
			if(e.keyCode == 13)
				return false;
			clearTimeout(Cosmopol.searchTimer);
			Cosmopol.searchTimer = setTimeout(Cosmopol.doSearch, 100);
		});

		$("#searchform button").click(function() {
			clearTimeout(Cosmopol.searchTimer);
			Cosmopol.doSearch();
			return false;
		});
		
		$(window).resize(function(e) {
			clearTimeout(Cosmopol.resizeTimer);
			Cosmopol.resizeTimer = setTimeout(function() { craster(0, true)}, 300);
		});
		
		
		$(".social_link, .social_popup").hover(
			function() { 
				clearTimeout(Cosmopol.socialCloser);
				$("#" + (this.rel || this.id)).show() 
			},
			function() { 
				var p = "#" + (this.rel || this.id);
				Cosmopol.socialCloser = setTimeout(function() { $(p).hide() }, 500);
			}
		);
		
		Cosmopol.socialLinks = [];
		 $("#social1 a").each(function() {
			Cosmopol.socialLinks.push(this.href);
		});
		
		
		Cosmopol.startLoc = Cosmopol.canonLocation(location.href + "");
   
		$(".popup .close").live("click", function() {
			if(Cosmopol.prevLoc.length)
				history.back(-1);
			else
				location.href = Cosmopol.startLoc;
			
			return false;
		});
		
		Cosmopol.checkLocation();
		
		setInterval(Cosmopol.checkLocation, 100);
		Cosmopol.setTop(0);
		Cosmopol.updateCartCount();

		Cosmopol.showStartInfo();		
	}
}





