﻿$(document).ready(function () {
    // Handlers for shipping and payment change
    $(".checkOutForm input[type=radio]").click(function (e) {
        var product = $(this).val();

        $.ajax({
            type: "POST",
            url: GetRelativePath() + "ajax/AddItem.aspx",
            data: { "product": product },
            success: function (data) {
                UpdateCartAndReceipt();
                //UpdateReceipt();
            }
        });
    });

    // Handler for purchase
    $("a.buyBtn").click(function (e) {
        e.preventDefault();

        var link = $(this);
        var attribute = link.siblings(".price").children("select").children("option:selected").attr("value");
        var quantity = link.siblings(".amount").children("input").val();

        if (attribute == "") {
            link.siblings(".price").children("select").addClass("error").focus();
        } else if (isNaN(quantity) || quantity < 1) {
            link.siblings(".amount").children("input").addClass("error").focus();
        } else {
            link.siblings(".amount").children("input").removeClass("error");
            link.siblings(".price").children("select").removeClass("error");

            var animobj;

            if (link.is(".content .prodInfo .options a"))
                animobj = $(".content .prodImg");
            else
                animobj = link.parent().parent().children(".img").find("a");

            $.ajax({
                type: "POST",
                url: GetRelativePath() + "ajax/AddItem.aspx",
                data: { "attribute": attribute, "quantity": quantity },
                dataType: "json",
                success: function (data) {
                    if (data == undefined || data.Items > 0) {
                        ToCartAnimation(animobj);
                        UpdateCart();
                    }

                    ShowStatus(data.Label, data.Contents);
                }
            });
        }
    });

    // Handler for vouchers
    $("input.verifyBtn").click(function (e) {
        e.preventDefault();

        var code = $("input.voucher").val();

        if (code.length > 0) {
            $("input.voucher").removeClass("error");

            $.ajax({
                type: "POST",
                url: GetRelativePath() + "ajax/AddVoucher.aspx",
                data: { "code": code },
                dataType: "json",
                success: function (data) {
                    if (data == undefined || data.Items > 0) {
                        $(".voucherResponse").html("Koden är giltig").removeClass("bad").addClass("good");
                        UpdateCartAndReceipt();
                    } else {
                        $(".voucherResponse").html("Koden är ogiltig").removeClass("good").addClass("bad");
                        //ShowStatus(data.Label, data.Contents);
                    }
                }
            });
        } else {
            $("input.voucher").addClass("error");
        }

        return false;
    });
});

$(".cartItem .delete a").live("click", function (e) {
    var url = $(this).attr("href");

    e.preventDefault();

    $.ajax({
        type: "GET",
        url: url + "&ajax=true",
        success: function (data) {
            UpdateCartAndReceipt();
            //UpdateReceipt();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            this.location.href = url;
        }
    });
});

function GetRelativePath() {
    var path = window.location.toString();

    if (path.indexOf("localhost") >= 0) {
        return "/greatestmom.se/";
    } else {
        return "/";
    }
}

function UpdateReceipt() {
    if ($("div.receipt").length) {
        $.ajax({
            type: "POST",
            url: GetRelativePath() + "ajax/GetReceipt.aspx",
            success: function (data) {
                $("div.receipt").fadeOut(250, function () {
                    $("div.receipt").replaceWith(data);
                    $("div.receipt").hide().fadeIn(250);
                });
            }
        });
    }
}

function UpdateCart() {
    if ($("div.cart").length) {
        $.ajax({
            type: "POST",
            url: GetRelativePath() + "ajax/GetCart.aspx",
            success: function (data) {
                $("div.cart").fadeOut(250, function () {
                    $("div.cart").replaceWith(data);
                    $("div.cart").hide().fadeIn(250);
                });
            }
        });
    }
}

function UpdateCartAndReceipt() {
    $.ajax({
        type: "POST",
        url: GetRelativePath() + "ajax/GetCartAndReceipt.aspx",
        dataType: "html",
        success: function (data) {
            var cart = $(data).filter("div.cart");
            var receipt = $(data).filter("div.receipt");

            if ($("div.cart").length) {
                $("div.cart").fadeOut(250, function () {
                    $("div.cart").replaceWith(cart);
                    $("div.cart").hide().fadeIn(250);
                });
            }

            if ($("div.receipt").length) {
                $("div.receipt").fadeOut(250, function () {
                    $("div.receipt").replaceWith(receipt);
                    $("div.receipt").hide().fadeIn(250);
                });
            }
        }
    });
}

function ToCartAnimation(elem) {
    var sourcePos = elem.offset();
    var targetPos = $("div.cart").offset();
    var productClone = $(elem).clone();

    productClone.css({
        "position": "absolute",
        "top": sourcePos.top + "px",
        "left": sourcePos.left + "px"
    });
    
    productClone.appendTo($("body"));

    productClone.animate({
        "top": targetPos.top + "px",
        "left": targetPos.left + "px",
        "opacity": "0"
    }, 1000, function () {
        productClone.remove();
    });
}

function getXYpos(elem) {
    if (!elem) {
        return { "x": 0, "y": 0 };
    }
    
    var xy = { "x": elem.offsetLeft, "y": elem.offsetTop }
    var par = getXYpos(elem.offsetParent);
    
    for (var key in par) {
        xy[key] += par[key];
    }

    return xy;
}

function ShowStatus(head, contents) {
    if (head.toString().length > 0) {
        $(document.createElement("div"))
            .addClass("errormessage")
            .html("<strong>" + head + "</strong> " + contents + "")
            .appendTo($("body"))
            .hide()
            .fadeIn(1000, function () {
                setTimeout("RemoveStatus()", 5000);
            });
    }
}

function RemoveStatus() {
    $("div.errormessage").fadeOut(500, function () {
        $(this).remove();
    });
}
