$(function(){ 
    addToCart = function(prodID) {
        clearForm();
        $.getJSON("/scripts/ajax_functions.php?t=getProduct&pid=" + prodID, function(json) {
            var prodRow = json.results;
            $('#a2c_prodID').text(prodRow.ID);
            $('#a2c_prodPrice').text(prodRow.Price);
            $('#a2c_prodTotalPrice').text("Price: R" + formatNumber(prodRow.Price) + " incl. VAT");
            $('#a2c_prodThumb').attr("src", "img/products/thumbs/" + prodRow.ID + ".jpg");
            $('#prodName').text(prodRow.Name);
            $("#a2c_prodQuantity").text("1")
            $('#addToCartDialog').dialog('open');    
        });                                
    }
    
    $.fx.speeds._default = 500;                          

    $('#addToCartDialog').dialog({
        open: function(event, ui) {
            $(this).css({'max-height': 400, 'overflow-y': 'auto'}); 
        }, 
        bgiframe: true,
        modal: true,
        autoOpen: false,
        resizable: false, 
        maxHeight: 400,
        width:400,
        title: 'Add To Cart',
        position: ['center',10],
        buttons: {
            'Cancel': function() {
                $(this).dialog('close');
            },
            'Add To Cart': function() {
                if ($("#frm_addToCart").valid()) {
                    submitForm();     
                } 
            }
        }
    });
    
    $("#a2c_shipName").autocomplete("scripts/ajax_functions.php?t=searchShipping", {
        dataType: 'json',
        limit:10,
        parse: function(data) {
            var rows = new Array();
            if (data.length) { 
                for(var i=0; i<data.length; i++){
                    rows[i] = {
                        data:data[i],
                        value:data[i].ShippingAddress1
                    };
                }
            }
            return rows;
        },
        formatItem: function(row, i, n) {
            returnStr = "";
            returnStr += row.RecipientName + "<br />";
            returnStr += row.ShippingAddress.replace(/\n/g,'<br />') + "<br />";
            returnStr += row.ShippingDate;
            return returnStr;
        }
    }).result(function(event, item) {
        $('#a2c_shipName').val(item.RecipientName);
        $('#a2c_shipTel').val(item.RecipientTel);
        $('#a2c_shipAddress1').val(item.ShippingAddress1);
        $('#a2c_shipAddress2').val(item.ShippingAddress2);
        $('#a2c_shipAddress3').val(item.ShippingAddress3);
        $('#a2c_shipProvince').val(item.ShippingProvince);
        $('#a2c_shipCity').val(item.ShippingCity);
        $('#a2c_shipPostalCode').val(item.ShippingPostalCode);
        $('#a2c_shipDate').val(item.ShippingDate);
        $('#a2c_shipInstructions').val(item.ShippingSpecialInstructions);
    });
        
    $("#a2c_shipAddress1").autocomplete("scripts/ajax_functions.php?t=searchShipping", {
        dataType: 'json',
        limit:10,
        parse: function(data) {
            var rows = new Array();
            if (data.length) { 
                for(var i=0; i<data.length; i++){
                    rows[i] = {
                        data:data[i],
                        value:data[i].ShippingAddress1
                    };
                }
            }
            return rows;
        },
        formatItem: function(row, i, n) {
            returnStr = row.ShippingAddress.replace(/\n/g,'<br />') + "<br />";
            returnStr += row.ShippingDate;
            return returnStr;
        }
    }).result(function(event, item) {
        $('#a2c_shipAddress1').val(item.ShippingAddress1);
        $('#a2c_shipAddress2').val(item.ShippingAddress2);
        $('#a2c_shipAddress3').val(item.ShippingAddress3);
        $('#a2c_shipProvince').val(item.ShippingProvince);
        $('#a2c_shipCity').val(item.ShippingCity);
        $('#a2c_shipPostalCode').val(item.ShippingPostalCode);
        $('#a2c_shipDate').val(item.ShippingDate);
        $('#a2c_shipInstructions').val(item.ShippingSpecialInstructions);
    });
    
    // validate signup form on keyup and submit
    $("#frm_addToCart").validate({
        invalidHandler: function(form, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = "";
                if (errors==1) {
                    message = 'You missed a field. It has been highlighted';
                } else {
                    message = 'You missed ' + errors + ' fields. They have been highlighted';
                }
                $("#a2c_errorDiv").html(message);
                $("#a2c_errorDiv").addClass('val_error');
                $("#a2c_errorDiv").show();
            } else {
                $("#a2c_errorDiv").hide();
            }
        },
        success:function() {
            $("#a2c_errorDiv").hide();    
        },
        errorPlacement: function(error, element) {},
        rules: {
            a2c_prodQuantity: {
                required: true,
                min: 1,
                number: true           
            },
            a2c_shipName: {
                required: function() {
                    return ($('input:radio[name=a2c_deliver]:checked').val() == "courier");
                }          
            },
            a2c_shipTel: {
                required: function() {
                    return ($('input:radio[name=a2c_deliver]:checked').val() == "courier");
                }          
            },
            a2c_shipAddress1: {
                required: function() {
                    return ($('input:radio[name=a2c_deliver]:checked').val() == "courier");
                }          
            },
            a2c_shipAddress2: {
                required: false          
            },
            a2c_shipAddress3: {
                required: false          
            },
            a2c_shipProvince: {
                required: function() {
                    return ($('input:radio[name=a2c_deliver]:checked').val() == "courier");
                },
                min: function() {
                    if ($('input:radio[name=a2c_deliver]:checked').val() == "courier") return 1;
                    else return 0;
                },
                number: true          
            },
            a2c_shipCity: {
                required: function() {
                    return ($('input:radio[name=a2c_deliver]:checked').val() == "courier");
                }          
            },
            a2c_shipPostalCode: {
                required: function() {
                    return ($('input:radio[name=a2c_deliver]:checked').val() == "courier");
                }          
            },
            a2c_shipDate: {
                required: function() {
                    return ($('input:radio[name=a2c_deliver]:checked').val() == "courier");
                },
                date: true          
            },
            a2c_shipInstructions: {
                required: false         
            },
            a2c_giftMessage: {
                required: function() {
                    if ($('#a2c_giftWrap:checked').val() == 1) {
                        return true;        
                    } else {
                        return false; 
                    }
                }          
            }
        }
    });
    
    function submitForm() {
        a2c_deliver = 0;
        if ($('input:radio[name=a2c_deliver]:checked').val()=="courier") {
            a2c_deliver = 1    
        }
        a2c_giftWrap = 0;
        if ($('#a2c_giftWrap:checked').val()==1) {
            a2c_giftWrap = 1    
        }
        $.ajax({
            type: 'POST',
            url: "/scripts/ajax_functions.php",
            data: {
                t: 'addToCart',
                pid: $('#a2c_prodID').text(),
                quan: $('#a2c_prodQuantity').text(),
                deliver: a2c_deliver,
                sname: $('#a2c_shipName').val(),
                stel: $('#a2c_shipTel').val(),
                saddr1: $('#a2c_shipAddress1').val(),
                saddr2: $('#a2c_shipAddress2').val(),
                saddr3: $('#a2c_shipAddress3').val(),
                sprov: $('#a2c_shipProvince').val(),
                scity: $('#a2c_shipCity').val(),
                spcode: $('#a2c_shipPostalCode').val(),
                sdate: $('#a2c_shipDate').val(),
                sinstr: $('#a2c_shipInstructions').val(),
                isgift: a2c_giftWrap,
                msg: $('#a2c_giftMessage').val()   
            },
            success: function(data) {
                if (!data.success) { 
                    alert('Failed to add item(s) to cart.\n' + data.errors.message);        
                } else {
                    showCart(); 
                    $('#addToCartDialog').dialog('close');
                }                                      
            },
            dataType: 'json'
        });      
    }
    
    function clearForm() {
        $('#a2c_prodID').text('');
        $('#a2c_prodPrice').text('');
        $('#a2c_prodQuantity').text('1');
        $('#a2c_shipName').val('');
        $('#a2c_shipTel').val('');
        $('#a2c_shipAddress1').val('');
        $('#a2c_shipAddress2').val('');
        $('#a2c_shipAddress3').val('');
        $('#a2c_shipProvince').val('');
        $('#a2c_shipCity').val('');
        $('#a2c_shipPostalCode').val('');
        $('#a2c_shipDate').val('');
        $('#a2c_shipInstructions').val('');
        $('#a2c_giftWrap').attr('checked', false); 
        
        $('input:radio[name=a2c_deliver]').filter('[value=email]').attr('checked', true);

        $('#a2c_giftMessage').val('');
        $('#a2c_deliverDetails').hide();
        $('#a2c_giftMessageDiv').hide();
        $("#a2c_errorDiv").hide();  
    }
    
    function incrementValue(amount){       
        $("#a2c_prodQuantity").text(Math.max(parseInt($("#a2c_prodQuantity").text()) + amount, 1));
        newPrice = Number($('#a2c_prodPrice').text()) * parseInt($("#a2c_prodQuantity").text());
        $('#a2c_prodTotalPrice').text("Price: R" + formatNumber(newPrice) + " incl. VAT");
    }

    $("#plus").click(function(){incrementValue(+1)});
    $("#minus").click(function(){incrementValue(-1)});
    $("#a2c_shipDate").datepicker({
        dateFormat: 'D, d M yy',
        minDate: '+3d',
        maxDate: '+6m'
    });
    $("#a2c_giftMessage").keyup(function(){
        if ($("#a2c_giftMessage").val().length > 300) {
            $("#a2c_giftMessage").val($("#a2c_giftMessage").val().substring(0,300));    
        }
        $("#a2c_giftMsgCharsLeft").text(300 - $("#a2c_giftMessage").val().length);                                                                    
    });
    
    $('input:radio[name=a2c_deliver]').change(function(){             
        if ($('input:radio[name=a2c_deliver]:checked').val() == "courier") {
            $('#a2c_deliverDetails').show('fast');                                                 
        } else {
            $('#a2c_deliverDetails').hide('fast');
            $("#a2c_errorDiv").hide(); 
        }
    });
    $('#a2c_giftWrap').click(function(){             
        if ($('#a2c_giftWrap:checked').val() == 1) {
            $('#a2c_giftMessageDiv').show('fast', function() {
                $('#addToCartDialog').scrollTo('#a2c_giftMessageDiv', 2000);
            });                                                 
        } else {
            $('#a2c_giftMessageDiv').hide('slow'); 
        }
    });                                           
   
});
