function createUser() {

	var error;
	if ( ( $("#username").val().length < 5 ) && ( $("#username").val().length  >= 25 )) {
		error = "Username has to be between 5 and 25 characters.";
	}

	else if ( ( $("#password").val().length < 5 ) || ( $("#password").val().length  >= 25 )) {
		error = "Password has to be between 5 and 25 characters.";
	}

	else if ( $("#password").val() != $("#confirm_password").val() ) {
		error = "Passwords do not match.";
	}

	if ( error ) {
		alert ( error );
		return false;
	}

	 $.ajax({
        type    : "POST",
        url     : "/json_create_user",
        data    : $("#createUserForm").serialize(),
        dataType: "json",
        success : function(data, textStatus) {
            if(!data.success) {
                alert(data.error_msg);
             }
             else {
                  $("#createUserDialog").dialog('close');
                  $("#createAccountText").hide();
                  $("#userCreatedDialog").dialog('open');
             }
        },
        error: function() {
            alert('User could not be created.');
        }

    }); 

}

function retrieveShipping() {
     $.ajax({
        type    : "POST",
        url     : "/home/get_addresses",
        data    : {},
        dataType: "html",
        success : function(data, textStatus) {
            $("#shipping_list").html( data );
        },
        error: function() {
            alert('Could not retrieve any shipping addresses.');
        }

    });     
}

function deleteAddress(addressID) {

         $.ajax({
        type    : "POST",
        url     : "/home/json_delete_address",
        data    : {'address_id': addressID},
        dataType: "json",
        success : function(data, textStatus) {
            
        },
        error: function() {
            alert('Could not delete the shipping address.');
        }

    });   

    // Display the shipping again
    retrieveShipping();
}

function retrievePasswd() {
            $.ajax({
        type    : "POST",
        url     : "/home/json_send_email",
        data    : {'email': $("#lost_email").val() },
        dataType: "json",
        success : function(data, textStatus) {
            $("#lostPasswordDialog").dialog('close'); 
            $("#passwordSent").show();
        },  
        error: function() {
            alert('Could not retrieve password.');
        }   

    });   
}


function saveShipping() {
	if ( !$("#shipping_name").val() ) {
		alert('Please specify the label for shipping (ie. Home, Office, etc)');
		return false;
	}

	 $.ajax({
        type    : "POST",
        url     : "/json_save_address",
        data    : $("#addShippingAddress").serialize(),
        dataType: "json",
        success : function(data, textStatus) {
            if(!data.success) {
                alert(data.error_msg);
             }
             else {
             	alert('Shipping Address has been saved.');
             }

             $("#shipping_name").val('');
             retrieveShipping();

        },
        error: function() {
            alert('Address could not be saved. Please try again.');
        }

    }); 	
}

function showState() {
	
	if ( $("#country").val() != 'United States' ) {
		$("#stateListRow").hide();
		$("#provinceListRow").show();
	}
	else {
		$("#stateListRow").show();
		$("#provinceListRow").hide();
	}
}

function updateCart() {
    
    $("#pre_payment_cart").html('');
    $("#loader_cart").show();

	$.ajax({
		type : "POST",
        url     : "/update_cart_options",
        data    : $("#prePaymentForm").serialize(),
        dataType: "html",
        success : function(data, textStatus) {
               $("#pre_payment_cart").html( data );
               $("#loader_cart").hide();
               $("#shippingSelect").bind('change', function() { $("#pre_payment_cart").html(''); updateCart(); return false; });
               $("#insure").bind('click', function() { $("#pre_payment_cart").html(''); updateCart(); r });
               $("#us_media_mail").bind('click', function() { $("#pre_payment_cart").html(''); updateCart();  });
        },
        error: function() {
            alert('Cart could not be changed. Please try again.');
        }
    }); 	
}

function changeAccountDetails() {
    $.ajax({
        type : "POST",
        url     : "/home/json_change_account",
        data    : $("#updateAccount").serialize(),
        dataType: "json",
        success : function(data, textStatus) {
             if(!data.success) {
                alert(data.error_msg);
             }
             else {
                 $("#accountForm").html('<p>Account details have been changed.</p>');
             }
        },
        error: function() {
            alert('Password cannot be changed. Please try again.');
        }
    });     
}


function purchaseCart() {
    // Send emails and then let them go to pay
   // Ajax and on success:
    if ( $("#payment_type").val() == 1 ) {

        $("#paymentChoiceDialog").dialog('close');
        $("#paypalPaymentDialog").dialog('open');
    }

    if ( $("#payment_type").val() == 2 ) {
        // Credit card
        //show modal box to confirm ('Order processed please continue to make payment')
    
        // Clear out cart and change status
        $("#paymentChoiceDialog").dialog('close');
        $("#verisignPaymentDialog").dialog('open');
    }
}

function addWishList(itemID) {
    
        $.ajax({
        type : "POST",
        url     : "/json_add_wishlist/" + itemID,
        data    : { },
        dataType: "json",
        success : function(data, textStatus) {    
            if ( data.success == 1 ) {
                $("#addWishListDialog").dialog('open');      
            }
            else {
                $("#addWishListDialogFail").dialog('open');  
            }
        },
        error: function() {
            alert('Could not be saved.');
        }
    });     
}
function saveCart() {
 
    if ( !$("#shippingSelect").val() || !$("#billingSelect").val() ) {
        return false;
    }
   

        $.ajax({
        type : "POST",
        url     : "/confirm_order",
        data    : { shipping_address : $("#shippingSelect").val(),
                    billing_address : $("#billingSelect").val(),
                    insure: $("#insure").is(':checked'),
                    us_media_mail: $("#us_media_mail").is(':checked') },
        dataType: "html",
        success : function(data, textStatus) {
              $("#checkout_page").html(data);
              
        },
        error: function() {
            alert('Cart could not be confirmed. Please try again.');
        }
    });     

}

function showOrder( orderNumber ) {
    
    $.ajax({
        type : "POST",
        url     : "/json_get_order/" + orderNumber,
        data    : { },
        dataType: "html",
        success : function(data, textStatus) {    
                $("#showOrderDialoag").dialog('open'); 
                $("#orderDetal").html( data );     
        },
        error: function() {
            alert('Order could not be retrieved.');
        }
    });     
}

$(document).ready( function() {
    $("#addShippingAddress").submit(function() {  saveShipping(); return false  });
    //$("#prePaymentForm").submit(function() {  updateCart(); return false  });
    $("#country").bind('change',function() { showState(); return false });
    $("#updateAccount").submit(function() { changeAccountDetails(); return false; });
    $("#selectShippingCart").bind('click',function() { updateCart(); return false; });


    
});

