ipanema = {

    productSelector: function() {
	var s = jQuery(this);
	function updateVisibleButton() {
	    if (s.val() == "") {
		jQuery(".addToBasketOptions").hide();
		jQuery(".addToBasketOptions.choose").show();
	    } else {
		var a;
		if (typeof ipanemaSpConfig["attributes"]["507"] != "undefined")
		    a = ipanemaSpConfig["attributes"]["507"]["options"];
		else
		    a = ipanemaSpConfig["attributes"]["496"]["options"];
		for (var i=0; i<a.length; i++) {
		    if (a[i]["id"] == s.val()) {
			var p = ipanemaConfig[a[i]["products"][0]];
			jQuery(".addToBasketOptions").hide();
			jQuery(".addToBasketOptions."+p.method).show();
			jQuery("p.duedate span").text(p.ipanema_arriving_date);
			break;
		    }
		}
	    }
	}
	s.change(updateVisibleButton).keyup(updateVisibleButton);
//	var order = false;
//	var preorder = false;
//	for (prod in ipanemaConfig) {
//	    if (ipanemaConfig[prod].method == "order")
//		order = true;
//	    if (ipanemaConfig[prod].method == "preorder")
//		preorder = true;
//	}
//	var method = "outofstock";
//	if (preorder)
//	    method = "preorder";
//	if (order)
//	    method = "order";
//	jQuery(".addToBasketOptions."+method).show();
    },

    inputDefaults: function() {
	jQuery(this).focus(function() {
	    if (jQuery(this).val() == jQuery(this).attr('default'))
		jQuery(this).val('').removeClass('default');
	});
	jQuery(this).blur(function() {
	    if (jQuery(this).val() == '' || jQuery(this).val() == jQuery(this).attr('default'))
		jQuery(this).addClass('default').val(jQuery(this).attr('default'));
	});
	jQuery(this).blur();
    },
    
    startZoom : function(ev) {
	var zoomRef = jQuery(this).parents('.zoomer');
	var zoomimage = zoomRef.find(".image img");
	var zoomimg = zoomRef.find(".zoom img");
	var imageOffset = zoomimage.offset();
	var imgoff = zoomimage.offset().left - zoomRef.find(".image").offset().left;
	var maxx = zoomimage.width();
	var maxy = zoomimage.height();
	var glass = zoomRef.find(".glass");
	ipanema.updateZoom(zoomRef, ev.pageX-imageOffset.left, ev.pageY-imageOffset.top, imgoff, maxx, maxy, zoomimg, glass);
	zoomRef.find('.holder').show();
	glass.show();
	zoomRef.find('.image').mousemove(function(e) {
	    ipanema.updateZoom(zoomRef, e.pageX-imageOffset.left, e.pageY-imageOffset.top, imgoff, maxx, maxy, zoomimg, glass);
	});
    },

    stopZoom : function() {
	var zoomRef = jQuery(this).parents('.zoomer');
	zoomRef.find('.holder').hide();
	zoomRef.find('.glass').hide();
	zoomRef.find('.image').unbind('mousemove');
    },

    updateZoom : function(zoomRef, x, y, imgoff, maxx, maxy, zoomimg, glass) {
	var mx = (x < 47 ? 47 : x > maxx-48 ? maxx-48 : x) - 47;
	var my = (y < 55 ? 55 : y > maxy-55 ? maxy-55 : y) - 55;
	zoomimg.css({left:-mx*4, top:-my*4});
	glass.css({left:mx+imgoff,top:my});
    },

    twitterScroller : function() {
	var ts = jQuery(this);
	var initialpause = parseInt(ts.attr('initialpause') || "9000");
	var pause = parseInt(ts.attr('pause') || "6000");
	var li = ts.find("li");
	var step = 0;
	function cb() {
	    var h = li.eq(step).position().top;
	    setTimeout(function() { ts.animate({top:-h+"px"}, {complete:cb}); }, step==1 ? initialpause : pause);
	    step += 1;
	    if (step == li.length)
		step = 0;
	};
	if (li.length != 0) {
	    cb();
	}
    },

    homeBanner: function(bs) {
	this.state = 0;
	this.total = 0;
	this.timeoutId = undefined;
	this.width = bs.width();
	this.rate = parseInt(bs.attr('bsrate') || "4000");
	this.clickHold = parseInt(bs.attr('bsclickhold') || "15000");
	this.wrap = bs.attr('bswrap') ? bs.attr('bswrap') == "true" : true;
	this.speed = parseInt(bs.attr('bsspeed') || "1000");
	this.easing = bs.attr('bseasing') || "swing";
	this.bs = bs;
	this.clickMode = bs.attr('bsclickmode') ? bs.attr('bsclickmode') == "true" : false;

	this.select = function(index) {
	    this.bs.find('ul').animate({left: (index*-this.width)+"px"}, { queue:false, duration:this.speed, easing:this.easing } );
	    this.bs.find('ol li').removeClass('on')
	    jQuery(this.bs.find('ol li')[index==this.total?0:index]).addClass('on');
	    this.state = index;
	};

	this.timer = function() {
	    if (this.wrap && this.state == this.total) {
		this.state = 0;
		this.bs.find('ul').css({left: "0px"});
	    }
	    this.state += 1;
	    if (!this.wrap && this.state == this.total)
		this.state = 0;
	    this.select(this.state);
	    this.setTimeout(this.rate);
	};

	this.setTimeout = function(delay) {
	    this.clearTimeout();
	    var me = this;
	    this.timeoutId = setTimeout(function() { me.timer(); }, delay);
	};

	this.clearTimeout = function() {
	    clearTimeout(this.timeoutId);
	};

	var html = "";
	bs.find('ul li').each(function() { html += "<li></li>"; });
	if (html == "" || html == "<li></li>")
	    return;
	html = "<ol>"+html+"</ol>";
	bs.append(html);
	var index = 0;
	var me = this;
	bs.find('ol li').each(function() {
	    var pos = index;
	    if (this.clickMode) {
		jQuery(this).click(function() {
		    me.setTimeout(me.clickHold);
		    me.select(pos);
		});
	    } else {
		jQuery(this).mouseenter(function() {
		    me.clearTimeout();
		    me.select(pos);
		}).mouseleave(function() {
		    me.setTimeout(me.clickHold);
		});
	    }
	    index += 1;
	});
	this.total = index;
	if (this.wrap) 
	    bs.find('ul>li:first-child').clone().appendTo(bs.find('ul'));

	if (this.total > 0) {
	    jQuery(bs.find('ol li')[0]).addClass('on');
	    this.setTimeout(this.rate);
	}
    },

    styleReformat: function() {
	var ol = jQuery(this);
	for(var col=0; col<6; col++) {
	    var li = ol.find('li');
	    if (col*20 > li.length)
		break;
	    ol.parent().append("<ol class='narrow-by-col-"+(col+1)+"'></ol>");
	    var newol = ol.parent().find('ol.narrow-by-col-'+(col+1));
	    li.slice(col*20, Math.min(col*20+20, li.length)).clone().appendTo(newol);
	}
	ol.remove();
    },

    stylePopoutSetup: function() {
	jQuery('#narrow-by-list dt.Style').mouseenter(ipanema.stylePopoutOpen);
	jQuery('#narrow-by-list').mouseleave(ipanema.stylePopoutClose);
    },
    stylePopoutOpen: function() {
	jQuery('#narrow-by-list dt.Style').addClass("active");
	jQuery('#narrow-by-list dd.Style ol').show();
    },
    stylePopoutClose: function() {
	jQuery('#narrow-by-list dt.Style').removeClass("active");
	jQuery('#narrow-by-list dd.Style ol').hide();
    },

    basketPopupNotify: function() {
	var price = jQuery(".ipanema-header-cart .header-part .total .price").text();
	var lastPrice = jQuery.JSONCookie("lastPrice").price;
	if (typeof lastPrice == "undefined")
	    lastPrice = "£0.00";
	if (price != lastPrice) {
	    jQuery("div.popup-part").addClass("open");
	    setTimeout(function() { jQuery("div.popup-part").removeClass("open"); }, 7500);
	    jQuery.JSONCookie("lastPrice", {price:price});
	} else if (price != "£0.00") {
	    jQuery.JSONCookie("lastPrice", {price:price});
	}
    },

    pullouts: function() {
	jQuery(".pullout").each(function() {
	    var pullout = jQuery(this);
	    var open = false;
	    pullout.mouseleave(function() { pullout.animate({left:'-605px'}, {queue:false, duration: open?1000:30}); open=false;});
	    pullout.mouseenter(function() { pullout.animate({left:'-595px'}, {queue:false, duration:30});});
	    pullout.click(function () { if (open) return true; pullout.animate({left:'0px'}, {queue:false}); open=true; return false; });
	});
    },

    last: 'one'
}

