﻿/// <reference name="MicrosoftAjax.js" />
/// <reference path="ITG.js" />

ITG.Client.eCommerce = function(url, sessionId, onlineRetailerId)
{
    this._onlineRetailerId = onlineRetailerId;
    this._sessionId = sessionId;
    this._url = url;
}

ITG.Client.eCommerce.prototype =
{
    get_onlineRetailerId: function() {
        return this._onlineRetailerId;
    },

    set_onlineRetailerId: function(value) {
        this._onlineRetailerId = value;
    },

    get_sessionId: function() {
        return this._sessionId;
    },

    set_sessionId: function(value) {
        this._sessionId = value;
    },

    get_url: function() {
        return this._url;
    },

    set_url: function(value) {
        this._url = value;
    },

    addToCart: function(quantity, wineBottleAttributeGroupId, postBack, reservationOrderDetailId) {
        var me = this;
        var parameters;
        var webservice = this.get_url() + "/CheckAvailability";

        try {
            this.trackSession();

            parameters = "{ sessionId: '" + this.get_sessionId() + "', onlineRetailerId: " + this.get_onlineRetailerId()
                + ", wineBottleAttributeGroupId: " + wineBottleAttributeGroupId + ", reservationOrderDetailId: " + reservationOrderDetailId + ", quantity: " + quantity + " }";

            $.ajax(
            {
                type: "POST",
                url: webservice,
                data: parameters,
                contentType: "application/json",
                dataType: "json",
                dataFilter: function(data, type) {
                    return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, "new $1");
                },

                error: function(result) {
                    radalert("An error occurred attempting to add wine to your cart.", 300, 150, "Inside the Grape");
                },

                success: function(result) {
                    if (result.d) {
                        if (result.d.HasQuantityRequested) {
                            if (result.d.IsFutureAvailable) {
                                var date;
                                var message = "The wine you have selected is not yet available, "
                                    + "but is expected to ship on {0}/{1}/{2}.\n\n"
                                    + "Click 'OK' to add to cart or click 'Cancel'";

                                date = result.d.ExpectedAvailableDate;
                                message = String.format(message, date.getMonth() + 1, date.getDate(), date.getFullYear());

                                radconfirm(message, function(arg) {
                                    if (arg == true) me.__addToCart(quantity, wineBottleAttributeGroupId, reservationOrderDetailId, postBack);
                                }, 400, 150, null, "Inside the Grape");
                            }
                            else me.__addToCart(quantity, wineBottleAttributeGroupId, reservationOrderDetailId, postBack);
                        }
                        else {
                            if (result.d.AvailableQuantity <= 0) {
                                radalert("Wine is currently not available", 300, 150, "Inside the Grape");
                            }
                            else {
                                var message = "The number of bottles you requested is not available.\n"
                                + "Would you like to add {0} bottles to your cart?\n\n"
                                + "Click 'OK' to add to cart or click 'Cancel'";

                                message = String.format(message, result.d.AvailableQuantity);

                                radconfirm(message, function(arg) {
                                    if (arg == true) me.__addToCart(result.d.AvailableQuantity, wineBottleAttributeGroupId, reservationOrderDetailId, postBack);
                                }, 400, 150, null, "Inside the Grape");
                            }
                        }
                    }
                    else radalert("Error occurred attempting to check wine inventory", 300, 150, "Inside the Grape");
                }
            });
        }
        catch (e) {
            radalert(String.format("An error occurred: {0}", e.message), 300, 150, "Inside the Grape");
        }

        return false;
    },

    deleteCart: function(success, error) {
        var me = this;
        var parameters;
        var webservice = this.get_url() + "/DeleteCart";

        try {
            parameters = "{ sessionId: '" + this.get_sessionId() + "'"
            + ", onlineRetailerId: " + this.get_onlineRetailerId() + " }";

            $.ajax(
            {
                type: "POST",
                url: webservice,
                data: parameters,
                contentType: "application/json",
                dataType: "json",

                error: function(result) {
                    if (error) error();
                    else radalert("An error occurred attempting to delete cart.", 300, 150, "Inside the Grape");
                },

                success: function(result) {
                    if (result.d) {
                        if (success) success();
                    }
                    else radalert("An error occurred attempting to delete cart.", 300, 150, "Inside the Grape");
                }
            });
        }
        catch (e) {
            radalert(String.format("An error occurred: {0}", e.message), 300, 150, "Inside the Grape");
        }

        return false;
    },

    purchase: function(textboxId, wineBottleAttributeGroupId, postBack, reservationOrderDetailId) {
        var me = this;
        var input = $find(textboxId);
        var parameters;
        var webservice = this.get_url() + "/CheckAvailability";

        if (input.get_value().length == 0 || input.get_value() == "0") {
            radalert("Please enter a valid quantity.", 300, 150, "Inside the Grape");
            return false;
        }

        try {
            this.trackSession();

            parameters = "{ sessionId: '" + this.get_sessionId() + "', onlineRetailerId: " + this.get_onlineRetailerId()
                + ", wineBottleAttributeGroupId: " + wineBottleAttributeGroupId + ", reservationOrderDetailId: " + reservationOrderDetailId + ", quantity: " + input.get_value() + " }";

            $.ajax(
            {
                type: "POST",
                url: webservice,
                data: parameters,
                contentType: "application/json",
                dataType: "json",
                dataFilter: function(data, type) {
                    return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, "new $1");
                },

                error: function(result) {
                    radalert("An error occurred attempting to add wine to your cart.", 300, 150, "Inside the Grape");
                },

                success: function(result) {
                    if (result.d) {
                        if (result.d.HasQuantityRequested) {
                            if (result.d.IsFutureAvailable) {
                                var date;
                                var message = "The wine you have selected is not yet available, "
                                    + "but is expected to ship on {0}/{1}/{2}.\n\n"
                                    + "Click 'OK' to add to cart or click 'Cancel'";

                                date = result.d.ExpectedAvailableDate;
                                message = String.format(message, date.getMonth() + 1, date.getDate(), date.getFullYear());

                                radconfirm(message, function(arg) {
                                    if (arg == true) me.__addToCart(input.get_value(), wineBottleAttributeGroupId, reservationOrderDetailId, postBack);
                                }, 400, 150, null, "Inside the Grape");
                            }
                            else me.__addToCart(input.get_value(), wineBottleAttributeGroupId, reservationOrderDetailId, postBack);
                        }
                        else {
                            if (result.d.AvailableQuantity <= 0) {
                                radalert("Wine is currently not available", 300, 150, "Inside the Grape");
                            }
                            else {
                                if (result.d.IsFutureAvailable) {
                                    var date;
                                    var message = "The wine you have selected is not yet available, "
                                        + "but is expected to ship on {0}/{1}/{2}.\n\n"
                                        + "Click 'OK' to add to cart or click 'Cancel'";

                                    date = result.d.ExpectedAvailableDate;
                                    message = String.format(message, date.getMonth() + 1, date.getDate(), date.getFullYear());

                                    radconfirm(message, function(arg) {
                                        if (arg == true) {
                                            var message = "The number of bottles you requested is not available.\n"
                                                + "Would you like to add {0} bottles to your cart?\n\n"
                                                + "Click 'OK' to add to cart or click 'Cancel'";

                                            message = String.format(message, result.d.AvailableQuantity);

                                            radconfirm(message, function(arg) {
                                                if (arg == true) me.__addToCart(result.d.AvailableQuantity, wineBottleAttributeGroupId, reservationOrderDetailId, postBack);
                                            }, 400, 150, null, "Inside the Grape");
                                        }
                                    }
                                    , 400, 150, null, "Inside the Grape");
                                }
                                else me.addToCart(input.get_value(), wineBottleAttributeGroupId, postBack, reservationOrderDetailId);
                            }
                        }
                    }
                    else radalert("Error occurred attempting to check wine inventory", 300, 150, "Inside the Grape");
                }
            });
        }
        catch (e) {
            radalert(String.format("An error occurred: {0}", e.message), 300, 150, "Inside the Grape");
        }

        return false;
    },

    trackSession: function() {
        var me = this;
        var parameters;
        var webservice = this.get_url() + "/TrackSession";

        try {
            parameters = "{ sessionId: '" + this.get_sessionId() + "'"
                + ", onlineRetailerId: " + this.get_onlineRetailerId() + " }";

            $.ajax(
            {
                type: "POST",
                url: webservice,
                data: parameters,
                contentType: "application/json",
                dataType: "json",

                error: function(result) {
                    radalert("An error occurred attempting to track session.", 300, 150, "Inside the Grape");
                },

                success: function(result) {
                    // do nothing
                }
            });
        }
        catch (e) {
            radalert(String.format("An error occurred: {0}", e.message), 300, 150, "Inside the Grape");
        }
    },

    updateCart: function(textboxId, cartId, wineBottleAttributeGroupId, reservationOrderDetailId, postBack) {
        var me = this;
        var input = $(ITG.getIdSelector(textboxId));
        var parameters;
        var webservice = this.get_url() + "/CheckAvailabilityForUpdate";

        if (input.val().length == 0) {
            radalert("Please enter a valid quantity.", 300, 150, "Inside the Grape");
            return false;
        }

        try {
            this.trackSession();

            parameters = "{ sessionId: '" + this.get_sessionId()
                + "', onlineRetailerId: " + this.get_onlineRetailerId()
                + ", wineBottleAttributeGroupId: " + wineBottleAttributeGroupId
                + ", reservationOrderDetailId: " + reservationOrderDetailId
                + ", quantity: " + input.val() + " }";

            $.ajax(
            {
                type: "POST",
                url: webservice,
                data: parameters,
                contentType: "application/json",
                dataType: "json",
                dataFilter: function(data, type) {
                    return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, "new $1");
                },

                error: function(result) {
                    radalert("An error occurred attempting to add wine to your cart.", 300, 150, "Inside the Grape");
                },

                success: function(result) {
                    if (result.d) {
                        if (result.d.HasQuantityRequested) {
                            me.__updateCartItem(cartId, input.val(), postBack, textboxId);
                        }
                        else {
                            if (result.d.AvailableQuantity <= 0) {
                                radalert("Wine is currently not available", 300, 150, "Inside the Grape");
                            }
                            else {
                                var message = "The number of bottles you requested is not available.\n"
                                + "Would you like to add {0} bottles to your cart?\n\n"
                                + "Click 'OK' to add to cart or click 'Cancel'";

                                message = String.format(message, result.d.AvailableQuantity);

                                radconfirm(message, function(arg) {
                                    if (arg == true) {
                                        me.__updateCartItem(cartId, result.d.AvailableQuantity, postBack, textboxId);
                                    }
                                }, 400, 150, null, "Inside the Grape");
                            }
                        }
                    }
                    else radalert("Error occurred attempting to check wine inventory", 300, 150, "Inside the Grape");
                }
            });
        }
        catch (e) {
            radalert(String.format("An error occurred: {0}", e.message), 300, 150, "Inside the Grape");
        }
        finally {
            allowThisSubmit = true;
        }

        return false;
    },

    __addToCart: function(quantity, wineBottleAttributeGroupId, reservationOrderDetailId, postBack) {
        var me = this;
        var parameters;
        var webservice = this.get_url() + "/AddToCartForItg";
        var returnValue = false;

        try {
            parameters = "{ sessionId: '" + this.get_sessionId() + "'"
                + ", onlineRetailerId: " + this.get_onlineRetailerId()
                + ", wineBottleAttributeGroupId: " + wineBottleAttributeGroupId
                + ", reservationOrderDetailId: " + reservationOrderDetailId
                + ", quantity: " + quantity + " }";

            $.ajax(
            {
                type: "POST",
                url: webservice,
                data: parameters,
                contentType: "application/json",
                dataType: "json",

                error: function(result) {
                    radalert("An error occurred attempting to add wine to cart.", 300, 150, "Inside the Grape");
                },

                success: function(result) {
                    if (result.d) {
                        //radalert("Wine added to cart.", 300, 150, "Inside the Grape");
                        if (postBack && postBack.length > 0) eval(postBack);
                    }
                    else radalert("An error occurred attempting to add wine to cart.", 300, 150, "Inside the Grape");
                }
            });
        }
        catch (e) {
            radalert(String.format("An error occurred: {0}", e.message), 300, 150, "Inside the Grape");
            returnValue = false;
        }



        return returnValue;
    },

    __updateCartItem: function(cartId, quantity, postBack, textboxId) {
        var me = this;
        var parameters;
        var webservice = this.get_url() + "/UpdateCartItem";
        var returnValue = false;

        try {
            parameters = "{ cartId: '" + cartId + "', quantity: " + quantity + " }";

            $.ajax(
            {
                type: "POST",
                url: webservice,
                data: parameters,
                contentType: "application/json",
                dataType: "json",

                error: function(result) {
                    radalert("An error occurred attempting to update quantity.", 300, 150, "Inside the Grape");
                },

                success: function(result) {
                    if (result.d) {
                        if (postBack && postBack.length > 0) {
                            $("#" + textboxId).val(quantity);
                            eval(postBack);
                        }
                    }
                    else radalert("An error occurred attempting to update quantity.", 300, 150, "Inside the Grape");
                }
            });
        }
        catch (e) {
            radalert(String.format("An error occurred: {0}", e.message), 300, 150, "Inside the Grape");
            returnValue = false;
        }

        return returnValue;
    }
}
