function scrollTime(pixels) {
    return pixels*2;
}


function storeBasketPosition() {
    $.cookie("2s4u.basketposition", $("#shopStrip").css("top"),
            { expires: 7, path: "/" });
}

function resetStripState() {
    var strip_parts = $("#shopStrip ul.toPurchase > li");
    var strip_height = 160;
    for (var i in strip_parts) {
        if (1) {
            strip_height+=strip_parts.eq(i).outerHeight(true);
        }
    }

    var scroll_length = $(window).height()-strip_height;
    var up = $("#stripScroll-up");
    var down = $("#stripScroll-down");
    var strip = $("#shopStrip");

    $("#home").unbind(".alienhover");
    up.unbind(".stripscroll");
    down.unbind(".stripscroll");

    if (parseInt(strip.css("top"), 10)<0) {
        up.removeClass("disabled");
    } else {
        up.addClass("disabled");
    }

    if (parseInt(strip.css("top"), 10)>scroll_length) {
        down.removeClass("disabled");
    } else {
        down.addClass("disabled");
    }

    $("#stripScroll-up")
        .bind("mouseenter.stripscroll", function() {
            if (!$(this).hasClass("disabled")) {
                var distance = -parseInt(strip.css("top"), 10);
                var duration = scrollTime(distance);
                down.removeClass("disabled");
                strip.stop(true).animate({top: 0}, duration, function() {
                    storeBasketPosition();
                    resetStripState(); });
            }
        })
        .bind("mouseleave.stripscroll", function() {
            if (!$(this).hasClass("disabled")) {
                strip.stop(true);
                storeBasketPosition();
            }
        });


    $("#stripScroll-down:not(.disabled)")
        .bind("mouseenter.stripscroll", function() {
            if (!$(this).hasClass("disabled")) {
                var distance = -(scroll_length+parseInt(strip.css("top"), 10));
                var duration = scrollTime(distance);
                up.removeClass("disabled");
                strip.stop(true).animate({top: scroll_length}, duration, function() {
                    storeBasketPosition();
                    resetStripState(); });
            }
        })
        .bind("mouseleave.stripscroll", function() {
            if (!$(this).hasClass("disabled")) {
                strip.stop(true);
                storeBasketPosition();
            }
        });

    $("#home")
	.bind("mouseenter.alienhover", function() {
	    if (!$("#shopStrip").hasClass("alien")) {
		return;
	    }
	    $(this).btOn();
	})
	.bind("mouseleave.alienhover", function() {
	    $(this).btOff();
	});
}


function openArticle(article_id) {
    var link = $("#" + article_id + " a:first");

    if (link.attr("target")==="alien-site") {
        link.click();
    } else {
        window.open(link.attr("href"));
    }
}


$(".buttonOrder").live("click", function() {
    openArticle("strip-article-" + $(this).val());
});


$(".addToBasket").live("click", function() {
    var form = $(this).parents("form").get(0);
    var retailer_id = $(form.retailer_id).val();
    var retailer = $("#strip-retailer-"+retailer_id);
    var article_id = $(form.article_id).val();

    trackEvent("basket", "add", article_id);

    article_id = "strip-article-"+article_id;
    var button = $(this);
    button.addClass("processing");


    $.ajax({
        type: "POST",
        url: form.action,
        cache: false,
        dataType: "json",
        success: function(data, status) {
            button.removeClass("processing");
            if (data.result==="ok") {
                var strip = $("#shopStrip");
                var block;

                if (!strip.length) {
                    strip = $("<div id='shopStrip'/>").appendTo("body");
                    $("<div id='shopStrip-up'/>").addClass("disabled").appendTo("body");
                    $("<div id='shopStrip-down'/>").addClass("disabled").appendTo("body");

                    strip.load(strip_url + " #shopStrip > *", function() {
                            $(document).trigger("newContent", strip);
                            $("body").addClass("hasBag");
                            $(window).resize();
                            resetStripState();
                    });
                } else if (!retailer.length) {
                    retailer_id = "strip-retailer-"+retailer_id;
                    block = $("<li/>").attr("id", retailer_id)
                                          .addClass("retailer")
                                          .css("display", "none")
                                          .prependTo($(".toPurchase"));
                    block.load(strip_url+" #"+retailer_id+ " > *", function() {
                        $(document).trigger("newContent", block);
                        block.slideDown(function() {
                            resetStripState();
                        });
                    });
                } else {
                    retailer_id = "strip-retailer-"+retailer_id;
                    $("#"+retailer_id+" .totals").load(strip_url+" #"+retailer_id+" .totals > *");

                    block = $("<li/>").attr("id", article_id)
                                          .addClass("article")
                                          .css("display", "none")
                                          .prependTo($("#"+retailer_id+" > ul"));
                    block.load(strip_url+" #"+article_id+ " > *", function() {
                        $(document).trigger("newContent", block);
                        block.slideDown(function() {
                            resetStripState();
                        });
                    });
                }
            }
            RenderJSONResponse(data);
            $("#productDetails").parent().fadeOut(function() {
                    $("#productDetails").dialog("close").remove();});
        },
         error: function(request, status, error) {
            button.removeClass("processing");
            ShowMessage("Er is iets fout gegaan bij het toevoegen van dit artikel.", "error");
         }
     });

    return true;
});