jQuery(document).ready(function(){
    jQuery('input[default]').each(ipanema.inputDefaults);
    jQuery('.account-access.notloggedin').mouseenter(function() { jQuery('#ipanema-login-popup').show(); });
    jQuery('#ipanema-login-close').click(function() { jQuery('#ipanema-login-popup').hide(); });
    jQuery('#ipanema-login-popup, .header').mouseleave(function() { jQuery('#ipanema-login-popup').hide(); });
    jQuery('.zoomer.active .image').hover(ipanema.startZoom, ipanema.stopZoom);
    jQuery('#ipanema-box').tabs();
    jQuery('#ipanema-twitter-scroller').each(ipanema.twitterScroller);
    jQuery('.bannerSlider').each(function() { new ipanema.homeBanner(jQuery(this)); });
    jQuery('.ipanema-content .links ul li a, a.slide').click(function() {
	var href = jQuery(this).attr('href');
	if (href.substring(0,1) == '#') {
	    jQuery.scrollTo(jQuery('a[name='+href.substring(1)+']'), { speed:2000 });
	    return false;
	}
    });
    jQuery('select[id=attribute507],select[id=attribute496]').each(ipanema.productSelector);
    jQuery('#narrow-by-list dd.Style ol').each(ipanema.styleReformat);
    ipanema.stylePopoutSetup();
    ipanema.basketPopupNotify();
    jQuery('div.popup-part').mouseleave(function() { jQuery(this).removeClass('open'); } );
    jQuery('#search_mini_form').submit(function() {
	if (jQuery('#search').hasClass('default')) {
	    jQuery('#search').addClass('validation-failed').focus();
	    alert('please enter a search keyword');
	    return false;
	}
	return true;
    });
    ipanema.pullouts();

    Validation.addAllThese([
	['validate-number-range', 'Amount is not within the specified range.', function (v, el) {
	    var m = el.className.match(/\Wfrom-([0-9.]+)-to-([0-9.]+)\W/);
	    if (!m) return true;
	    v = parseNumber(v);
	    return v>=m[1] && v<=m[2];
	}],
    ]);
});

