/* Validation */
function validationErrorPlacement(error, element) {
    // Locate the last input element in the row
    while(element.next(":input, a, label.unit, label.error, img").length > 0) element = element.next();

    // Add error
    element.after(error);
}

// Add extra validation functions
$(document).ready(function(){
    // Phone
    jQuery.validator.addMethod("phone", function(value, el) {
        return this.optional(el) || /^([0-9]([. -]?[0-9]){9}|[+][0-9]([. -]?[0-9]){7,})$/.test(value);
    }, "Please enter a valid number (e.g. 646-123-4567 or +16461234567)");

    // Alphanumeric
    jQuery.validator.addMethod("alphanumeric", function(value, el) {
        return this.optional(el) || /^[A-za-z0-9]+$/.test(value);
    }, "Please enter letters and numbers only");

    // Unique screen name
    jQuery.validator.addMethod("uniqueScreenName", function(value, el) {
        var result = false;
        $.ajax({
            type: "GET",
            url: "resources/validation/screenName",
            cache: false,
            data: {screenName: value},
            success: function() {result = true},
            async: false
        });
        return result;
    }, "Screen name already taken, please pick another");

    // Unique e-mail
    jQuery.validator.addMethod("uniqueEmail", function(value, el, params) {
        var result = false;
        var data = {email: value};
        if(!isNaN(params[0]) && (params[0] != null)) data.personId = params[0];
        if(params[1] === true) data.ignorePrincipal = true;
        else data.ignorePrincipal = false;
        $.ajax({
            type: "GET",
            url: "resources/validation/email",
            cache: false,
            data: data,
            success: function() {result = true},
            async: false
        });
        return result;
    }, "This e-mail address belongs to another account");

    // Credit card number (may be blocked out)
    jQuery.validator.addMethod("blockedCreditCard", function(value, el) {
        if(value[4] == '*') return true;
        return jQuery.validator.methods.creditcard.call(this, value, el);
    }, "Please enter a valid credit card number.");

    // Device barcode
    jQuery.validator.addMethod("deviceBarcode", function(value, el) {
        return this.optional(el) || /^0010000[01][0-9][0-9][0-9][0-9]$/.test(value);
    }, "Invalid device barcode");

    // Unassigned device
    jQuery.validator.addMethod("unassignedDevice", function(value, el) {
        if(this.optional(el)) return true;

        var result = false;
        $.ajax({
            type: "GET",
            url: "resources/validation/unassignedDevice",
            cache: false,
            data: {identifier: value},
            success: function() {result = true},
            async: false
        });
        return result;
    }, "Device already assigned");

});

