//Called by Validate Reponse to unbind and rebind for the next click
function ProjectBuilderModify(pid) {
  //identify current state
	if ($('#pc' + pid + ' img').attr("src").indexOf("uncheck") > 0) {
	  ValidateResponse(pid, 'add');
	} else {
	  ValidateResponse(pid, 'remove');
	}
};
var modifyCart = function(pid, rType) {
  productId = pid;
  var ajaxResponse;
  if (rType == "add") {
    cUrl = "/cart/ajaxAddPBItem.asp";
  }
  else {
    cUrl = "/cart/ajaxRemovePBItem.asp";
  }
  //ajax call here
  var ajaxResponse = $.ajax({
    type: "GET",
    async: false,
    url: cUrl,
    data: "ProductId=" + productId,
    dataType: "html",
    timeout: 5000
  }).responseText;
  return ajaxResponse;
};
function ValidateResponse(pid, rType) {
	//Add to cart
  ajaxResponse = modifyCart(pid, rType);
  
	//Evaluate Response
	if (isNaN(ajaxResponse)) {
		//Handle something strange (didn't return a number show general error) -- this should never happen.
	  alert("Sorry the " + rType + " from list feature did not work.  Please try " + rType + "ing to the project builder from the detail page.");
	}
	else {
		//convert ajaxResponse to a number
	  ajaxResponse = ajaxResponse - 0;
		
		if(ajaxResponse >= 0) {
			//success update counter on page
			//alert("success cart count = " + ajaxResponse)
			//swap image with checked image
			if(rType == "add") {
				$('#pc' + pid +' img').attr("src","/images/assets/checkbox_checked.jpg");
			} else {
				$('#pc' + pid +' img').attr("src","/images/assets/checkbox_uncheck.jpg");
			}
			if(ajaxResponse == 0) {
			  $('#pbcount').empty();
			} else {
				$('#pbcount').empty().append("&nbsp;("+ ajaxResponse + ")&nbsp;");
			}
	  } 
		else {
			//Handel Numeric error
			switch(ajaxResponse) {
				case -1 : 
					NotLoggedIn();
					break;
				case -2 : 
					alert("vb error");
					break;
			}
		}
	}
};
function NotLoggedIn() {
	if(confirm("You need to be signed in to use the Project Builder.\n\nWould you like to Sign-In Now?")) {
		window.location = "/cart/AddPBItem.asp?ProductId=" + productId;
	} 
};
