$(function() {
    // username validation
    $('#username').after('<span id="uname_result" class="ajaxy"></span>');
    $('#username').blur(function () {
        $(this).val($(this).val().toLowerCase().replace(/[^a-zA-Z0-9]/g,''));
        checkUname($(this).val());
    });
    // email address
    $('#email').after('<span id="email_result" class="ajaxy"></span>');
    $('#email').blur(function () {
        checkEmail($(this).val());
    });
    // password strength detector
    $("#pass1").after('<span id="pass_strength" class="ajaxy"></span>');
	$("#pass1").keyup(function () {
		checkPass($(this).val());
	});            
    // location bidness
    // $('#zip').after('<input type="hidden" name="locale" id="locale">');
    // $('#zip').after('<input type="hidden" name="lat" id="lat">');
    // $('#zip').after('<input type="hidden" name="lon" id="lon">');
    // $('#zip').after('<span id="geocode_result"></span>');
    // $('#zip').blur(function () {
    //     findAddress();
    // });            
    // $('#country').blur(function () {
    //     findAddress();
    // });            
    $('#country').change(function(){
        switch($(this).val()) {
            case 'US':
            case 'GB':
            case 'CA':
                $('#ziprow').show();
                break;
            default:
                $('#ziprow').hide();
                $('#zip').val('');
                break;
        }
        findAddress();
    });
    // birthday bidness
    $('#bday').datepicker({yearRange: '-80:0'});
});

// check to see if username is valid and available
function checkUname(myUsername) {
    var message = '';
    var color = '#c00';
    // check for valid & available
    $("#uname_result").text('Checking...').css('color','#000').fadeIn("slow");
    // check the username exists or not from ajax
    $.post("/signup/check/", { username:myUsername }, function(result) {
        // the username is available
        switch(result) {
            case '1':
                message = 'Available';
                color = '#0c0';
                break;
            case '0':
                message = 'Not Available';
                color = '#c00';
                break;
            case '-1':
            default:
                message = 'Not Valid';
                color = '#c00';
                break;
        }
        $("#uname_result").fadeTo(200,0.1, function() { 
            $(this).html(message).css('color', color).fadeTo(500,1);	
        });
    });
}

// verify that the email addy matches the right pattern
function checkEmail (email) {
    if (!email.match(/^([\w+-]+(?:\.[\w+-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i))
        $("#email_result").html('Not Valid').css('color', '#c00').fadeIn(500);	
    else
        $("#email_result").fadeOut(200);
}

// calculate and update the password strength
function checkPass(password) {
    message = 'Too Short';
    color = '#c00';
    score = 0;
    //password > 4
    if (password.length > 0 && password == $("#username").val())
        message = 'Same As Username! Bad!';
    else if (password.length >= 4) {
        // password length
        score += password.length * 4;
        // password has 2 numbers
        if (password.match(/(.*[0-9].*[0-9].*[0-9].*)/))  score += 5;
        // password has 2 symbols
        if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 5;
        // password is mixed case
        if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  score += 10;
        // password has number and chars
        if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  score += 15;
        // password has number and symbol
        if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/))  score += 15;
        // password has char and symbol
        if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/))  score += 15;
        // password is just a nubers or chars
        if (password.match(/^\w+$/) || password.match(/^\d+$/) )  score -= 10;
        // if (score < 0) { message = 'Bad'; color = '#c00'; }
        if (score > 10) { message = 'Weak'; color = '#c0'; }
        if (score > 25) { message = 'Okay'; color = '#cc0'; }
        if (score > 50) { message = 'Strong'; color = '#0c0'; }
        if (score >= 85) { message = 'Excellent!'; color = '#0c0'; }
    }
    $('#pass_strength').html(message).css('color',color);
}

// // use the google geocoder to find coordinates
// function findAddress() {
//     $('#geocode_result').fadeOut(200);
//     $('#lon').val('');
//     $('#lat').val('');
//     $('#locale').val('');
//     myZip = $("#zip").val();
//     myCountry = $("#country option:selected").text();
//     myString = myZip+', '+myCountry;
//     // alert(myString);
//     var geocoder = new GClientGeocoder();
//     geocoder.getLocations(myString, function(response) {
//         place = response.Placemark[0];
//         locale = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
//         lon = place.Point.coordinates[1];
//         lat = place.Point.coordinates[0];
//         $('#lon').val(lon);
//         $('#lat').val(lat);
//         $('#locale').val(locale);
//         // $('#geocode_result').html(locale+', '+myCountry).fadeIn(500);
//     });        
//     // $('#geocode_result').html('Required').fadeIn(500);
// }
