﻿var lastId = 0;

jQuery.validator.addMethod("isSiretValid", function() {
    var re = /^\d{14}$/;
    var string = $('#NumeroSiretId').val().toString();
    if (re.test(string) == true) {
        var chars = new Array();
        for (var i = 13; i >= 0; i--) {
            chars.push(string.charAt(i));
        }
        var total = 0;
        for (var j = 0; j < 14; j++) {
            var t = parseInt(chars[j]);
            t = ((1 + j) == 0 || (1 + j) % 2 == 0) ? t * 2 : t;
            if (t > 9) {
                t = parseInt(t.toString().charAt(0)) + parseInt(t.toString().charAt(1));
            }
            total += parseInt(t);
        }
        return (total % 10 == 0) ? true : false;
    }
    return false;
});

jQuery.validator.addMethod("isLoginValid", function() {   
    var log = $('#LoginDef').val().toString();
    return (($('#testLogin')[0]).value == 'true') ? true : false;

});


jQuery.validator.addMethod("isCodeValid", function() {
    var re = /^[V|P|E]{1}\d+$/;
    var string = $('#CodeClientInternet').val().toString();
    if (re.test(string) == true) {
        var val = ($('#testCodeInternet')[0]).value;
        return (($('#testCodeInternet')[0]).value == 'true') ? true : false;
    }
});

$('#CodeClientInternet').blur(function() {
    var string = $('#CodeClientInternet').val();
    validateCodeInternet(string);
});
$('#TypeCompteId').change(function() {
    var string = $('#CodeClientInternet').val();
    validateCodeInternet(string);
    
});

$('#LoginDef').blur(
            function() {
                var log = $('#LoginDef').val();
                validateLogin(log);
            }
         );

$('#Zipcode').keypress(
            function(e) {
                //if the letter is not digit then display error and don't type anything
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    return false;
                }
            }
         );

$('#Zipcode').blur(function() {
    if (($('.countryId :selected').text().toLowerCase() == "france" || $('.countryId :selected').val() == 84 || $('.countryId :selected').val() == 91
            || $('.countryId :selected').val() == 135 || $('.countryId :selected').val() == 180) && $('#Zipcode').val().length == 5 && lastId != $('#Zipcode').val()) {
        lastId = $('#Zipcode').val();
        $.ajax({
            url: sitePath + "ajax/ContactGetVilles/" + lastId,
            dataType: "json",
            cache: true,
            success: function(obj) {
                $('.ville').children().remove();
                $.each(obj, function() {
                    $('.ville').append('<option value="' + this.Localite + '">' + this.Localite + '</option>');
                });
                if ($('.ville').children().length > 0)
                    $('.ville').removeAttr('disabled');
            },
            error: function() { alert('Erreur'); }
        });
    }
    else if (($('.countryId :selected').text().toLowerCase() == "france" || $('.countryId :selected').val() == 84 || $('.countryId :selected').val() == 91
            || $('.countryId :selected').val() == 135 || $('.countryId :selected').val() == 180) && lastId != $('#Zipcode').val()) {
        $('.ville').children().remove();
        $('.ville').attr('disabled', 'disabled');
        lastId = $('#Zipcode').val();
    }
});

$("form#compteForm").validate({
    rules: {
        Mail: { required: true, email: true },
        NumeroSiretId: { required: true, minlength: 14, isSiretValid: true },
        CodeClientInternet: { required: true, minlength: 5, isCodeValid: true },
        LoginDef: { required: true, minlength: 5, isLoginValid:true},
        Password: { required:true, minlength: 4},
        ConfirmPassword: { required: true, equalTo: "#Password" },
        CityId: { required: true },
        City: { required: true },
        Adress: { required: true },
        Zipcode: { required: true }
    },
    messages: {
        CodeClientInternet: ' ',
        NumeroSiretId: ' ',
        RaisonSocialeId: ' ',
        Lastname: ' ',
        Firstname: ' ',
        Adress: ' ',
        Zipcode: ' ',
        CityId: ' ',
        PhoneNumber: ' ',
        LoginDef: ' ',
        Mail: ' ',
        Password: ' ',
        ConfirmPassword: ' '
    },
    ignore: ".ignore",
    success: function(label) { label.addClass("valid").fadeOut(5000); }
})

$("form#compteForm").submit(function() {
    $(this).valid();
});

function validateLogin(log) {
    var tmp = $.ajax({
        url: sitePath + 'ajax/IsLoginDisponible/' + log,
        dataType: "json",
        cache: false,
        success: function(obj1) {
            ($('#testLogin')[0]).value = obj1.isValid;
            $('#LoginDef').valid();
            return (obj1.isValid);
        },
        error: function() { return false; }
    });
    return tmp;
}

function validateCodeInternet(string) {
    $.ajax({
        url: sitePath + 'ajax/IsInternetCodeValid/' + string + '/' + $('.kind :selected').val(),
        dataType: "json",
        cache: false,
        success: function(obj) {

            if (obj.isValid == true) {
                ($('#testCodeInternet')[0]).value = 'true';
                if (obj.isUnassigned == false) {
                    $('#CodeClientInternet').attr('disabled', 'disabled');
                    ($('#NumeroSiretId'))[0].value = obj.numeroSiretId;
                    $('#NumeroSiretId').attr('disabled', 'disabled');
                    ($('#RaisonSocialeId'))[0].value = obj.raisonSociale;
                    $('#RaisonSocialeId').attr('disabled', 'disabled');
                    $('#TypeCompteId').attr('disabled', 'disabled');

                    for (var k = 0; k < $('#TailleEntrepriseId').children().lenght; k++) {
                        var item = ($('#TailleEntrepriseId').children())[k];
                        if (item.value == obj.tailleEntrepriseId) {
                            item.selected = true;
                        } else {
                            item.selected = false;
                        }
                    }
                    $('#TailleEntrepriseId').attr('disabled', 'disabled');
                    $('.taille').attr('disabled', 'disabled');
                }
            }
            else {
                ($('#testCodeInternet')[0]).value = 'false';
            }
            $('#CodeClientInternet').valid();
            return obj.isValid;
        },
        error: function() { return false; }
    });
}


$('.countryId').change(function() {
    if ($('.countryId :selected').text().toLowerCase() == "france" || $('.countryId :selected').val() == 84 || $('.countryId :selected').val() == 91
            || $('.countryId :selected').val() == 135 || $('.countryId :selected').val() == 180) {
        $('input[name=City]').attr("disabled", "disabled");
        $('#ville_txt').hide();
        $('#ville_select').show();
        if ($('#ville_select select').children().length > 0)
            $('#ville_select select').removeAttr("disabled");
    }
    else {
        $('#ville_select select').attr("disabled", "disabled");
        $('#ville_select').hide();
        $('#ville_txt').show();
        $('input[name=City]').removeAttr("disabled");
    }
    $('#code_postal_id').keyup();
});

$('.countryId').change();
