/**
 * AJAX add to cart
 *
 * 1. Send form using AJAX POST request
 *   1a. Add to basket and return JSON response (server)  
 * 2. Open jGrowl popup using callback
 * 3. Print product title, price and total price in popup 
 */

function getQueryArray(qs) {
    var args = qs.split('&');
    var params = {}

    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);
        var value = (pair.length==2)
            ? decodeURIComponent(pair[1])
            : name;

        params[name] = value;
    }

    return params;
 }

(function($){
    $(document).ready(function(){

        $.jGrowl.defaults.position = 'center';

        $(".add-to-cart").submit(function() {

        	$(this.element).find('div.jGrowl-notification:parent').remove();

            var id = getQueryArray($(this).attr('action')).prod;
            var url = "/cart/index.cfm?go=main.addnew&prod=" + id;
            //var url = "/gia/json.php?go=main.addnew&prod=" + id;
            var q = $(this).find(":input[name=qty]").val();

            // because of form-table bug on products list
            if (q == undefined) {
            	q = $(this).next().find(":input[name=qty]").val();
            }

            if (q == undefined) {
            	q = 1;
            }

            $.post(url, { qty: q },
                function(data){
            	
            	    var price = data.PRICE * data.QTY;

                    $.jGrowl("<h1>Thank you!</h1>" + 
                             "<h2>You have added to your cart</h2>" + 
                             "<p>" + data.QTY + " x \"" + data.TITLE + "\" for $" + price.toFixed(2) + "</p>" +  
                             "<p>Your shopping cart subtotal is $" + data.TOTAL.toFixed(2) + "</p>" +
                             "<div id='continue'><a href=''></a></div>" +
                             "<div id='cart'><a href='/cart'></a></div>", {
                    	/*beforeOpen: function(e,m,o) {
                             //remove existing jgrowls
                             $(this.element).find('div.jGrowl-notification').remove();
                        },*/ 
                        speed:  'slow',
                        theme: 'accessible',
                        sticky: true
                    });
                    
                    $('#continue').click(function(){
                        $(this.element).find('div.jGrowl-notification:parent').remove();
                        return false;
                    });

                }, "json");

            return false;
        });

    });
})(jQuery);