﻿//NOTE: The page must initialize the expansion state of the VisualCart before it can be shown. The state must be maintained in memory
//http://sorgalla.com/projects/jcarousel/
var vc;

//Moved to server-side
//$(document).ready(function() {
//    vc = new VisualCart();
//    vc.Load();
//});

//ideally this would use some kind of id to search across all isntances but for now just hardcode to look at vc
function VCInstance() {
    return vc;
}

/*--- The Visual Cart Object Definition*/
function VisualCart() {
    this.FullPageLoadCartState = null; //used only on initial pageload
    this.MY_CAROUSEL = null;
    this.GLOBAL_ADD_ID = "";
    this.GLOBAL_REMOVE_ID = "";
    this.CarouselItemData = []; //loaded after getting cartState
    this.SERVICE = new Customization.BVModules.Services.VisualCartService();
    this.MAX_VISIBLE_ITEMS = 6;
    this.ItemRemovalScrollAnimationIsRunning = false;

    //Setup togglebutton events
    $(".toggleButton").click(function(e) { VCInstance().ToggleClick(); });

    //*--- Load and Update Methods */

    this.Load = function(cartState) {
        this.FullPageLoadCartState = cartState;
        jQuery('#mycarousel').jcarousel({
            size: 0,
            scroll: 1,
            animation: 400,
            easing: "jswing", //jswing,easeOutBounce,easeOutQuint,easeOutElastic,easeOutExpo
            itemLoadCallback: { onBeforeAnimation: function(carousel, state) { VCInstance().mycarousel_itemLoadCallback(carousel, state); } }
        });
    }

    //--- Load all the carousel li containers from the datasource
    this.mycarousel_itemLoadCallback = function(carousel, state) {
        this.HideNotifications();
        if (this.MY_CAROUSEL == null) {
            this.MY_CAROUSEL = carousel;
        }

        if (state != 'next' && state != 'prev') {
            //If cartState is available then load from that else retrieve it from the server.
            if (this.FullPageLoadCartState) {
                this.LoadDataResult(this.FullPageLoadCartState);
                this.FullPageLoadCartState = null; //this should not be used after the initial full page load
            }
        }
    }

    this.mycarousel_itemAddCallback = function(data) {
        for (var i = 0; i < data.length; i++) {
            //always reload incase there were changes from deletion
            var li = this.mycarousel_getItemHTML(data[i]);
            this.MY_CAROUSEL.add(i + 1, li);
        }
        this.MY_CAROUSEL.size(data.length);
        //Adjust cropping
        $('.jcarousel-item img').each(function() {
            var heightLimit = 83;
            var imgHeight = $(this).height();
            var cropOffset = imgHeight > heightLimit ? (imgHeight - heightLimit) / 2 : 0;
            $(this).css("bottom", cropOffset + "px");
        });
    }

    //--- Load the datasource: no longer used since loads occur either from client side objects passed from server during full page loads or from directly passed objects from AJAX responses 
    //    this.LoadData = function() {
    //        this.SERVICE.GetCartState(function(cartState) {
    //            var vCart = VCInstance();
    //            vCart.LoadDataResult(cartState);
    //        });
    //    }

    //--- Load the control from cartState Data. This is used for the callback of several operations.
    this.LoadDataResult = function(cartState) {
    
        //initialize expansion state only if auto expand was not requested
        if (cartState.AutoExpandRequested == false) {
            this.InitExpansion(cartState);
        }

        $('#numItems').html(cartState.NumItemsInCart);
        $('#subtotal').html(cartState.SubTotal_S);
        $('.visualCart .offer').html(cartState.OfferContent);
        //$('#shipping').html(cartState.ShippingTotal_S);

        //Update Items
        this.CarouselItemData = []; //reset

        for (var i = 0; i < cartState.Items.length; i++) {
            var jcItem;
            jcItem = {
                LineItemId: cartState.Items[i].LineItemId,
                title: cartState.Items[i].ProductName,
                ProductUrl: cartState.Items[i].ProductUrl,
                Quantity: cartState.Items[i].Quantity,
                UnitPrice: cartState.Items[i].UnitPrice,
                UnitPrice_S: cartState.Items[i].UnitPrice_S,
                ImageUrl: cartState.Items[i].ImageUrl
            };
            this.CarouselItemData.push(jcItem);
        }

        //Load items into carousel
        if (this.GLOBAL_REMOVE_ID == "") {
            //reload the carousel item markup unless this is part of a delete operation
            this.mycarousel_itemAddCallback(this.CarouselItemData);
        }
        else {
            this.GLOBAL_REMOVE_ID = "";
            this.MY_CAROUSEL.size(this.CarouselItemData.length);
        }

        return this.CarouselItemData;
    }

    /*--- Visual Cart Expansion State Methods */

    this.InitExpansion = function(cartState) {

        $('.visualCart .toggleButton').attr("class", "toggleButton"); //reset classes first to ensure a clean starting point
        $('.visualCart').attr("class", "visualCart");
        if (cartState.Expanded) {
            $('.visualCart').css('visibility', 'visible');
            $('.visualCart .carouselAnchor').css('visibility', 'visible');
            $('.visualCart .toggleButton').addClass("toggleExpanded");
            $('.visualCart').css("bottom", "0px");
            this.SetVCElementExpansionState(true);
        }
        else {
            $('.visualCart').addClass('visualCartCollapse');
            $('.visualCart').css('visibility', 'visible');
            $('.visualCart .carouselAnchor').css('visibility', 'hidden');
            $('.visualCart .toggleButton').addClass("toggleCollapsed");
            $('.visualCart').css("bottom", "-60px");
            this.SetVCElementExpansionState(false);
        }
    }

    this.ToggleClick = function() {
        var method1 = 'easeInSine';
        var method2 = 'easeInOutSine';
        this.HideNotifications();

        //check the expasion state each time before it is displayed.
        var isExpanded = this.GetVCElementExpansionState();
        if (isExpanded) {
            //collapse
            $('.visualCart').animate({ bottom: "-88px" }, 400, method1, function() {
                $('.visualCart .carouselAnchor').css('visibility', 'hidden');
                $('.visualCart .toggleButton').removeClass("toggleExpanded");
                $('.visualCart .toggleButton').addClass("toggleCollapsed");
            });
            $('.visualCart').animate({ bottom: "-60px" }, { duration: 300, easing: method2 });

            this.SERVICE.SetExpansionState(false, null);
            this.SetVCElementExpansionState(false);
        }
        else {
            //expand
            $('.visualCart').animate({ bottom: "-88px" }, 400, method1, function() {
                $('.visualCart .carouselAnchor').css('visibility', 'visible');
                $('.visualCart .toggleButton').removeClass("toggleCollapsed");
                $('.visualCart .toggleButton').addClass("toggleExpanded");
            });
            $('.visualCart').animate({ bottom: "0px" }, { duration: 300, easing: method2 });

            this.SERVICE.SetExpansionState(true, null);
            this.SetVCElementExpansionState(true);
        }
    }

    //--- Client Side Expansion State Property/Methods

    this.SetVCElementExpansionState = function(state) {
        $('.visualCart').data('vcExpansionState', state);
    }

    this.GetVCElementExpansionState = function() {
        return $('.visualCart').data('vcExpansionState');
    }

    /*--- Add Product To Cart Methods: Result is to be called by Anthem's add-to-cart response. */

    this.AddProductToCart_Result = function(cartState) {

        if (cartState.AutoExpandRequested) {
            this.ToggleClick();
        }

        //set the GLOBAL_ADD_ID so that the new item is initially hidden
        this.GLOBAL_ADD_ID = cartState.CurrentOperationLineItemId;

        //Add to the cart
        this.Carousel_PartialUpdate(cartState);

        //Run the background color flash animation
        $('.bgColorBlink').css({ opacity: 0, display: "block" }).fadeTo("200", 0.35, function() { $('.bgColorBlink').fadeOut(); });

        //Run the add animation
        var cartItemImage = $('img[LineItemId=' + cartState.CurrentOperationLineItemId + ']');
        var cartItem = cartItemImage.parent();

        cartItemImage.animate({ marginTop: "0px" }, 300, null);

        //show notification only if not also auto expanding
        if (cartState.AutoExpandRequested == false) {
            //Show notification
            $.pnotify({
                pnotify_title: '',
                pnotify_text: 'An item has been added to your cart.'
            });

            this.SetNotificationVerticalPosition(0);
            var summaryLeft = $('.divSummary').offset().left + 319;
            $('.ui-pnotify').css('left', summaryLeft + 'px');
        }
    }

    /*--- Update Cart Methods */

    this.UpdateCartItem = function() {
        //pull in data from the dialog
        var lid = $('.contextMenu .lid').html();
        var qty = $('.contextMenu input').val();

        this.SERVICE.UpdateItemQty(lid, qty, function(result) { VCInstance().UpdateCartItemResult(result); });
    }

    this.UpdateCartItemResult = function(cartState) {
        this.Carousel_PartialUpdate(cartState);
        $('.contextMenu .main').hide();
        $('.contextMenu .success').show();
    }

    /*--- Remove Cart Methods */

    this.RemoveCartItem = function() {
        //Pull in data from the dialog
        var lid = $('.contextMenu .lid').html();

        //Store some state information
        this.GLOBAL_REMOVE_ID = lid;

        //Remove the item
        this.SERVICE.RemoveFromCart(lid, function(result) { VCInstance().RemoveCartItemResult(result); });
    }

    this.RemoveCartItemResult = function(cartState) {
        var cartItemImage = $('img[LineItemId=\"' + cartState.CurrentOperationLineItemId + '\"]');
        var cartItem = cartItemImage.parent();

        //mark the start of the remove animation
        this.ItemRemovalScrollAnimationIsRunning = true;
        cartItem.animate(
        {  float: "none", marginTop: "88px" },/*do not try opacity here because IE7 will leave some visual residue until the item is completely removed*/
        300,
        function() {
            $(this).animate(
            { marginLeft: "0px", marginRight: "0px", width: "0px", padding: "1px" },
            300,
            function() {
                var vc = VCInstance(); vc.RemoveCartItemResult_LastStep(cartItem, cartState);
                //Mark the end of the remove animation
                vc.ItemRemovalScrollAnimationIsRunning = false;
            }
            );

        });

        this.HideNotifications();
    }

    this.RemoveCartItemResult_LastStep = function(cartItem, cartState) {
        //remove the markup
        cartItem.remove();
        this.Carousel_PartialUpdate(cartState);
        //scroll left if needed
        var removeOffset = 1;
        var canScrollPrev = this.MY_CAROUSEL.first > 1;
        var lastVisibleIsLastItem = this.MY_CAROUSEL.last - removeOffset == this.CarouselItemData.length;
        var scrollPrev = canScrollPrev && lastVisibleIsLastItem;

        if (scrollPrev) {
            this.MY_CAROUSEL.prev();
        }
    }

    this.HideNotifications = function() {
        $('.ui-pnotify').hide();
    }


    //*--- Load Helpers and Msc Helpers */

    //--- Update the datasource and the carousel container names
    this.Carousel_PartialUpdate = function(cartState) {
        //update
        this.LoadDataResult(cartState);

        //manually update the li classes and attributes
        var i = 1;
        $('#mycarousel li').each(function() {
            $(this).attr("class", "jcarousel-item jcarousel-item-horizontal jcarousel-item-" + i + " jcarousel-item-" + i + "-horizontal");
            $(this).attr("jcarouselindex", i);
            i++;
        });

        //The right arrow is turning on inconsistently at unexpected times and I can't figure out why so I am forcing it to behave here until I can figure out what is going on.
        var b = $('.jcarousel-next');
        if (this.MY_CAROUSEL.size() <= this.MAX_VISIBLE_ITEMS) {
            b.css('visibility', 'hidden');
        }
        else {
            b.css('visibility', 'visible');
        }
    }

    //--- Item html creation helper.
    this.mycarousel_getItemHTML = function(item) {
        var initialStyle = '';
        if (item.LineItemId == this.GLOBAL_ADD_ID) {
            initialStyle = 'style="margin-top:88px; margin-left:0px; margin-right:0px; padding-left:0px; padding-right:0px;"';
            this.GLOBAL_ADD_ID = ""; //reset
        }
        return '<img src="' + item.ImageUrl + '" width="83" ' + initialStyle + ' alt="' + item.url + '"  onmouseover="VCInstance().LoadItemContextMenu(this);" LineItemId="' + item.LineItemId + '" onclick="window.location=\'' + item.ProductUrl + '\';" /><div class="cartItemQtyBox"><b>' + item.Quantity + '</b></div>';
    };

    //--- Item Context Menu
    this.LoadItemContextMenu = function(sender) {
        if (this.ItemRemovalScrollAnimationIsRunning || this.MY_CAROUSEL.animating) {
            return;
        }

        var lid = $(sender).attr('LineItemId');
        var itemCount = this.CarouselItemData.length;
        var item;
        for (var i = 0; i < itemCount; i++) {
            if (this.CarouselItemData[i].LineItemId == lid) {
                item = this.CarouselItemData[i];
                break;
            }
        }
        //assume item is always found
        $('.ui-pnotify-container').css("display", "none");  //close all dialogs already open first
        void $.pnotify_remove_all();
        //display product dialog
        var tmp = '<div class="main"><span class="lid">LID</span><div class="name">PNAME</div><table><tr><td>PPRICE <input type="text" class="text" value="PQTY" maxlength="2" onchange="VCInstance().ValidateInput(this);"/></td><td class="update" onclick="VCInstance().UpdateCartItem();">Save Changes</td></tr><tr><td></td><td class="remove" onclick="VCInstance().RemoveCartItem();">Remove</td></tr></table></div><div class="success">Quantity updated successfully.</div>';
        $.pnotify({
            pnotify_title: '',
            pnotify_text: tmp.replace('LID', item.LineItemId).replace('PNAME', item.title).replace('PPRICE', item.UnitPrice_S).replace('PQTY', item.Quantity),
            pnotify_fade_speed: "fast",
            pnotify_delay: "900",
            LineItemId: sender.LineItemId//custom option being passed to the notification, this is used in jquery.pnotify.custom.js
        });
        var senderLeft = parseInt($(sender).offset().left) - 28;
        $('.ui-pnotify').css('left', senderLeft + 'px').addClass('contextMenu');
        $('.contextMenu input.text').keypress(function() { $('.contextMenu .update').addClass('updateActive'); });
        this.SetNotificationVerticalPosition(-8);
    }

    //-- Adjust positioning of notification box
    this.SetNotificationVerticalPosition = function(vOffset) {
        //display just above vcart depending on expansion state
        var vCartBottom = $('.visualCart').css('bottom').replace('px', '');
        var vCartHeight = $('.visualCart').height();
        var nbottom = parseInt(vCartBottom) + parseInt(vCartHeight) + vOffset;
        $('.ui-pnotify').css('bottom', nbottom + 'px');
    }

    this.ValidateInput = function(input) {//prevents junk from being entered...only accepts decimals
        if (parseInt(input.value) > 0 && parseInt(input.value) != NaN) {
            input.value = parseInt(input.value);
        }
        else {
            input.value = 1; //use 1 as a default so that they do not try to remove an item by changing the quantity to 0
        }
    }
}
























