$(document).ready(function(){
	
	// move repeating code to paint_usercode()

	$.get("/index.php/yh/check_code/" + $('input#usercode').value, function(data) {
	
	if(data=='wrong')
		$('input#usercode').css('background-color', '#ffccaa');
	else
		$('input#usercode').css('background-color', 'white');
		
	});
	
	$("#usercode").change(function(event){
		
		$.get("/index.php/yh/check_code/" + event.target.value, function(data) {

		if(data=='wrong')
			$('input#usercode').css('background-color', '#ffccaa');
		else
			$('input#usercode').css('background-color', 'white');
			
		});
	});
	
	$("#usercode").keyup(function(event){
		
		$.get("/index.php/yh/check_code/" + event.target.value, function(data) {
		
		if(data=='wrong')
			$('input#usercode').css('background-color', '#ffccaa');
		else
			$('input#usercode').css('background-color', 'white');
			
		});
	});
	
	$("#rb_bango").click(function(event) {
		$("input#usercode").css('background-color', 'lightgray'); 
		$("input#usercode").attr('disabled', 'disabled');
	});
	
	$("#rb_usercode").click(function(event) {
		$('input#usercode').css('background-color', '#ffccaa');
		$("input#usercode").attr('disabled', '');
	});
	
	$("#usercountry").change(function(event){

		var country_name = $("select#usercountry option:selected").text();
		
		country_name = $.trim(country_name.replace(/[^a-zA-Z 0-9,\-']+/g,'')); // Removing all CRAP

		$.get("/index.php/yh/cities_of/" + escape(country_name), function(data) {
			
			$('#usercity').children().remove();

			var cities = data.split(',');

			var options = ""; 

			for (var i = 0; i < cities.length-1;++i)
				options = options + '<option value="'+cities[i]+'">'+cities[i]+'</option>';

			$('#usercity').append(options);
			
		});
	});
	
	$("#sms_auth_link").click(function(event){
		$("#sms_auth_form").toggle();
	});
	
	$('#msisdn_button').click(function() {
		var bValid = true;
		var msisdn = $("#runer_msisdn");
		bValid = bValid && checkLength(msisdn,8,8);
		if(!bValid)
			$("#msisdn_status").html("Mobil nr. should be without leading + or 47");
		else
		{
			bValid = bValid && checkRegexp(msisdn,/^([0-9])+$/);
			if(!bValid)
				$("#msisdn_status").html("Mobil nr. field only allow : 0-9");
		}
		if(bValid)
		{
			$.get("/index.php/yh/check_sms_auth/0/" + msisdn.val(), function(data){
				$("#msisdn_status").html(data);
			});
		}
	});

	$('#code_button').click(function() {
		var service_id = $('#service_id').attr('value');
		var bValid = true;
		var code = $("#runer_code");
		var msisdn = $("#runer_msisdn");
		bValid = bValid && checkRegexp(code,/^([0-9])+$/);
		if(!bValid)
			$("#code_status").html("Code field only allow : 0-9");
		if(bValid)
		{
			$.getJSON("/index.php/yh/check_sms_auth/" + code.val() + "/" + msisdn.val(), function(data){
				if(data.status == 'ok')
				{
					$("#code_status").css('color', '#00aa00'); 
				}
				$("#code_status").html(data.message);
			});
			
		}
	});
	
	$("#sms_auth_form").hide();
});

function validateUsercode(fld) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "<div class='error'>You didn't enter SMS code.</div>"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

function validateUsername(fld) {
    var error = "";
    var legalChars = /a-zA-Zа-яА-Я -/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "<div class='error'>You didn't enter a username.</div>";
    } else if (legalChars.test(fld.value)) {
        fld.style.background = 'Yellow'; 
        error = "<div class='error'>The username contains illegal characters.</div>";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "<div class='error'>You didn't enter an email address.</div>";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "<div class='error'>Please enter a valid email address.</div>";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "<div class='error'>The email address contains illegal characters.</div>";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validateFormOnSubmit(theForm) {

  var reason = "";

  reason += validateUsername(theForm.username);
  reason += validateEmail(theForm.usermail);
  
  if ($("#rb_usercode").attr('checked') == "true") {
  	reason += validateUsercode(theForm.usercode);
  }
      
  if (reason != "") {
	$('#validation').empty().append(reason)
    return false;
  }

  return true;
}

function checkLength(o,min,max) {

	if ( o.val().length > max || o.val().length < min ) {
		return false;
	} else {
		return true;
	}

}
 
function checkRegexp(o,regexp) {

	if ( !( regexp.test( o.val() ) ) ) {
		return false;
	} else {
		return true;
	}

}
