$(document).ready(function() {
    //wire up our entity add-to-cart
    $('#dialog').jqm();
    
    $('.AddToCartSmall').click(function() {
        //add this item to our cart
        var ids = $(this).attr('id').split('_');
        var productId = ids[1];
        var variantId = ids[2];

        //validate our quantity
        //var quantity = parseInt($('#Quantity_' + productId + '_' + variantId).val());
        var quantity = 1;
        
        if (quantity > 0) {
            DemacAddToCart(productId, variantId, quantity);
        } else {
            alert('Quantity must be greater than 0 to add to cart.');
        }

        return false;
    });

    var DemacAddToCart = function(productId, variantId, qtyToAdd) {
        $.get('addtocart.aspx', { ProductID: productId, VariantID: variantId, Quantity: qtyToAdd });

        //update our cart quantity in header
        var qtyCartItems = parseInt($("#hdCartItemCount").val());
        qtyCartItems = qtyCartItems + qtyToAdd;

        $("#Header_ltrNumCartItems").html(qtyCartItems);
        $("#hdCartItemCount").val(qtyCartItems);

        $('#dialog').jqmShow(); //show our dialog
    };
    

    String.prototype.trimEnd = function(c) {
        if (c)
            return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
        return this.replace(/\s+$/, '');
    }
    String.prototype.trimStart = function(c) {
        if (c)
            return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
        return this.replace(/^\s+/, '');
    }

    String.prototype.escapeRegExp = function() {
        return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
    };

    getUrlEncodedKey = function(key, query) {
        if (!query)
            query = window.location.search;
        var re = new RegExp("[?|&]" + key + "=(.*?)&");
        var matches = re.exec(query + "&");
        if (!matches || matches.length < 2)
            return "";
        return decodeURIComponent(matches[1].replace("+", " "));
    }
    setUrlEncodedKey = function(key, value, query) {

        query = query || window.location.search;
        var q = query + "&";
        var re = new RegExp("[?|&]" + key + "=.*?&");
        if (!re.test(q))
            q += key + "=" + encodeURI(value);
        else
            q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
        q = q.trimStart("&").trimEnd("&");
        return q[0] == "?" ? q : q = "?" + q;
    }
    
    

});


