﻿(function($) {
    var storepic = "<img src='/images/stores/";
    function formatStore(p) {
        if (p.StoreShortName == "" || p.StoreShortName == null) {
            var s = p.ProductUrl.substring(p.ProductUrl.indexOf(".") + 1);
            return "<b>" + s.split("/")[0] + "</b>";
        } else
            return storepic + p.StoreShortName + ".jpg' alt='' class='store' />";
    }

    function formatName(p) {
        p.ProductUrl = p.ProductUrl.replace("http://", "");
        if (p.Name == "" || p.Name == null || p.Name.trim().length == 0) {
            return '<a href="/check' + p.ProductUrl + '">' + (p.ProductUrl.length > 30 ? p.ProductUrl.substring(0, 27) + "..." : p.ProductUrl) + "</a>"
        } else {
            return '<a href="/check' + p.ProductUrl + '">' + p.Name + "</a>"
        }
    }

    $.pr_add2cart = function(p) {
        p.Method = 3;
        $.prs("cart", p, function(msg) {
            try {
                if (msg.Success) window.location.href = "/" + $.root + "/cart";
                else alert(msg.Message);
            } catch (e) { }
        });
    };

    function getCartNode(p) {

        var content = '<td>' + formatStore(p) + '</td>';
        content += '<td class="info"><h2>' + formatName(p) + '</h2><small>' + p.Description + '</small>';
        content += '<p class="tax"><b>' + p.ImportTax;
        content += '&nbsp;</b>[<a href="javascript:void(0);" class="tax">cambiar</a>]</p>';
        content += '<span class="btn"><img src="/images/delete.png" alt="" /><a href="javascript:void(0);" class="remove">Borrar</a></span>';
        content += '<span class="btn"><img src="/images/saveforlater.png" alt="" /><a href="javascript:void(0);" class="save4">Guardar Para Después</a></span></td>';
        content += '<td class="quantity"><input type="text" value="' + p.Quantity + '" class="quantity" /></td>';

        return $("<tr/>").html(content).append(getCartPrice(p));
    }

    function getCartPrice(p) {
        var td = $('<td class="price"></td>');
        var content = '<h2 >';

        content += formatCurrency($.CurrencySymbol, p.FinalPrice * $.pr_cart.ExchangeRate) + "</h2>";
        content += '<b ><small>Producto + Impuestos: </small><span class="landedprice"> ' + formatCurrency($.CurrencySymbol, ((p.FinalPrice - p.ServicePrice) * $.pr_cart.ExchangeRate).toFixed(2)) + '</span></b>';
        content += '<b><small>Servicios: </small><span class="serviceprice"> ' + formatCurrency($.CurrencySymbol, ((p.ServicePrice) * $.pr_cart.ExchangeRate).toFixed(2)) + '</span></b>';
        return td.html(content);
    }

    function createCartNode(parent) {
        var current = getCartNode(this).appendTo(parent);
    }

    function getShelfNode(p) {
        var content = '<td>' + formatStore(p) + '</td>';
        content += '<td class="info"><h2 >' + formatName(p) + '</h2>';
        content += '<p class="tax"><b>' + p.ImportTax + '</b>&nbsp;[<a href="javascript:void(0);" class="tax shelftax">cambiar</a>]</p>';
        content += '<span class="btn"><img src="/images/delete.png" alt="" /><a href="javascript:void(0);" class="remove">Borrar</a></span>';
        content += '<span class="btn"><img src="/images/addtocart.png" alt="" /><a href="javascript:void(0);" class="add2cart">Mover a Carreta</a></span></td>';
        content += '<td class="quantity"><div style="width:110px">&nbsp;</div></td>';
        content += '<td class="price"><h2 style="width:100px;">≈ ' + formatCurrency($.CurrencySymbol, p.FinalPrice * $.pr_cart.ExchangeRate) + "</h2>";
        content += '<b><a href="' + p.ProductUrl + '">Ver precio actual</a></b>';
        content += '</td>';

        return $("<tr/>").html(content);
    }

    function createShelfNode(parent) {
        return getShelfNode(this).appendTo(parent);
    }

    $.fn.pr_update = function(o) {
        return;
        var $this = $(this);
        $this.append($('<img class="cart_update"/>').attr("src", "/images/loading1.gif"));
        $.prs("productupdate", { o: o.OrderItemID }, function(msg) {
            $this.find(".cart_update").hide();
            if (msg.Success) {
                $($.pr_cart.cartitems).each(function(i) {
                    if ($.pr_cart.cartitems[i].OrderItemID == msg.Message.OrderItemID) {
                        $.pr_cart.cartitems[i] = msg.Message;
                        $this.html(getCartPrice(msg.Message).html());
                        return true;
                    }
                });
            } else {
                alert(msg.Message);
            }
        });
    };

    $.pr_cart = {
        cartitems: [],
        shelfitems: [],
        mini: { Count: 0, SubTotal: 0, OrderID: 0 },
        curItem: null,
        curDom: null,
        save: function(p) { $.pr_add2cart(p); },
        add: function(p) {
            if (typeof p == 'undefined' || !p) {
                if ($(".pr_offers").length > 0) {
                    var s = $(".pr_offers").get(0);
                    var e = $(".pr_offers option:nth(" + s.selectedIndex + ")").get(0);
                    p = $.data(e, "offer");
                } else if (typeof proxy != 'undefined') {
                    p = proxy.ticket;
                } else
                    return false;
            }

            if (p.ProductPrice < 1 && $(".buyBox .enterZip").length > 0) {
                $(".pidelorapido_add").unbind("click").addClass("empty").attr("onclick", "");
                return false;
            }

            if (p.ProductPrice == "" || p.ProductPrice <= 0) {
                prBox2('', '<p style="padding:10px; "><strong>Hubo un error al calcular el precio de este producto.  Por favor usa el Cotizador.</strong></p>');
                return false;
            }

            if (p.ProductUrl.indexOf("http://") >= 0) {
                p.ProductUrl = p.ProductUrl.replace("http://", "/");
            }

            if (p.ProductUrl.indexOf("/") != 0) p.ProductUrl = "/" + p.ProductUrl;
            if (!p.Description) p.Description = "";

            p = $.pr_cart.fill(p);

            p.Status = 1;
            if (p.ImportTaxID == "" || p.ImportTaxID < 0) {
                $($(".pidelorapido_add").get(0)).addClass("empty");
                alert("Por favor selecciona la categoría del producto.");
                $(".pidelorapido_taxcat").addClass("pidelorapido_focus");
                return;
            } else {
                $(".pidelorapido_taxcat").removeClass("pidelorapido_focus");
                $($(".pidelorapido_add").get(0)).removeClass("empty");
            }

            p.Quantity = 1;

            $.pr_cart.cartitems.push(p);
            $.pr_cart.calc();

            $.pr_cart.save(p);
            $.pr_cart.updateMiniCart();
        },
        fill: function(p) { return p },
        hook: function() { },
        xTax: function(ticket, options) {
            ticket.Method = 1;
            ticket.ImportCategories = "";
            options = options || {};
            $.prs('cart', ticket, function(msg) {
                if (msg.Success) {
                    var t = msg.Message;
                    ticket.FinalPrice = t.FinalPrice;
                    ticket.FLSPrice = t.FLSPrice;
                    ticket.FLLSPrice = t.FLLSPrice;
                    ticket.LandedPrice = t.LandedPrice;
                    ticket.ImportTax = t.ImportTax;
                    ticket.ExchangeRate = t.ExchangeRate;
                    ticket.ServicePrice = t.ServicePrice;
                    ticket.Payment = t.Payment;
                    if (typeof options.success != 'undefined') options.success.call(this, ticket);
                } else {
                    if (typeof options.error != 'undefined') options.error.call(this, msg.Message);
                }
            });
        },

        setCategory: function(options) {
            proxy.ticket.ImportTaxID = $(".pidelorapido_taxcat").val();
            if (proxy.ticket.ImportTaxID == "") {
                $(".pidelorapido_final").text("N/A");
                return false;
            }

            options = options || {};
            options.success = function(rst) {
                proxy.ticket = rst;
                $(".pidelorapido_final").text(proxy.ticket.FLSPrice);
                if ($(".pidelorapido_lowest a").length > 0) { // update lowest price if provided
                    $(".pidelorapido_lowest a").text(proxy.ticket.FLLSPrice);
                }
                if ($(".pidelorapido_payment").length > 0) {
                    $(".pidelorapido_payment").html('Cuotas Desde<br /><b>' + formatCurrency($.CurrencySymbol, proxy.ticket.Payment * proxy.ticket.ExchangeRate.toFixed(2)) + '/mes</b>');
                } else {
                    $(".pidelorapido_final").parent().after('<span class="pr_2line pidelorapido_payment" >Cuotas Desde<br /><b>' + formatCurrency($.CurrencySymbol, proxy.ticket.Payment * proxy.ticket.ExchangeRate.toFixed(2)) + '/mes</b></span>');
                }

                window.location.hash = "tax_" + proxy.ticket.ImportTaxID;

                if (proxy.ticket.HasPriceRange) {
                    $.pr_cart.updateOffers(proxy.ticket);
                }
            };
            this.xTax(proxy.ticket, options);
            return false;
        },

        updatePrice: function(ids) {
            return;
            $(ids).each(function(i) {
                $($.pr_cart.cartitems).each(function(j) {
                    if ($.pr_cart.cartitems[j].OrderItemID == ids[i]) {
                        $(".cart tr:nth(" + (i + 1) + ") td:nth(3)").pr_update($.pr_cart.cartitems[j]);
                        return false;
                    }
                });
            });
        },

        updateCategory: function() {
            $.pr_cart.curItem.ImportTaxID = $("div.taxes select").val();
            $.pr_cart.curItem.Method = 1;
            $.prs('cart', $.pr_cart.curItem, function(msg) {
                $("div.taxes").hide();
                if (msg.Success) {
                    $.pr_cart.curItem.FinalPrice = msg.Message.FinalPrice;
                    $.pr_cart.curItem.FLSPrice = msg.Message.FLSPrice;
                    $.pr_cart.curItem.LandedPrice = msg.Message.LandedPrice;
                    $.pr_cart.curItem.ImportTax = msg.Message.ImportTax;
                    $.pr_cart.curDOM.children("td.info").children("p").children("b").text($.pr_cart.curItem.ImportTax);
                    $.pr_cart.curDOM.children("td.price").children("h2").text($.pr_cart.curItem.FLSPrice);
                    var r = formatCurrency($.CurrencySymbol, (p.LandedPrice * p.ExchangeRate).toFixed(2));
                    $.pr_cart.curDOM.children("td.price").children("b:first").children("span.landedprice").text(r);
                    r = formatCurrency($.CurrencySymbol, ((p.FinalPrice - p.LandedPrice) * p.ExchangeRate).toFixed(2));
                    $.pr_cart.curDOM.children("td.price").children("b:first").children("span.commissionprice").text(r);
                } else {
                    alert(msg.Message);
                }
            });
            return false;
        },

        calc: function() {
            $.pr_cart.mini.SubTotal = 0;
            $.pr_cart.mini.Count = 0;
            $($.pr_cart.cartitems).each(function(i) {
                var p = $.pr_cart.cartitems[i];
                $.pr_cart.mini.Count += p.Quantity
                $.pr_cart.mini.SubTotal += p.FinalPrice * $.pr_cart.ExchangeRate * p.Quantity;
            });
        },

        updateMiniCart: function(mini) {
    
            if (mini)
                $.pr_cart.mini = mini;
            if ($.pr_cart.mini.Count == 0) {
                if ($(".pidelorapido_subtotal").length > 0)
                    $(".pidelorapido_subtotal").text(formatCurrency($.CurrencySymbol, 0));
                if ($(".pidelorapido_count").length > 0)
                    $(".pidelorapido_count").text($.pr_cart.mini.Count);
                return;
            }

            if ($(".pidelorapido_subtotal").length > 0)
                $(".pidelorapido_subtotal").text(formatCurrency($.CurrencySymbol, $.pr_cart.mini.SubTotal.toFixed(2)));

            if ($(".pidelorapido_count").length > 0)
                $(".pidelorapido_count").text($.pr_cart.mini.Count);
            $.pr_cart.toggle();
        },

        load: function() {
            $(".pidelorapido_add").attr("onclick", "").unbind("click").click(function() {
                if (typeof (proxy) != 'undefined' && !$(this).hasClass("pidelorapido_offers")) {
                    $.pr_cart.add(proxy.ticket);
                }
            });
        },

        toggle: function() {
            if ($.pr_cart.mini.Count == 0) $(".pidelorapido .basket-box .content").addClass("empty");
            else $(".pidelorapido .basket-box .content").removeClass("empty");

            if ($.pr_cart.HasShelf > 0) $(".pidelorapido .basket-box .content").addClass("hasshelf");
        },

        removeAt: function(e, i) {
            $(".cart .remove").each(function(j) { if (this == e.get(0)) i = j; });
            var p = $.pr_cart.cartitems[i];
            var t = { method: 4, OrderItemID: p.OrderItemID, Callback: i };
            e.parent().parent().parent().fadeOut("slow", function() { $(this).remove(); });
            $.pr_cart.cartitems.splice(i, 1);
            $.prs("cart", t, function(msg) {
                if (msg.Success) $.pr_cart.showSubTotal();
                else alert(proxy.ticket.Message);
            });
        },

        removeAtInShelf: function(e, i) {
            $(".shelf .remove").each(function(j) { if (this == e.get(0)) i = j; });
            var p = $.pr_cart.shelfitems[i];
            var t = { method: 4, OrderItemID: p.OrderItemID, Callback: i };
            e.parent().parent().parent().fadeOut("slow", function() { $(this).remove(); });
            $.pr_cart.shelfitems.splice(i, 1);
            $.prs("cart", t, function(msg) {
                if (!msg.Success) alert(proxy.ticket.Message);
            });
        },

        adjustQuantity: function(e, i) {
            $(".cart input.quantity").each(function(j) { if ($(this).get(0) == e.get(0)) i = j; });
            var p = $.pr_cart.cartitems[i];
            p.Quantity = e.val();
            var t = { method: 2, OrderItemID: p.OrderItemID, Quantity: p.Quantity, Callback: i };

            $.prs("cart", t, function(msg) {
                if (msg.Success) {
                    $.pr_cart.showSubTotal();
                } else alert(proxy.ticket.Message);
            });
        },

        save4Later: function(e, i) {
            $(".cart .save4").each(function(j) { if ($(this).get(0) == e.get(0)) i = j; });
            var p = $.pr_cart.cartitems[i];
            $.pr_cart.cartitems.splice(i, 1);
            p.Status = 0;
            $.pr_cart.shelfitems.push(p);
            e.parent().parent().parent().fadeOut("slow", function() { $(this).remove(); });
            var t = { method: 5, OrderItemID: p.OrderItemID, Callback: i };
            $.prs("cart", t, function(msg) {
                $.pr_cart.showSubTotal();
                if (!msg.Success) alert(proxy.ticket.Message);
            });
            $(getShelfNode(p)).insertAfter("table.shelf tr:last").hide().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
            $("table.cart tr:last").fadeIn("slow");
            $(".shelf .remove:last").click(function(e) { $.pr_cart.removeAtInShelf($(this), i); });
            $(".shelf .add2cart:last").click(function(e) { $.pr_cart.move2cart($(this), i); });
            $(".shelf a.tax:last").click(function(e) { $.pr_cart.changeTax($(this), i); });

        },

        changeTax: function(e, i) {
            var coordinates = e.offset();
            var x = coordinates.left;
            $.pr_cart.curDOM = e.parent().parent().parent();
            var y = coordinates.top + e.height();
            var taxes = $("div.taxes");
            taxes.css("position", "absolute");
            taxes.css("top", y);
            taxes.css("left", x);

            if (e.hasClass("shelftax")) {
                $.pr_cart.curItem = $.pr_cart.shelfitems[i];
            } else {
                $.pr_cart.curItem = $.pr_cart.cartitems[i];
            }

            $("div.taxes select option").each(function() {
                if ($(this).val() == $.pr_cart.curItem.ImportTaxID) {
                    $(this).attr("selected", "selected");
                    return;
                }
            });

            taxes.fadeIn("slow");
        },

        move2cart: function(e, i) {
            $(".shelf .add2cart").each(function(j) { if ($(this).get(0) == e.get(0)) i = j; });
            var p = $.pr_cart.shelfitems[i];
            $.pr_cart.shelfitems.splice(i, 1);
            p.Status = 1;
            $.pr_cart.cartitems.push(p);
            var r = e.parent().parent().parent();
            r.fadeOut("slow", function() { $(this).remove(); });
            var t = { method: 10, OrderItemID: p.OrderItemID, Callback: i };
            $.prs("cart", t, function(msg) {
                $.pr_cart.showSubTotal();
                $("table.cart tr:last").show();
                if (!msg.Success) alert(proxy.ticket.Message);
                else {
                    $("table.cart tr:last td:nth(3)").pr_update(p);
                }
            });

            $(getCartNode(p)).insertAfter("table.cart tr:last").css("display", "none").fadeIn('slow').animate({ opacity: 1.0 }, 3000)
            $("table.cart tr:last").fadeIn("slow");
            $(".cart .remove:last").click(function(e) { $.pr_cart.removeAt($(this), i); });
            $(".cart .save4:last").click(function(e) { $.pr_cart.save4Later($(this), i); });
            $(".cart input.quantity:last").blur(function(e) { $(this).numeric(); $.pr_cart.adjustQuantity($(this), i); });
            $(".cart a.tax:last").click(function(e) { $.pr_cart.changeTax($(this), i); });
        },

        showSubTotal: function() {
            $.pr_cart.calc();
            $(".cartwrapper .subtotal").text("Total: " + formatCurrency($.CurrencySymbol, $.pr_cart.mini.SubTotal.toFixed(2)));
            $.pr_cart.updateMiniCart();
        },

        showDetail: function(options) {
            var el = $(options.el);
            $.pr_cart.cartitems = options.cartitems;
            $.pr_cart.shelfitems = options.shelfitems;
            $.pr_cart.toupdates = options.toupdates;
            $.pr_cart.ExchangeRate = options.ExchangeRate;
            $.each($.pr_cart.cartitems, createCartNode, [$("table.cart")]);
            $.each($.pr_cart.shelfitems, createShelfNode, [$("table.shelf")]);
            $.pr_cart.calc();
            $(".cartwrapper .subtotal").text("Total: " + formatCurrency($.CurrencySymbol, $.pr_cart.mini.SubTotal.toFixed(2)));
            $(".cart .remove").each(function(i) {
                $(this).click(function(e) {
                    $.pr_cart.removeAt($(this), i);
                });
            });

            $(".cart .save4").each(function(i) {
                $(this).click(function(e) { $.pr_cart.save4Later($(this), i); });
            });
            $(".shelf .remove").each(function(i) {
                $(this).click(function(e) { $.pr_cart.removeAtInShelf($(this), i); });
            });
            $(".shelf .add2cart").each(function(i) { $(this).click(function(e) { $.pr_cart.move2cart($(this), i); }); });
            $(".cart input.quantity").each(function(i) {
                $(this).numeric(); $(this).blur(function(e) { $.pr_cart.adjustQuantity($(this), i); });
            });
            $(".cart a.tax").each(function(i) {
                $(this).click(function(e) { $.pr_cart.changeTax($(this), i); });
            });
            $(".shelf a.tax").each(function(i) {
                $(this).click(function(e) { $.pr_cart.changeTax($(this), i); });
            });

            $.pr_cart.load();
            $.pr_cart.updatePrice(options.toupdate);
        }
    }
})(jQuery);

