﻿/***************************************
Shopping cart
-------------------------------------- */
var cartStatusId;

var $cartMessages = {};
$cartMessages.RemoveFromCart = "Удалить из корзины";
$cartMessages.AddToCart = "Добавить в корзину";

$.fn.syncCartItemActionTip = function () {
    if ($(this).attr('src').indexOf('vm-cart-add.png') >= 0) {
        $(this).attr({
            "alt": $cartMessages.AddToCart,
            "title": $cartMessages.AddToCart
        });
        return;
    }

    if ($(this).attr('src').indexOf('vm-cart-remove.png') >= 0) {
        $(this).attr({
            "alt": $cartMessages.RemoveFromCart,
            "title": $cartMessages.RemoveFromCart
            });
            
        return;
    }
}

function swapCartImageOver() {
    if ($(this).attr('src').indexOf('vm-cart.png') >= 0) {
        $(this).attr("src", '/images/vm-cart-add.png');
        return;
    }

    if ($(this).attr('src').indexOf('vm-cart-added.png') >= 0) {
        $(this).attr("src", '/images/vm-cart-remove.png');
        return;
    }
}

function swapCartImageOut() {
    if ($(this).attr('src').indexOf('vm-cart-add.png') >= 0) {
        $(this).attr("src", '/images/vm-cart.png');
        return;
    }

    if ($(this).attr('src').indexOf('vm-cart-remove.png') >= 0) {
        $(this).attr("src", '/images/vm-cart-added.png');
        return;
    }
}

function SetCartStatusMessage(cartStatusMessage, ItemId, TotalCartItemsCount, TotalCartItemsCost) {
    var $jref = '#'+ cartStatusId + ':first';
    var $lnk = $($jref);
    
    if ($lnk != null) {
        $lnk.show();
        $lnk.text(cartStatusMessage);
    }
}

function removeItemAndSyncCart() {
    var $actionItem = $(this);
    var $itemId = $actionItem.attr('CommandArgument');
    $('table #cart tr.cartItemDetailsEntry').each(function () {
        if ($(this).attr('itemId') == $itemId) {
            var res = $actionItem.updateCart();
            if (res) {
                $(this).remove();
                RecalcCart();
            } else {
                alert('UI will not be updated');
            }
            return;
        }
    });
};

$.fn.updateCart = function () {
    var $isUpdated = false;
    var saleItemId = $(this).attr('CommandArgument');
    if (saleItemId == null || saleItemId <= 0) {
        alert('Необходимо выбрать позицию для добавления в корзину');
        return $isUpdated;
    }
    var $img = $(this);
    var data = {}; var ItemId = {}; var Method = {};
    data.Id = saleItemId;
    data.Method = 'ManageByCartItemState';

    var dataJson = JSON.stringify(data);
    //var currentUrl = window.location.pathname;
    var currentUrl = '/Handler/ajaxRemoteGateway.ashx';
    $.ajax({
        type: "POST",
        async: false,
        url: currentUrl,
        data: dataJson,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        timeout: (10 * 1000),
        // Define the error method.
        error: function (objAJAXRequest, strError) {
            $("#response").text("Error! Type: " + strError);
            $isUpdated = false;
        }, //error
        success: function (xhr, status) {
            if (status == "success") {
                var action;
                if (xhr != null && xhr.IsSuccess != null) {
                    action = xhr.Message;
                    if (xhr.IsSuccess) {
                        SetCartStatusMessage(xhr.Message, xhr.ItemId, xhr.TotalCartItemsCount, xhr.TotalCartItemsCost);
                        //update status image
                        if (xhr.IsAddAction) {
                            $img.attr("src", '/images/vm-cart-added.png');
                        } else {
                            $img.attr("src", '/images/vm-cart.png');
                        }
                        $isUpdated = true;
                    } else {
                        alert(action);
                        $isUpdated = false;
                    }
                } else {
                    alert("Ошибка при обработке запроса");
                    $isUpdated = false;
                }
                //alert(action);
            }
        }
    }); //ajax
    return $isUpdated;
};       //click