$(".toPurchase .remove").live("click", function() {
    var article_id = $(this).val();

    trackEvent("basket", "remove", article_id);

    var retailer = $(this).parents(".retailer");
    var victim;
    var button = $(this);
    var updateTotals = false;
    button.addClass("processing");

    if (retailer.find("ul li").length>1) {
        victim=$(this).parents(".article");
        updateTotals=true;
    } else if ($(".toPurchase li.retailer").length>1) {
        victim=retailer;
    } else {
        victim=$("#shopStrip");
    }

    $.ajax({
        type: "POST",
        url: this.form.action,
        cache: false,
        dataType: "json",
        success: function(data, status) {
            button.removeClass("processing");

            if (data.result==="ok") {
                if (updateTotals) {
                    retailer.find(".totals").load(strip_url+" #"+retailer.attr("id")+" .totals > *");
                }

                victim.slideUp("slow", function() {
                    if (victim.attr("id")==="shopStrip") {
                        $("body").removeClass("hasBag");
                        $("#alien-site").remove();
                        $(window).resize();
                    }
                    victim.remove();
                    resetStripState();
                });
                // Reload the strip to get the new totals
            }

            RenderJSONResponse(data);
            },
         error: function(request, status, error) {
            button.removeClass("processing");
            ShowMessage("Er is iets fout gegaan bij het toevoegen van dit artikel.", "error");
         }
     });
    return false;
});


$(".toPurchase a[target=alien-site]").live("click", function() {
    var frame = $("#alien-site");

    if (!frame.length) {
        frame = $("<iframe src='about:blank' id='alien-site'/>")
                .css("width", ($(window).width()-105) + "px")
                .css("background", "#ffffff");
        frame.insertBefore("#shopStrip");
    }

    frame.attr("src", $(this).attr("href"));
    $(".toPurchase .current").removeClass("current");
    $(this).parents("li").addClass("current");
    $("#shopStrip").addClass("alien");

    return false;
});

$("#shopStrip.alien #home").live("click", function() {
    $("#alien-site").remove();
    $("#shopStrip").removeClass("alien")
                   .find(".current").removeClass("current");
});


$("#shopStrip:not(.alien) #home").live("click", function() {
    window.location.href=$("#personalDock .home > a").attr("href");
    return false;
});

$(".addToWardrobe").live("click", function() {
    var button = $(this),
        article_id = this.form.id.value;

    trackEvent("wardrobe", "add", article_id);

    button.addClass("processing");

    $.ajax({
        type: "POST",
        url: this.form.json_url.value,
        cache: false,
        dataType: "json",
        data: {id: article_id },
        success: function(data, status) {
            button.removeClass("processing");
            RenderJSONResponse(data);
            },
         error: function(request, status, error) {
            button.removeClass("processing");
            ShowMessage("Er is iets fout gegaan bij het toevoegen van dit artikel.", "error");
         }
     });

    return false;
});


$("ul.rateable a").live("click", function() {
    var article_id = $(this).attr("rel"),
        rater = $(this).parents("ul")[0],
        score = $(this).parent().attr("class").slice(-1);
    $(rater)
      .removeClass("rated-1")
      .removeClass("rated-2")
      .removeClass("rated-3")
      .removeClass("rated-4")
      .removeClass("rated-5")
      .addClass("rated-" + score);
    $("#article-"+article_id)
      .removeClass("rated-1")
      .removeClass("rated-2")
      .removeClass("rated-3")
      .removeClass("rated-4")
      .removeClass("rated-5")
      .addClass("rated-" + score);

    $.ajax({type: "POST",
            url: $(this).attr("href"),
            cache: false,
            dataType : 'json',
            data : { score : score },
            success : RenderJSONResponse
            });

    return false;
});


$(document).bind("newContent", function(event, content) {
    $(".accordion").accordion({autoHeight: false, clearStyle: true});
});

$(document).ready(function() {
    var pos = $.cookie("2s4u.basketposition");
    if (pos!==null) {
        $("#shopStrip").css("top", pos);
    }
    resetStripState();
    $(window).resize(function() {
        $("#alien-site").css("width", ($(window).width()-105) + "px");
        resetStripState();
    });

    $("#home").bt($("#hometip").html(), {trigger: "none"});
});


