﻿/// <reference path="scripts.htm" />

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Copyright (c) 2008-2009 OrderBot Software, Inc. All rights reserved.
// orderbot.cart.js
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Object.createNamespace('orderbot.cart');

Object.extend(orderbot.cart, {
    // main properties
    sc: null,
    options: null,
    pe: null,
    //remove
    tbody: null,
    highlightColor: '#E2E2E2',

    //    loadingImg: { name: 'wait.gif', w: 24, h: 24 },
    loadingImg: { name: 'ajax-loading-bg-black.gif', w: 16, h: 16 },


    init: function() {
        // set main properties
        this.sc = $('sc-content');
        this.options = $('cart-options');
        this.options.absolutize();

        // remove
        var table = $('sc-content').down('table');
        this.tbody = table.down('tbody');

        var container = this;
        // set items hover effects
        this.options.observe('mouseover', function(e) { container.clearHoverTimer(); });
        this.options.observe('mouseout', function(e) { container.startHoverTimer(); });
        // get items row in SC
        var rows = this.sc.select('tr.itemrow');
        rows.each(function(tr) { container.addHoverObserver(tr); });
    },

    addHoverObserver: function(tr) {
        var container = this;
        // show item options on mouseover
        tr.observe('mouseover', function(e) {
            container.clearHoverTimer();

            var productId = tr.id.substring(tr.id.indexOf('_') + 1);
            var recipientId = tr.id.substring(0, tr.id.indexOf('_'));

            var qs = String.format('?p={0}', productId);
            var btnEdit = container.options.down('table').down('a[id$=btnEdit]');
            btnEdit.href = btnEdit.href.lastIndexOf('p=') != -1 ? btnEdit.href.replace(/\?p=.*/, qs) : btnEdit.href += qs;

            var btnDelete = container.options.down('table').down('input[id$=btnDelete]');
            btnDelete.productId = productId;
            btnDelete.recipientId = recipientId;

            var divDim = container.options.getDimensions();
            var trDim = tr.getDimensions();
            var pos = tr.cumulativeOffset();
            var left = (pos.left - divDim.width) + 'px';
            var top = pos.top + 'px';
            container.options.down('table').setStyle({ height: trDim.height + 'px' });
            container.options.setStyle({ left: left, top: top, height: trDim.height + 'px' }).show();
        });

        tr.observe('mouseout', function(e) { container.startHoverTimer(); });
    },

    startHoverTimer: function() {
        this.pe = new PeriodicalExecuter(function() { this.options.hide(); } .bind(this), 1);
    },

    clearHoverTimer: function() {
        if (this.pe) { this.pe.stop(); this.pe = null; }
    },

    addItem_click_old: function(e, productId) {
        Event.stop(e);

        //alert("come to add");
        var inputs = $('product-details').down('table#info').select('input.quantity');


        var ddl1 = null;
        var ddl2 = null;
        var ddl3 = null;


        ddl1 = $('productvars').down('select[id$=ddlpvv1]');
        //        ddl2 = $('productvars').down('SELECT[id$=ddlpvv2]');
        //        ddl3 = $('productvars').down('SELECT[id$=ddlpvv3]');

        ddl2 = $('productvars').down('SELECT[id$=ddlpvv2]');

        var input1 = $('productvars').down('input[id$=hfvv1]');
        var input2 = $('productvars').down('input[id$=hfvv2]');

        var value1 = null;
        var value2 = null;
        var value3 = null;

        //ddl.options[ddl.selectedIndex].value
        //  var si = ddl.selectedIndex.value;

        //  alert(ddl1.inspect());

        if (ddl1 != null) {
            value1 = $F(ddl1);
        }
        else if (input1 != null) {
            value1 = $F(input1);
        }

        if (ddl2 != null) {
            value2 = $F(ddl2);
        }
        else if (input2 != null) {

            value2 = $F(input2);
        }

        if (value1 != null && value2 != null) {
            //var response = ShoppingCartHandler.GetProductidbypv(productId, value1, value2, value3);
            var response = ShoppingCartHandler.GetProductidbypvNew(productId, value1, value2);

            if (response.error) { alert("error from ajax method is: " + response.error.Message); return; }
            var childproid;
            chldprods = orderbot.parseJSON(response.value);
            chldprods.each(function(p) {
                childproid = p;
                productId = childproid;
                // alert(childproid);
            });
        }


        //            if (chosenoption.value != "nothing") {
        //                window.open(chosenoption.value, "", "") //open target site (based on option's value attr) in new window
        //            }

        // var pvvs = $('product-details').down('table#info').select('input.ddlpvv1').value;

        // var pvvs = $('product-details').down('details').select('input.ddlpvv1');

        // alert(pvvs + " is pvvs comes here");


        var recipients = [];

        inputs.each(function(input) {
            var isNew = input.hasClassName("new");
            if (isNew || !input.value.strip().empty()) {
                var qty = parseInt(input.value, 10);
                var tr = input.up('tr');
                var recipient = isNew ?
                        tr.down('input[id$=txtNewRecipient]').value.strip() :
                        tr.down('span[id$=lblRecipient]').innerHTML.strip();
                if (!recipient.empty() && (isNew || qty > 0)) {
                    qty = isNaN(qty) ? null : qty;
                    recipients.push({ qty: qty, recipient: recipient, isNew: isNew });
                }
            }
        });

        if (recipients.size() > 0) {
            var btn = e.element();
            orderbot.toogleAjaxButton(btn, true, this.loadingImg);
            var context = this;
            //alert ("calls this one...");
            ShoppingCartHandler.AddItems(productId, recipients, function(response) {

                orderbot.toogleAjaxButton(btn, false);
                if (response.error) { alert(response.error.Message); return; }

                var data = orderbot.parseJSON(response.value);
                data.Recipients.each(function(recipient) { context.updateRecipient(recipient); });
                context.updateTotal(data);
            })
        }
    },

    addItem_click: function(e, productId) {
        Event.stop(e);

        //alert("come to add");
        var inputs = $('product-details').down('table#info').select('input.quantity');

        var ddl1 = null;

        ddl1 = $('productvars').down('select[id$=ddlpvv1]');

        var value1 = null;

        if (ddl1 != null) {
            value1 = $F(ddl1);
        }

        //alert(productId + '  ' + value1);
        if (value1 != null) {
            //var response = ShoppingCartHandler.GetProductidbypv(productId, value1, value2, value3);
            var response = ShoppingCartHandler.GetProductidbypvNew1(productId, value1);

            if (response.error) { alert("error from ajax method is: " + response.error.Message); return; }
            var childproid;
            chldprods = orderbot.parseJSON(response.value);
            chldprods.each(function(p) {
                childproid = p;
                productId = childproid;
                // alert(childproid);
            });
        }

        var recipients = [];

        inputs.each(function(input) {
            var isNew = input.hasClassName("new");
            if (isNew || !input.value.strip().empty()) {
                var qty = parseInt(input.value, 10);
                var tr = input.up('tr');
                var recipient = isNew ?
                        tr.down('input[id$=txtNewRecipient]').value.strip() :
                        tr.down('span[id$=lblRecipient]').innerHTML.strip();
                if (!recipient.empty() && (isNew || qty > 0)) {
                    qty = isNaN(qty) ? null : qty;
                    recipients.push({ qty: qty, recipient: recipient, isNew: isNew });
                }
            }
        });

        if (recipients.size() > 0) {
            var btn = e.element();
            orderbot.toogleAjaxButton(btn, true, this.loadingImg);
            var context = this;
            //alert ("calls this one...");
            ShoppingCartHandler.AddItems(productId, recipients, function(response) {

                orderbot.toogleAjaxButton(btn, false);
                if (response.error) { alert(response.error.Message); return; }

                var data = orderbot.parseJSON(response.value);
                data.Recipients.each(function(recipient) { context.updateRecipient(recipient); });
                context.updateTotal(data);
            })
        }
    },

    updateRecipient: function(recipient) {
        var tr = this.getRecipientRow(recipient.RecipientId);

        if (Object.isUndefined(tr)) { tr = this.createRecipient(recipient); }

        recipient.Products.each(function(item) { this.UpdateItem(item); } .bind(this));
        this.updateRecipientTotal(recipient);
    },

    updateTotal: function(data) {
        var count = data.ItemsCount;
        var tr = this.getFooterRow();
        if (Object.isUndefined(tr)) return;
        var span = tr.down('span[id$=lblTotal]');
        var oldValue = span.innerHTML.strip();
        var newValue = data.SubTotal.numberFormat("$#,##0.00 USD");
        //if (oldValue != newValue) {
        span.update(newValue);
        this.tbody.up().down('span[id$=lblInfo]').update('Your cart has ');
        this.tbody.up().down('span[id$=lblCount]').update(String.format('{0} items', count));
        var btn = this.tbody.down('input[id$=btnCheckout]');
        if (newValue == '$0.00 USD') { btn.hide(); } else { btn.show(); }
        // }
        window.location.reload();
    },

    getRecipientRow: function(recipientId) {
        var selector = String.format('tr[id={0}]', recipientId);
        return this.tbody.down(selector);
    },

    getItemRowId: function(recipientId, productId) {
        return String.format('{0}_{1}', recipientId, productId);
    },

    getItemRow: function(recipientId, productId) {
        var id = this.getItemRowId(recipientId, productId);
        var selector = String.format('tr[id={0}]', id);
        return this.tbody.down(selector);
    },

    getRecipientTotalRowId: function(recipientId) { return String.format('{0}_subtotal', recipientId); },

    getRecipientTotalRow: function(recipientId) {
        var id = this.getRecipientTotalRowId(recipientId);
        var selector = String.format('tr[id={0}]', id);
        return this.tbody.down(selector);
    },

    getFooterRow: function() { return this.tbody.down('tr#footerTotal'); },

    removeItem: function(e) {
        Event.stop(e);
        this.options.hide();
        var element = e.element();
        var pid = element.productId;
        var rid = element.recipientId;
        var context = this;
        var args = { recipientId: rid, productId: pid };

        ShoppingCartHandler.RemoveItemFromCart(args, function(response) {

            if (response.error) { alert(response.error.Message); return; }

            var data = orderbot.parseJSON(response.value);

            var tr = context.getItemRow(rid, pid);
            if (tr) { tr.remove(); }

            var recipient = data.Recipients.first();
            context.clearRecipientQty(rid);

            context.updateRecipientTotal(recipient);
            context.updateTotal(data);
        })
    },

    UpdateItem: function(item) {
        var tr = this.getItemRow(item.RecipientId, item.ProductId);
        if (Object.isUndefined(tr)) { tr = this.createItem(item); }
        //        try {
        tr.down('span[id$=lblQty]').update(item.Quantity);
        tr.down('span[id$=lblPrice]').update(item.SubTotal.numberFormat("$#,##0.00"));
        //        } catch (e) { alert(e); }
    },

    updateRecipientTotal: function(recipient) {
        var tr = this.getRecipientTotalRow(recipient.RecipientId);
        var selector = 'span[id$=lblSubTotal]';
        var span = tr.down(selector);
        var oldValue = span.innerHTML.strip();
        var newValue = recipient.SubTotal.numberFormat("$#,##0.00");
        if (oldValue != newValue) {
            tr.down(selector).update(newValue);
        }
    },

    clearRecipientQty: function(recipientId) {
        var selector = String.format("tr#rid_{0}", recipientId);
        var div = $('details');
        if (div) {
            var tr = div.down('table#info').down(selector);
            if (tr) { tr.down('input[id$=txtQty]').value = ''; }
        }
    },

    //NOT USING ...is for ADDRESSBOOK
    addNameRecipients: function(names) {
        var recipients = [];
        names.each(function(name) { recipients.push({ recipient: name.name }); });
        ShoppingCartHandler.AddRecipients(recipients, this.addItemResponse.bind(this));
    },

    createRecipient: function(recipient) {
        var divDetails = $('details');
        if (Object.isUndefined(divDetails)) { return; }

        if (recipient.Name != 'Me') {
            var spaniid = String.format('{0}_lblRecipient', recipient.RecipientId);
            var inputid = String.format('{0}_txtQty', recipient.RecipientId);
            var input;
            var rid = String.format('rid_{0}', recipient.RecipientId);
            var tr =
            $.TR({ id: rid },
                $.TD({ style: 'text-align: right' },
                    $.SPAN({ id: spaniid }, recipient.Name)
                ),
                $.TD({ style: 'text-align: center' },
                    input = $.INPUT({ id: inputid, type: 'text', 'class': 'quantity', maxlength: '5', style: 'font-size:100%;width:2.5em;' })
                )
            );

            if ($('details')) {
                var newrecrow = $('details').down('table[id=info]').down('tr.newrecipientrow');
                newrecrow.insert({ before: tr });
                newrecrow.down('input[id$=txtNewRecipient]').value = '';
                input.value = newrecrow.down('input[id$=txtNewQty]').value;
                newrecrow.down('input[id$=txtNewQty]').value = '';
            }
        }

        var spanTitleId = String.format('{0}_lblRecipient', recipient.RecipientId);

        var trTitle =
            $.TR({ id: recipient.RecipientId },
                $.TD({ colSpan: '3', 'class': 'recipient' },
                    $.H3({},
                        $.SPAN({ id: spanTitleId }, recipient.Name)
                    )
                )
            );
        var trTotalId = String.format('{0}_subtotal', recipient.RecipientId);
        var spanTotalId = String.format('{0}_lblSubTotal', recipient.RecipientId);
        var trTotal =
            $.TR({ id: trTotalId },
                $.TD({ colSpan: '2', 'class': 'subtotal-text' },
                    $.DIV({}, 'Recipient Subtotal:')
                ),
                $.TD({ 'class': 'subtotal' },
                    $.SPAN({ id: spanTotalId }, '$0.00')
                )
            );
        var footer = this.getFooterRow();
        if (!footer) { footer = this.createFooterRows(); }
        footer.insert({ before: trTitle });
        footer.insert({ before: trTotal });
        return $(trTitle);
    },

    createItem: function(item) {
        var id = this.getItemRowId(item.RecipientId, item.ProductId);
        var tr =
            $.TR({ id: id, 'class': 'itemrow' },
                $.TD({ 'class': 'qty' },
                    $.SPAN({ id: id + '_lblQty' }, $.NBSP)
                ),
                $.TD({ 'class': 'desc' },
                    $.SPAN({ id: id + '_lblItem' }, item.ProductName)
                ),
                $.TD({ 'class': 'price' },
                    $.SPAN({ id: id + '_lblPrice' }, $.NBSP)
                )
            );
        var row = this.getRecipientTotalRow(item.RecipientId);
        row.insert({ before: tr });
        tr = $(tr);
        this.addHoverObserver(tr);
        return tr;
    },

    createFooterRows: function() {
        var trFooter =
            $.TR({ id: 'footerTotal' },
                $.TD({ colSpan: '3', 'class': 'total-text' },
                  $.H2({ style: 'float:left' }, 'Subtotal:'),
                    $.H2({ style: 'float:right' }, $.SPAN({ id: 'lblTotal' }, $.NBSP)
                    )
                )
            );
        this.tbody.insert(trFooter);
        var btn;
        var tr =
            $.TR({},
                $.TD({ colSpan: '4', 'class': 'checkout' },
                    $.DIV({},
                        btn = $.INPUT({ type: 'submit', value: 'Checkout', id: 'btnCheckout' })
                    )
                )
            );
        Event.observe(btn, 'click', function(e) {
            //TODO Add checkout functionallity
            e.stop();
            location.href = '/Cart/';
        });
        this.tbody.insert(tr);


        var style = 'line-height: 1px; height: 1px; border-width:0px';
        tr = $.TR({},
                $.TD({ 'class': 'qty', style: style }),
                $.TD({ 'class': 'desc', style: style }),
                $.TD({ 'class': 'price', style: style })
            );
        this.tbody.insert(tr);
        return $(trFooter);
    },

    getShoppingCart: function() {

        ShoppingCartHandler.GetShoppingCart(function(response) {

            var data = orderbot.parseJSON(response.value);
            var count = 0;
            var total = 0;
            if (data) {
                //alert("come in 1");
                count = data.ItemsCount;
                total = data.SubTotal;
            }

            var header = $('header');
            var span_lbShoppingCartItems = header.down('span[id$=lbShoppingCartItems]');
            var span_lbTotal = header.down('span[id$=lbTotal]');


            var cardInfos = $$('span[id$=lblShoppingCardInfo]');
            var cartContainer = $('cart-container');

            if (cartContainer) {
                var btchkout = cartContainer.down('input[id$=btnCheckout]');


                if (btchkout) {
                    btchkout.hide();

                    if (count > 0) {
                        btchkout.show();
                    }
                }

                //alert(btchkout.inspect());
            }

            cardInfos.each(
                function(cardInfo) {
                    //if (count > 0) {
                    // $(cardInfo).update(String.format('YOUR CART HAS {0} ITEMS', count));

                    $(span_lbShoppingCartItems).update(count);
                    $(span_lbTotal).update(total);
                    //}

                    var pos = cardInfo.cumulativeOffset();

                    // alert(pos.left + "--" + pos.top);

                    if (cartContainer) {

                        //cartContainer.setStyle({
                        //    position: 'fixed',
                        //    left: pos.left - 90 + 'px',
                        //    top: pos.top + 30 + 'px'
                        //});

                        cardInfo.setStyle({
                            cursor: 'pointer'
                        });
                    }

                    cardInfo.observe('click', function(e) { cartContainer.toggle(); });
                }
            )

        });


    },

    getShoppingCartNew: function() {


        var cardInfos = $$('span[id$=lblShoppingCardInfo]');
        var cartContainer = $('cart-container');

        cardInfos.each(
                function(cardInfo) {

                    var pos = cardInfo.cumulativeOffset();

                    // alert(pos.left + "--" + pos.top);

                    if (cartContainer) {
                        cardInfo.setStyle({
                            cursor: 'pointer'
                        });
                    }

                    cardInfo.observe('click', function(e) { cartContainer.toggle(); });
                }
            );

    }

});