$(document).ready(function () {
    var stripe = function () {
        $('#cart tbody tr').removeClass('alt')
    .filter(':visible:odd').addClass('alt');
    }; //stripe
    
    stripe();

    $('div').each(function () {
        var $div = $(this);
        if ($div.is('#content-control-holder #cartItems')) {
            var stripe = function () {
                $('#cart tbody tr').removeClass('alt')
                .filter(':visible:odd').addClass('alt');
            };
            stripe();

            $('#recalculate').hide();

            $('.quantity input').keypress(function (event) {
                if (event.which && (event.which < 48 ||
                                       event.which > 57)) {
                    event.preventDefault();
                }
            });

            var quantity = 0;
            $('.quantity input').each(function () { }).focus(function () {
                if (this.value != '') {
                    quantity = parseInt(this.value);
                    this.value = '';
                }
            }).blur(function () {
                if (this.value == '') {
                    this.value = quantity;
                }
                RecalcCart();
            });
            window.onload = RecalcCart;
        };
    });
});

function RecalcCart() {
    var totalQuantity = 0;
    var totalCost = 0;
    $('#cart tbody tr').each(function () {
        var price = parseFloat($('.price', this)
                             .text().replace(/^[^\d.]*/, ''));
        price = isNaN(price) ? 0 : price;
        var quantity =
               parseInt($('.quantity input', this).val(), 10);
        quantity = isNaN(quantity) ? 0 : quantity;
        var cost = quantity * price;
        $('.cost', this).text(cost.toFixed(2));
        totalQuantity += quantity;
        totalCost += cost;
    });
    //$('.subtotal .cost').text(totalCost.toFixed(2));
    //var taxRate = parseFloat($('.tax .price').text()) / 100;
    //var tax = Math.ceil(totalCost * taxRate * 100) / 100;
    //$('.tax .cost').text(tax.toFixed(2));
    //totalCost += tax;
    //$('.shipping .quantity').text(String(totalQuantity));
    //var shippingRate = parseFloat($('.shipping .price')
    //                       .text().replace(/^[^\d.]*/, ''));
    //var shipping = totalQuantity * shippingRate;
    //$('.shipping .cost').text(shipping.toFixed(2));
    //totalCost += shipping;
    $('#cart tfoot .total .cost').text(totalCost.toFixed(2));
}
    $(function () {
        $('.bubbleInfo').each(function () {
            // options
            var distance = 10;
            var time = 250;
            var hideDelay = 500;

            var hideDelayTimer = null;

            // tracker
            var beingShown = false;
            var shown = false;

            var trigger = $('.trigger', this);
            var popup = $('.popup', this).css('opacity', 0);

            // set the mouseover and mouseout on both element
            $([trigger.get(0), popup.get(0)]).mouseover(function () {
                // stops the hide event if we move from the trigger to the popup element
                if (hideDelayTimer) clearTimeout(hideDelayTimer);

                // don't trigger the animation again if we're being shown, or already visible
                if (beingShown || shown) {
                    return;
                } else {
                    beingShown = true;

                    // reset position of popup box
                    popup.css({
                        top: -50,
                        left: 0,
                        display: 'block' // brings the popup back in to view
                    })

                    // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
            top: '-=' + distance + 'px',
            opacity: 1
        }, time, 'swing', function () {
            // once the animation is complete, set the tracker variables
            beingShown = false;
            shown = true;
        });
                }
            }).mouseout(function () {
                // reset the timer if we get fired again - avoids double animations
                if (hideDelayTimer) clearTimeout(hideDelayTimer);

                // store the timer so that it can be cleared in the mouseover if required
                hideDelayTimer = setTimeout(function () {
                    hideDelayTimer = null;
                    popup.animate({
                        top: '-=' + distance + 'px',
                        opacity: 0
                    }, time, 'swing', function () {
                        // once the animate is complete, set the tracker variables
                        shown = false;
                        // hide the popup entirely after the effect (opacity alone doesn't do the job)
                        popup.css('display', 'none');
                    });
                }, hideDelay);
            });
        });
    });

