/**
 * 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,.add-to-cart-regular").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 = parseFloat(data.PRICE) * parseInt(data.QTY);
					var practiceTrack = '';
					var productcode = data.PRODUCTCODE;
					var total = parseFloat(data.TOTAL);
					var qty = parseInt(qty);
					
								if (productcode != parseFloat(productcode)) {
									/* not a number use substring */
									if(productcode.substring(0,1)=='X') {
										/* this is an mp3, show onelicense ad */
										practiceTrack = '<div id="onelicense_ad_popup">With a Practice Track License from <a href="http://www.onelicense.net" target="_blank">OneLicense.net</a>, choir directors and leaders can now legally burn practice CDs or email the mp3s directly to your choir or ensemble! See <a href="http://www.onelicense.net" target="_blank">OneLicense.net</a> for more details on Practice Track licensing.</div>';
									}									
								}
										
										if(!data.RULE || data.RULE == 0) {
										
											$.jGrowl("<h1>Thank you!</h1>" + 
															 "<h2>You have added to your cart</h2>" + 
															 "<p>" + qty + " x \"" + data.TITLE + "\" for $" + price.toFixed(2) + "</p>" +  
															 "<p>Your shopping cart subtotal is $" + total.toFixed(2) + "</p>" +
															 "<div id='jgrowl-continue'><a href=''></a></div>" +
															 practiceTrack +
															 "<div id='jgrowl-cart'><a href='/cart'></a></div>", {
													speed:  'slow',
													theme: 'accessible',
													sticky: true,
													closer: false
											});
										}else{
											if(data.RULE==1) {
												$.jGrowl("<h1>Quantity Updated</h1>" + 
																 "<h2>The following item is already in your cart and the quantity has been updated</h2>" + 
																 "<p>" + data.TITLE + "</p>" + 
																 "<div id='jgrowl-continue'><a href=''></a></div>" +
																 "<div id='jgrowl-cart'><a href='/cart'></a></div>", {
														speed:  'slow',
														theme: 'accessible',
														sticky: true,
														closer: false
												});													
											}else if (data.RULE==2){
												$.jGrowl("<h1>Thank you!</h1>" + 
																 "<h2>The following album has eliminated the need for previously added tracks:</h2>" + 
															 	 "<p>" + qty + " x \"" + data.TITLE + "\" for $" + price.toFixed(2) + "</p>" +  
															     "<p>Your shopping cart subtotal is $" + total.toFixed(2) + "</p>" +
																 practiceTrack +
																 "<div id='jgrowl-continue'><a href=''></a></div>" +
																 "<div id='jgrowl-cart'><a href='/cart'></a></div>", {
														speed:  'slow',
														theme: 'accessible',
														sticky: true,
														closer: false
												});	
											}else if (data.RULE==3){
												$.jGrowl("<h1>Thank you!</h1>" + 
															 "<h2>You have added a pre-order to your cart.  You will be invoiced later for this product.</h2>" + 
															 "<p>" + qty + " x \"" + data.TITLE + "</p>" +  
															 "<p>Your shopping cart subtotal is $" + total.toFixed(2) + "</p>" +
															 "<div id='jgrowl-continue'><a href=''></a></div>" +
															 practiceTrack +
															 "<div id='jgrowl-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,
													closer: false
												});														
											}										
										}
                    
                    $('#continue').click(function(){
						$(this.element).find('div.jGrowl').remove();
                        return false;
                    });

                }, "json");

            return false;
        });

    });
})(jQuery);
