/**
 * 
 */
function showAddToCartPopup(data){
	//find the scroll offset
	var scrollTop = $(window).scrollTop();
	
	$("#cartDialog").html(data);
	$("#cartDialog").jqm(
			{
				modal:true,
				closeClass:'closeBox',
				onShow: function(h) {
					h.w.fadeIn(888);
				},
				onHide: function(h) { 
				      h.o.remove(); // remove overlay
				      h.w.fadeOut(888); // hide window
				    }
			});
	$("#cartDialog").css("top", scrollTop + "px");
	$("#cartDialog").jqmShow();
}

function myReplaceAll(value, orig, rep){
	var index = value.indexOf(orig);
	while (index>0){
		value = value.replace(orig, rep);
		index = value.indexOf(value.orig);
	}
	return value;
}

$.fn.serializeObject = function()
{
	encode = true;
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            //o[this.name].push(htmlEscapeString(this.value) || '');
            if (encode){
            	var newValue = myReplaceAll(this.value, '+', '~~~');
            	o[this.name].push(escape(newValue) || '');
            } else {
            	o[this.name].push(this.value || '');
            }
        } else {
            //o[this.name] = htmlEscapeString(this.value) || '';
        	if (encode){
        		//note: we need to do the following step because of the way that + signs are decoded (as spaces)
        		var newValue = myReplaceAll(this.value, '+', '~~~')
        		o[this.name] = escape(newValue) || '';
        	} else {
        		o[this.name] = this.value || '';
        	}
        }
    });
    if (encode){
    	o.isHttpEncoded='Y';
    }
    return o;
};

function handleAddToCartErrors(data){
	var errors = "";
	for(var x=0; x<data.errors.length; x++){
		errors = errors + '<p class="errorMsg">' + data.errors[x] + '</p>';
	}
	$('#atcErrors').html(errors);
	$('#atcErrors').slideDown();
}

function clearATCErrors(){
	$('#atcErrors').slideUp();
	$('#atcErrors').html('');
}

function updateHeaderCartCount(newCount){
	jQuery("#headerCartCount").html(newCount);
}

function disableAddToCartButtons(){
	$('.addToCart').attr('disabled', 'disabled');
}

function enableAddToCartButtons(){
	$('.addToCart').removeAttr('disabled');
}

function addProductToCart(id, catRefId){
	disableAddToCartButtons()
	$('#productId').val(id);
	$('#catalogRefIds').val(catRefId);
	$('#submitProductQty').val($('#productQty').val());
	$('#addToCartForm').submit();
}

function addListItemToCartQV(id, catRefId){
	$('#quickViewDetails').jqmHide();
	addListItemToCart(id, catRefId);
}
function addListItemToCart(id, catRefId){
	disableAddToCartButtons()
	$('#productId').val(id);
	$('#catalogRefIds').val(catRefId);
	$('#addToCartForm').submit();
}

$(document).ready(function(){
	$("#addToCartForm").live('submit', function(){
		clearATCErrors();
		try {
			var formData = jQuery(this).serializeObject();
			var submitButton = jQuery("#addToCartButton");
			var submitButtonName=submitButton.attr('name');
			formData[submitButtonName]=submitButtonName;
			formData.isAJAX='true';
			jQuery.post('/pal/product.jsp', formData, function(data){
				if (data.success){
					showAddToCartPopup(data.responseHTML);
					updateHeaderCartCount(data.cartCount);
				} else {
					handleAddToCartErrors(data);
				}
				enableAddToCartButtons()
			}, 'json').error(function(a,b,c){
				alert('error: ' + a)
			});
		} catch(e) {
			alert(e);
		}
		return false;
	})
})
