/**
 * cart.js
 */

/**
 * Add item to cart and notify user of result
 *
 * @param string Product SKU
 * @todo set order_id properly - necessary for editing
 */

var timeoutId = -1;

function addItemToCart(productId, quantity, productName)
{
    var cartData = '';
    updateCart('add', productId, quantity, productName, true, true);
    refreshOrderPage();
}

function updateCartQuantities()
{
    // get product and quantity for all items in cart
    var itemsArray = new Array();
    $('table tr td input.cartQty').each( function() 
      { 
        itemsArray.push(new Array($(this).parent().parent().attr('id'), $(this).val()));
      } 
    );
    
    // update all line items but do not refresh cart until down with all line items to prevent flickering.
    for(var i=0; i<itemsArray.length; i++)
    {
        updateItemQuantity(itemsArray[i][0], itemsArray[i][1], '', i==(itemsArray.length-1));
    }
    
    //refresh cart
    //viewCart();
    refreshOrderPage();
}

function updateItemQuantity(productId, quantity, productName, showCart)
{
    // explode was being used to hide price that wis being changed. But once multiple items were in the cart it got VERRRY slow
    //$("tr#" + productId + "  td > span[name=extPrice], tr > td.total > span, span[name=subtotal], span[name=tax], span[name=shipping], span[name=total]").effect("explode", {}, 500 ) ;
    updateCart('update', productId, quantity, productName, showCart);
}

function removeItemFromCart(productId, showCart)
{
    $("tr#" + productId).fadeOut("slow", 
      function() 
      {
          updateCart('remove', productId, 0, '', showCart, false);
          refreshOrderPage();
      } ) ;
}


function viewCart()
{
    updateCart('view', '', '', '', true);
}

function updateCart(action, productId, quantity, productName, showCart)
{
    $.get("/phpinc/cart_update.php", 
                {'product_id':productId, 'method':action, 'qty':quantity},
                function (data, textStatus)
                {
                    if ("success"==textStatus)
                    {
                        if (showCart)
                        {
                            displayCart(data, productId);
                        }
                        updateCartItemCount();
                    }
                    else
                    {
                        alert(data);
                    }
                }
            );
}

function displayCart(cartData, productIdToSelect)
{   
    // Build cart
    var content = '';
    
    // header 
    content += '<table width="100%" style="border-spacing:0">';
    
    // display cart data
    content += '<tr><td class="cartBody">';
    content += cartData;                                                           
    content += '</td></tr>';

    // highlight the product that was just updated
    if (productIdToSelect>0)
    {
        content += '<script>';
//        content += '$("tr#' + productIdToSelect + ' td > span[name=extPrice], tr > td.total > span, span[name=subtotal], span[name=tax], span[name=shipping], span[name=total]").hide().effect("pulsate", { times:2 }, 1000 ) ;';
        content += '$("tr#' + productIdToSelect + ' tr > td.total > span, span[name=total]").hide().effect("pulsate", { times:2 }, 1000 ) ;';
        content += '</script>';
    }
    
    content += '</table>';

    $('#dialog').empty();
    $('#dialog').append(content);
    $("#dialog").dialog({ autoOpen: false, 
                          modal: true, 
                          title: 'Your RECONYX Shopping Cart', 
                          width:600,
                          resizable:false,
                          buttons: { "Continue Shopping": function() { $(this).dialog("close"); },
                                     "Checkout": function() { window.location="/co/order.php"; } } });
    $("#dialog").dialog('open');
    
    if (1 == $("table tr#" + productIdToSelect + " td input.cartQty").length)
    {
        $("table tr#" + productIdToSelect + " td input.cartQty").select();
    }
    else
    {
        $("input:visible:first").select();
    }
    
}

function updateCartItemCount()
{
    var itemCount = 0;
    $.get("/phpinc/cart_update.php", 
                {'method':'count'},
                function (data, textStatus)
                {
                    if ("success"==textStatus)
                    {
                        if (data.length > 0)
                        {
                          itemCount = data;
                        }
                        if (1 == itemCount)
                        {
                            $("#cartCount").html(itemCount + ' item');
                        }
                        else
                        {
                            $("#cartCount").html(itemCount + ' items');
                        }
                    }
                    else
                    {
                        alert(data);
                    }
                }
            );

}

function refreshOrderPage()
{
    // if on the Order page, then we need to refresh it so that it shows the new order total
    var url = location.pathname;
    if (url.indexOf("order") > -1)
    {
        window.location.reload();
    }
}


function signIn(redirectOnSuccess)
{
    $.get("/module/user/login.php", 
                {'dialog':'true', 'referer': redirectOnSuccess},
                function (data, textStatus)
                {
                    if ("success"==textStatus)
                    {
                        $('#dialog').empty();
                        $('#dialog').append(data);
                        $("#dialog").dialog({ autoOpen: false, 
                                              modal: true, 
                                              resizable:false,
                                              title: 'Sign In', 
                                              width:420,
                                              buttons: {} });
                        $("#dialog").dialog('open');
                        $("#email").focus();
                    }
                    else
                    {
                        alert(data);
                    }
                }
            );
}

function signOut()
{
    $.get("/module/user/login.php", 
                {'action':'logout'},
                function (data, textStatus)
                {
                    if ("success"==textStatus)
                    {
                        // reload current page so that login area is updated
                        window.location.reload();
                    }
                    else
                    {
                        alert(data);
                    }
                }
            );
}

/*
// Opens the modify address dialog
// 'display'  options: 
//      'Ship': only show Shipping address
//      'Bill': only show Billing address
//      anything else will show both addresses
*/
function modifyAddress(customerId, display)
{
    $.get("/co/modify.php", 
                {'dialog':'1', 'id':customerId, 'display':display},
                function (data, textStatus)
                {
                    if ("success"==textStatus)
                    {
                        $('#dialog').empty();
                        $('#dialog').append(data);
                        dialogWidth = 920;
                        if ('SHIP' == display || 'BILL' == display)
                        {
                            dialogWidth = dialogWidth/2;
                        }
                        $("#dialog").dialog({ autoOpen: false, 
                                              modal: true, 
                                              title: 'Confirm Address', 
                                              resizable:false,
                                              width:dialogWidth,
                                              buttons: {} } );
                        $("#dialog").dialog('open');
                        $("input:first").focus();
                    }
                    else
                    {
                        alert(data);
                    }
                }
            );

}

