AreaMap = function(el) {
	el = $(el);
	var overlay = $(".map-overlay:first", el);
	var img = $("img:first", el);
	img.attr("src", "/i/map/empty.png");
	$("area", el).each(function(i){
		var area = $(this);
		area.attr("title", "");
		area.bind("mouseover focus", function() {
			var n = i;
			overlay.css("background-position", - (overlay.attr("offsetWidth") * (n + 1)) + "px 0");
		});
		area.bind("mouseout blur", function() {
			overlay.css("background-position", "0 0");
		});
	});
	$("#counties ul a").bind("mouseover", function() {
		var url = $(this).attr("href");
		$("area[href="+url+"]").trigger("mouseover");
	}).bind("mouseout", function() {
		var url = $(this).attr("href");
		$("area[href="+url+"]").trigger("mouseout");
	});
};

EnlargeMe = function(el) {
	el.prettyPhoto({
		animationSpeed: 'fast', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.5, /* Value betwee 0 and 1 */
		showTitle: true, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'dark_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
		callback: function(){}
	});
};

// Init on document ready
$(document).ready(function() {
	/* Choose store */
    $(".map").each(function() {
        var map = new AreaMap(this);
    });
	/* Product page javascripts */
	var productLinks = $("#m-products .products a");
	productLinks.click(function(){
		var self = $(this);
		var url = self.attr("href");
		var ajaxUrl = url + "?ajax=1";
		if($("#product").size()) {
			$("#product").fadeTo(100, 0.2, function(){
				/* Loading class if procedure takes more than 1 second */
				var t = setTimeout('$("#product").addClass("loading")', 400);
				$("#product").load(ajaxUrl, function(){
					$(this).removeClass("loading").fadeTo(200, 1.0, function(){
						clearTimeout(t);
					});
					EnlargeMe($("#product a[rel^='prettyPhoto']"));
				});
			});
		}
		productLinks.parents("li").removeClass("sel");
		self.closest("li").addClass("sel");
		if($("#m-spotlight").is(":visible")) {
			$("#m-spotlight").hide(500, function(){
				document.location.href = url;
			});
			return false;
		}
	});
	/* Enlarge product image */
	EnlargeMe($("#product a[rel^='prettyPhoto']"));
	/* Product pager */
	$("#product-pager a").live("click", function(){
		var self = $(this);
		var current = $("#m-products .products li.sel");
		if(self.hasClass("next") && current.size()) {
			if(current.is(":last-child")) {
				return true;
			} else {
				current.next("li").find("a:first").trigger("click");
			}
		} else if(self.hasClass("prev") && current.size()) {
			if(current.is(":first-child")) {
				return true;
			} else {
				current.prev("li").find("a:first").trigger("click");
			}
		}
		return false;
	});
});

$(window).load(function(){
	// Preload loading image after everything else
	$('<div>').html('<img src="/i/loading.gif" alt="" />');
});