$(document).ready(function() {
    // If we have a qlDialog, create the Quick Look dialog object
    var $qlDialog = $("#qlDialog");
    if ($qlDialog.length > 0) {
        $qlDialog.dialog( { draggable: false, autoOpen: false, resizable: false, height: 240, width: 420 });
    }
    
    // Check for bad images
    $('#productArea img').each(
        function(i) {
            var $img = $(this);
            $img.error(
                function() {
                    this.src="https://www.twopeasinabucket.com/graphics/brk_img_100x100.gif";
                }
            );
        }
    );
    
    // Display Buy All bar
    var $buyAllBar = $('#buyAllBar');
    if ($buyAllBar) {
        var $buyButtonAreas = $('span[@id^="buyButtonArea"]');
        if ( $buyAllBar.length > 0 && $buyButtonAreas.length > 0 ) {
                
            $buyAllBar.show()
            
            var quantity = document.getElementById('multiBuyQuantity').value;
            var product_list = "";
            
            $buyButtonAreas.each( function (i) {
                var prod = this.id.split('_')
                product_list += prod[1] + ',';
            });
            if ( product_list.slice(-1) == ',' ) { product_list = product_list.slice(0, -1); }
            
            $('#multiBuyButton').click( function () {
                $.post('/bucket_additem_many.asp',
                    { 'product_list': product_list, 'theQuantity': quantity },
                    function (data) {
                        $buyButtonAreas.html('<span class="standouttext">Item Added To Cart</span>');
                        $buyAllBar.html('<span class="standouttext">All Items Added To Cart</span>');
                    }
                );
            });
        }
    }
});

/*
    Update the Quick Look body and Display
*/
function updateQL(text) {
    $qlDialog = $("#qlDialog");
    $qlDialog.html(text);
    $qlDialog.dialog("open");
}

/*
    Add a product to the user's cart
*/
function addToBucket(form) {
    var $form = $(form);
    var product_id = $form.attr("id").split('_')[1]
    var $statusArea = $('#addStatusArea_' + product_id)
    
    // Add to bucket callback
    function addToBucketCallback(data) {
        // Check if this item was already in the cart
        if (data.search(":") >= 0) {
            $statusArea.html("Item Added To Cart");
            showAddedToCartDialog(data);
        } else {
            $statusArea.html("Item Already In Cart");
        }
        return false;
    }
    
    // Hide the quick look, hide the form and display some status
    $("#qlDialog").dialog("close");
    $form.hide();
    $statusArea.html('Adding item to cart...').show();
    
    // Ajaxify the form and submit
    $form.ajaxForm();
    $form.ajaxSubmit({success: addToBucketCallback, url: '/AJAX/bucket_additem_ajax.asp'});
}

/*
    Display Added To Cart Dialog
*/
function showAddedToCartDialog(data) {
    a = data.split(":");
    var request = {
        totalCost: a[0],
        itemsInBucket: a[1],
        cartTotal: a[2],
        curProductId: a[3],
        priceEach: a[4],
        itemQuantity: a[5],
        isLoggedIn: a[6]
    }

    // Header Cart Summary
    $("#headerItemsInBucket").html(request.itemsInBucket);
    $("#headerCartTotal").html(request.cartTotal);

    // Panel Cart Summary and Link
    var panelFooter = "<br />Items in Cart: " + request.itemsInBucket + "&nbsp;&nbsp;|&nbsp;&nbsp; Cart Subtotal: " + request.cartTotal 
    if (request.isLoggedIn == "1") {
        var url = ""
    } else {
        var url = "_offline"
    }
    panelFooter += '<br /><a href="/shop' + url + '_bucket.asp">View Cart</a>'    
    
    // Product Image
    icon = '<img style="margin-left: 5px;" src="http://is.twopeasinabucket.com/product_images/' + request.curProductId + 's.jpg">'
    
    // Dialog HTML
    var boxHTML = '<b>' + document.getElementById('productName_' + request.curProductId).innerHTML + '</b>';
    boxHTML += '<table><tr><td>Price:</td><td>' + request.priceEach + '</td></tr>'
    boxHTML += '<tr><td>Quantity:</td><td>' + request.itemQuantity + '</td></tr>'
    boxHTML += '<tr><td>Total:</td><td>' + request.totalCost + "</td></tr></table>"
    
    // Create the Dialog and display
    showTopRightNotification("Item Added To Cart", boxHTML, panelFooter, icon)
}

/*
    Add a product to the user's wishlist
*/
function addToWishList(product_id) {
    // Throbber
    if ( $('#addToWishImg').length > 0 ) {
        $('#addToWishImg').show();
    } else {
        $('#addToWishText_' + product_id).html('<span class="standouttext">Adding To Wishlist...</span>');
    }

    // Doit
    $.get("/bucket_additem.asp",
        { ajax: "true", wish: "1", 'product_id': product_id },
        function(data) {
            if ( $('#addToWishImg').length > 0 ) {
                $('#addToWishImg').hide();
                $('#addToWishText').html('<span class="standouttext">Item added to your wishlist</span>');
            } else {
                $('#addToWishText_' + product_id).html('<span class="standouttext">Item added to your wishlist</span>');
            }
        }
    );
}
var addToWish = addToWishList;

/*
    Add a product to the user's Bookmarks
*/
function addToBos(product_id) {
	$("#addToBosImg").show();
    $.get("/bos_add_ajax.asp", {t: 'PROD', id: product_id}, function(data) {
        $("#addToBosText").html("<span class=\"standouttext\">Item added to your bookmarks</span>");
	    $("#addToBosImg").hide();
    });
	return false;
}

/*
    Add a product to a user's recommended produts
*/
function addToRecommended(product_id) {
	$("#addToRecommendedImg").show();
    $.get("/AJAX/addToRecommendedProducts.asp", {product_id: product_id}, function(data) {
        $("#addToRecommendedText").html("<span class=\"standouttext\">Item added to your recommended products</span>");
	    $("#addToRecommendedImg").hide();   
    });
	return false;
}
