﻿jQuery(function() {

    // this function is called from the server control when using a non-standard clicking button without the OnClientClick.
    jQuery('[x-designercontrol-addproducttocartform-clickevent]').click(function() {
        alert('TODO: this jquery click method is finished, but might need a final test!');

        //var productId = jQuery(this).siblings('.productid').val();
        //var quantity = jQuery(this).siblings('.quantity').val();

        var parentContainer = jQuery(this).parents('[x-designercontrol-addproducttocartform-container]'); // it may not be the direct parent up, depending on how the button control is rendered.
        var quantity = parentContainer.children('[x-designercontrol-addproducttocartform-quantity]').val();
        var productID = parentContainer.attr('x-designercontrol-addproducttocartform-productid');


        if (designerControl_AddProductToCartForm_ValidateQuantity(quantity) == true) {
            addProductToCart({ 'quantity': quantity, 'productid': productID });
        }
    });



    // refresh any update panels if said in the RefreshUpdatePanelOnAddControlID property of the AddProductToCartForm control.
    jQuery('[x-designercontrol-addproducttocartform]:first').each(function() { // make sure we only take 1 because there will be lots of 'x-designercontrol-addproducttocartform' on the page, but only one UpdatePanel
        var updatePanelId = jQuery(this).attr('id');
        __doPostBack(updatePanelId, 'customPostback');
        //__doPostBack('<%=UpdatePanelCartBar.ClientID%>', 'customPostback');
    });
});

// this function is called from the server control when using an OnClientClick button.
function onClick_DesignerControl_AddProductToCartForm_Button(o) {
    //alert('click2');

    //var productID = o.productid;
    var clientID = o.clientid;
    var uniqueID = o.uniqueid;
    var quantityClientID = o.quantityclientid;


    //var quantity = o.quantity;
    var parentContainer = jQuery("#" + clientID);



    //remember the quantity control is optional.
    var quantity = 1;
    if (parentContainer.find('[x-designercontrol-addproducttocartform-quantity="me"]').val() !== undefined) {
        quantity = parentContainer.find('[x-designercontrol-addproducttocartform-quantity="me"]').val();
    }
    if (quantity == '')
        quantity = 1;


    var quantityControl = parentContainer.children('[x-designercontrol-addproducttocartform-quantity]');
    var productID = parentContainer.attr('x-designercontrol-addproducttocartform-productid');

    //alert(quantity);

    if (designerControl_AddProductToCartForm_ValidateQuantity(quantity) == true) {
        DesignerControl_AddProductToCartForm_AddProductToCart({ 'quantity': quantity, 'productid': productID });
    }
}

function designerControl_AddProductToCartForm_ValidateQuantity(quantity) {
    if (quantity == "" || quantity == "0") {
        alert("Please enter a quantity and try again.");
        return false;
    }
    return true;
}



function DesignerControl_AddProductToCartForm_AddProductToCart(p) {

    var formId = p.formId;
    var formData = jQuery('#' + formId).serializeArray();

    var w = p.width;
    var h = p.height;

    if (!w)
        w = 520;
    if (!h)
        h = 360;

    var width = w;
    var height = h;
    var quantity = p.quantity;
    var productId = p.productid;
    /*
    if (quantity === undefined) {
    jQuery.each(formData, function(i, field) {
    if (field.name == "quantity") {
    quantity = field.value;
    }
    });
    //quantity = formData.last().value;
    }

    if (productId === undefined) {
    jQuery.each(formData, function(i, field) {
    if (field.name == "productid" || field.name == "productId") {
    productId = field.value;
    }
    });
    //productId = formData.productid;
    }
    */
    var params = {
        'quantity': quantity,
        'productid': productId
    };
    var nocache = jQuery.jqModweb.random();

    jQuery.ajax({
        async: false,
        type: 'post',
        //data: formData,
        data: params,
        url: '/_framework/modules/carts/ajax/addProductToCart.asp',
        cache: false,

        success: function(data, status) {
            if (typeof modweb_designer_cartbar_updateAll !== 'undefined') {
                modweb_designer_cartbar_updateAll({'showLoader':true});
            }
            //updateCartContainer();

            jQuery('body').append('<div id="addToCartModalContainer" style="width:' + width + 'px;height:' + height + 'px;margin-left:' + (Math.round(width / 2) * -1) + 'px;display:none;" class="jqmWindow" ></div>');
            //var html = '<iframe width="100%" height="100%" frameborder="0" src="/_framework/modules/carts/ajax/displayAddProductToCartResults.asp">Loading...</iframe>';
            //jQuery('#addToCartModalContainer').html(html).jqm({ modal: true }).jqmShow();
            jQuery('#addToCartModalContainer').jqm({ ajax: '/_framework/modules/carts/ajax/displayAddProductToCartResults.asp?nocache=' + nocache, modal: true }).jqmShow();




        },
        error: function(data, status) {
            // debugger;
            alert('Your product could not be added to the cart at this time.\r\n\r\n\r\nThe error is as follows:\r\n\r\n' + data.statusText + "\r\n\r\n" + data.responseText);
        }
    });
}