
var Digirama = Digirama || {};
var debug = false;

Digirama.remote = {

    addToCart: function(mediaLicenseIds, callback) {
        if (debug) {
        	alert("addToCart: " + mediaLicenseIds);
        }
        else {
	        $.ajax({
	            url:"http://checkout.islandrecordsaustralia.com/shopbroker.ashx",
	            dataType: "jsonp",
	            jsonpCallback: 'processCartAdd',
	            data: {
	                mediaLicenseId: mediaLicenseIds
	            },
	            success: callback
	        });
	      }
    },

    getCartSummary: function(callback) {
        $.ajax({
            url:"http://checkout.islandrecordsaustralia.com/shopbroker.ashx",
            dataType: "jsonp",
            jsonpCallback: 'processCartAdd',
            success: callback
        });
    },

    getCheckoutUrl: function() {
        return "http://checkout.islandrecordsaustralia.com/checkout.aspx";
    },
    
    getVouncherRedeemUrl: function() {
        return "javascript:OpenModalWindow('','LogInWindow','')";
    },
    
    getMyAccountUrl: function() {
        return "javascript:OpenModalWindow('','LogInWindow','')";
    },
    
    getPurchaseHistoryUrl: function() {
        return "javascript:OpenModalWindow('','LogInWindow','')";
    }
};

Digirama.cart = function() {

    var showCartSummary = function() {
        Digirama.remote.getCartSummary(getCartSummaryCompleted);
    };

    var addToCartCompleted = function(data) {
        if (data.returnCode == 0) {
            $.jGrowl("Sorry, this item could not be added to your cart at this time.", {
                theme:  'error'
            });
            return;
        }
        else if (data.returnCode == 2) {
            $.jGrowl("This item is already in your cart.", {
                theme: 'warning'
            });
            return;
        }
        else if (data.returnCode == 3) {
            $.jGrowl("Sorry! Pre-orders can't be made in conjunction with any other purchase.", {
                theme: 'preorder'
            });
            return;
        }

        $.jGrowl("This item has been added to your cart.");
        showDigiramaData(data);
    };

    var getCartSummaryCompleted = function(data) {
        if (data.returnCode == 0 || data.returnCode == 2) {
            $.jGrowl("Sorry, we could not access your cart at this time.", {
                theme:  'error'
            });
            return;
        }

        showDigiramaData(data);
    };

    var showDigiramaData = function(data) {
        $("#cartCount").text(data.totalItems);
        $("#cartPrice").text(data.totalValue);

        if (data.creditBalance != '') {
            $("#cartCreditBalance").text(data.creditBalance);
            $("#storeCredit").addClass("show");
        }
    };

    var enableCartButtons = function() {
    		$("a.btn-cart").bind("click", function() {
    				var numericExp = /^[0-9]+$/;
            var mediaLicenseId = $(this).attr("medialicenseid");
            var qtyInput = $("input#"+mediaLicenseId);
            var count = parseInt(qtyInput.val());
            
            if (mediaLicenseId == "null") {
                if ($(this).hasClass("Apparel")){
	                $.jGrowl("Please select a size", {
	                    theme:  'selectsize'
	                });
	              }
	              else {
		              $.jGrowl("Please select a bonus", {
	                    theme:  'selectbonus'
	                });
	              }

                return false;
            }     
            
            if (qtyInput.length && (!qtyInput.val().match(numericExp) || count == 0)) {
                $.jGrowl("Please select a quantity", {
                    theme:  'selectquantity'
                });

                return false;
            }     
            
            Digirama.remote.addToCart(getMediaLicenseIDs(mediaLicenseId, count), addToCartCompleted);
        });
    };
    
    var enableMerch = function() { 
	    if ($("#merchselect").length) {
	    	var availableItem = getFirstAvailableOption();
  			
  			if (availableItem.length) {
  				var medialicenseid = availableItem.attr("medialicenseid");
					var mediatype = availableItem.attr("data-type");
										
					$(".pricetype strong").text(availableItem.attr("data-price"));
					$(".pricetype span").removeClass("Unavailable").addClass(availableItem.attr("data-availability"));
					$("input.qty").addClass(mediatype).attr("id", medialicenseid).attr("name", medialicenseid);
					$(".pricetype #buymerch").addClass(mediatype).attr("medialicenseid", medialicenseid).text("Buy " + mediatype);
					
					return;
  			}
  			
  			$("#PurchaseLinks span.Unavailable").remove();
			}
			
			$(".purchase-unavailable").remove();
    }
    
    var getFirstAvailableOption = function() {    	
    	var firstAvailableItem = $("#merchselect option[data-availability='Available']");
    
    	if(!firstAvailableItem.length){
    		firstAvailableItem = $("#merchselect option[data-availability='PreOrder']");
    	}
    
    	return firstAvailableItem;
    }
    
    var disableDigitalQuantity = function() {
    		$("input.AlbumDownload").attr("disabled", "true");
    }
    
    var getMediaLicenseIDs = function(mediaLicenseId, count) {
    		var totalIDs = mediaLicenseId;
    		
    		for (var i = 1; i < count; i++) {
    			totalIDs += "," + mediaLicenseId;
    		}
    		
        return totalIDs;
    }

    var enableCheckoutButtons = function() {        
        $("a[href*='checkout.aspx']").filter(function() {
            return (/digirama\/checkout.aspx/i).test($(this).attr('href'));
        }).each(function() {
            $(this).attr("href", Digirama.remote.getCheckoutUrl());
        });
    };
    
    var enableQuickLinkButtons = function() {
        $("a[href*='voucherredeem.aspx']").filter(function() {
            return (/digirama\/voucherredeem.aspx/i).test($(this).attr('href'));
        }).each(function() {
            $(this).attr("href", Digirama.remote.getVouncherRedeemUrl());
        });

        $("a[href*='myaccount.aspx']").filter(function() {
            return (/digirama\/myaccount.aspx/i).test($(this).attr('href'));
        }).each(function() {
            $(this).attr("href", Digirama.remote.getMyAccountUrl());
        });

        $("a[href*='purchasehistory.aspx']").filter(function() {
            return (/digirama\/purchasehistory.aspx/i).test($(this).attr('href'));
        }).each(function() {
            $(this).attr("href", Digirama.remote.getPurchaseHistoryUrl());
        });
    };

    var init = function() {
        showCartSummary();
        enableMerch();
        enableCartButtons();
        enableCheckoutButtons();
        enableQuickLinkButtons();
        disableDigitalQuantity();
    };

    return {
        init: init
    };
}();

jQuery(function() {
    Digirama.cart.init();
});
