// ecommerce.js defines the event handlers and AJAX required to support the Psycards shopping experience
// Author: Alex Dean
// Created: 12 May 2010
// Last updated: 13 May 2010

/*********************** ON READY EVENT ***********************/

// Add event handlers once the page is ready.
$(document).ready(function() {

    // Event handler for adding a product to the basket.
    jQuery('a.addOneProduct').click(function(){
        // Call the add product AJAX function. The id is set to the product SKU.
        addProduct(jQuery(this).attr('id'));
        return false;
    });

    // Add an updatePricing trigger to the controls which effect pricing (identified by class pricingImpact).
    jQuery(".pricingImpact").change(function(){
        updateProduct(jQuery(this).attr('id')); // The id for the quantity field is just the product SKU
    });

    // Need to make sure we're always displaying the current shopping basket contents.
    getBasket();
});

/*********************** ADD/UPDATE PRODUCT ***********************/

// AJAX to call CI and add 1 unit of a product to the basket.
function addProduct(productSKU) {

    jQuery.ajax({
        url: '/ecommerce/add_product',
        data: { productSKU: productSKU },
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            displayBasketSummary(data);
            notifyProductAdded(productSKU);
        },
        error: function(xhr, ajaxOptions, thrownError){
            // alert(xhr.status);
            // alert(xhr.statusText);
            // alert(xhr.responseText);
        }
    });
}

// Function to pop up a message telling the user that the product has been added.
function notifyProductAdded(productSKU) {
    // Notify Google.
    _gaq.push(['_trackEvent', 'Ecommerce', 'Add Product', productSKU]);

    // Notify user.
    jQuery.jGrowl("Product added to your shopping basket.");
}

// Updates the product quantity in the basket when a quantity is changed
function updateProduct(productSKU) {

    // First need to retrieve the new quantity for the product.
    productQuantity = jQuery('#' + productSKU).val(); // The quantity field just has id of PSY01 or whatever

    jQuery.ajax({
        url: '/ecommerce/update_product',
        data: { productSKU: productSKU, productQuantity: productQuantity },
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            displayBasketMain(data);
            notifyProductUpdated(productSKU);
        },
        error: function(xhr, ajaxOptions, thrownError){
            // alert(xhr.status);
            // alert(xhr.statusText);
            // alert(xhr.responseText);
        }
    });
}

// Function to pop up a message telling the user that the product has been added.
function notifyProductUpdated(productSKU) {
    // Notify Google.
    _gaq.push(['_trackEvent', 'Ecommerce', 'Update Product', productSKU]);

    // Notify user.
    jQuery.jGrowl("Product quantity updated.");
}

/*********************** GET SHOPPING BASKET ***********************/

// AJAX to get the current basket contents. Where we render this depends upon which basket is visible on the page
function getBasket() {

    basketSummaryPresent = (jQuery('#basketSummary').length != 0);
    basketMainPresent = (jQuery('#basketMain').length != 0);

    // Only run if the basket exists on this page.
    if (basketSummaryPresent || basketMainPresent) {

        jQuery.ajax({
            url: '/ecommerce/get_basket',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                if (basketSummaryPresent) {
                    displayBasketSummary(data);
                } else {
                    displayBasketMain(data);
                }
            },
            error: function(xhr, ajaxOptions, thrownError){
                // alert(xhr.status);
                // alert(xhr.statusText);
                // alert(xhr.responseText);
            }
        });
    }
}

/*********************** DISPLAY SHOPPING BASKETS ***********************/

// Displays the main shopping basket on the checkout page
function displayBasketMain(jsonBasket) {

    // Now let's update to show the current shopping basket contents.
    jQuery.each(jsonBasket.items, function(i, item){
        jQuery('#' + item.sku + 'Total').html(item.cost);
        jQuery('#' + item.sku).val(item.quantity); // Quantity field just uses SKU
        jQuery('#' + item.sku + 'LocalisedUnitPrice').html(item.localisedUnitPrice);
        jQuery('#' + item.sku + 'LocalisedTotalPrice').html(item.localisedTotalPrice);
    });

    // Also show the total cost for all products
    jQuery("#totalCost").html(jsonBasket.totalCost);
}

// Function to display shopping basket on page.
function displayBasketSummary(jsonBasket) {

    // First let's clear the current contents
    jQuery('#basketSummaryItems').children().remove();

    basketHasContents = false;

    // Now let's update to show the current shopping basket contents.
    jQuery.each(jsonBasket.items, function(i, item){
        if (item.quantity > 0) {
            basketHasContents = true;
            jQuery('#basketSummaryItems').append('<tr><td class="checkout" width="80px">' + item.name + '</td><td class="checkout" width="20px">' + item.quantity + '</td><td class="checkout" width="25px">' + item.localisedTotalPrice + '</td></tr>');
        }
    });

    if (basketHasContents) {
        jQuery('#basketSummary').show();
    } else {
        jQuery('#basketSummary').hide();
    }

    // Don't do anything with the go-to-shop button if it's not present on the page
    if (jQuery('#shopbutton').length != 0) {
        // If the basket is visible, hide the go-to-shop button
        if (jQuery('#basketSummary').length != 0 && jQuery('#basketSummary').is(':visible')) {
            jQuery('#shopbutton').hide();
        } else { // Show the button
            jQuery('#shopbutton').show();
        }
    }

}

/*********************** LEGACY PSYCARDS V1 CODE ***********************/

// Validate customer's details for ordering Psycards.
function check_form() {
		var elems = new Array();
		elems = document.getElementsByTagName('input');
		for (i=0;i<elems.length;i++)
		{
			if(elems[i].name=="giftv")
			{
				continue;
			}
			if (elems[i].type=="text"&&elems[i].value&&elems[i].name=="Email")
			{
				 var tfld =trim(elems[i].value);

				 var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
 				 if (!email.test(tfld))
				 {
				 	 alert("Invalid email address")
			 		 elems[i].focus();
			         return false;
				 }
			}
			else if (elems[i].type=="text"&&!elems[i].value&&elems[i].name!="address2")
			{
			 alert("Please fill in all required fields")
			 elems[i].focus();
			 return false;
			}
		}
}