/// <reference path="~/js/jquery-1.3.1.min.js" />
function isInteger(s) { return (s.toString().search(/^-?[0-9]+$/) == 0); }
function isUInteger(s) { return (s.toString().search(/^[0-9]+$/) == 0); }
//integer greater then 1
function isUInteger_g1(s) { return (s.toString().search(/^[1-9]+$/) == 0); }


function AddProduct(pid, qid) {
    var q = $(qid)[0].value;
    //q must be an integer.
    if (!isUInteger_g1(q)) {
        alert("Error: Quantity must be an integer > 0");
        return;
    }
    //Clear the success/failure classes
    $("#msgResult").removeClass("sucess failure");
    //Display Modal

    $("#msgHeader").html("<p>Processing...</p>");
    $("#msgResult").html("");
    $('#basicModalContent').modal({
        onOpen: function(dialog) {
            dialog.overlay.fadeIn('slow', function() {
                dialog.container.slideDown('slow', function() {
                    dialog.data.fadeIn('slow');
                });
            });
        } 
    });

//
    //this.preventDefault();
    //Call server to add product.Prepair, JSON string for the input.
    var inputDataStr = "{'userKey':'" + $("#UserKey")[0].value + "','prodIdStr':'"+ pid + "','quantityStr':'" + q + "' }";
    //"{'userKey':'Chris','prodIdStr':'Brandsma','quantityStr':'zz' }"
    // (string , string , string )
    //"firstName = H & lastName = Singh",
    $.ajax({
        type: "POST",
        url: "/WFlourWebService.asmx/AddProduct",
        data: inputDataStr,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: Error_AddProduct,
        success: Result_AddProduct
    });
}

//Function called when Server return the result of add product
function Result_AddProduct(msg) {
  var d = msg;      
  if(msg.d)
    d = msg.d;       
    if (d.Success) {
        $("#msgHeader").html("<h3>Item has been added! </h3>");
        $("#msgResult").html(d.Message + "<br/>" ).addClass("success");
        //Update the basket count
        $("#account-links li a:first").fadeOut('slow').html("My basket (" + d.CartCount + ")").fadeIn('slow');
    }        
    else {
        $("#msgHeader").html("<h3>An Error has occourd!</h3>");
        $("#msgResult").html(d.Message).addClass("failure");
    }
}
//Called if server response specfic error returned from add product
function Error_AddProduct(XMLHttpRequest, textStatus, errorThrown) {
    $("#msgHeader").html("<h3>An Error has occourd!</h3>");
    $("#msgResult").html("Could not add the Product! Please try agin<br/>" + textStatus + "<br/>" + errorThrown).addClass("failure");
}