jQuery(function() {
  var $ = jQuery;

  // Namn
  function validatename(firstname, surname) {
    if (firstname.length+'' > 0 && surname.length+'' > 0) {
      nameerror('hide');
      return true;
    } else {
      nameerror('show');
      return false;
    }
  }
  
  // Adress
  function validateadress(street, number, city) {
    if (street.length+'' > 0 && number.length+'' > 0 && city.length+'' > 0) {
      adresserror('hide');
      return true;
    } else {
      adresserror('show');
      return false;
    }
  }
  
  // Lön
  function loncheck(lon) {
    if (lon.length > 0) {
      lonerror('hide');
      return true;
    } else {
      lonerror('show');
      return false;
    }
  }
  
  // E-post
  function emailpatterncheck(value) {
    if (value.match(/^([A-Za-z0-9]{1,}([-+_\.&'][A-Za-z0-9]{1,}){0,}){1,}@(([A-Za-z0-9]{1,}[-]{0,1})\.){1,}[A-Za-z]{2,6}$/i)) {
      emailerror('hide');
      return true;
    } else {
      emailerror('show');
      return false;
    }
  }
  
  // E-post
  function emailmatchcheck(email1, email2) {
    if (email1 == email2) {
      emailverifyerror('hide');
      return true;
    } else {
      emailverifyerror('show');
      return false;
    }
  }
  
  // Kontonummer
  function kontonrcheck(clearingnummer, kontonumber) {
    if (clearingnummer.match(/^\d{4,5}$/i) && kontonumber.match(/^\d{7,}$/i)) {
      return true;
    } else {
      return false;
    }
  }
  
  // Personnummer
  function validatepersonnummer(id_pnr_date, id_pnr_lastfour) {
		// merge date and last four
		var input_personnr = id_pnr_date + '-' + id_pnr_lastfour;
    //console.log(input_personnr);
		// Match NNNNNNNN-NNNN, if not returns false
		if (!input_personnr.match(/^(\d{4})(\d{2})(\d{2})\-(\d{4})$/)) { 
			return false;
		}
		
		// Create Date
		this.now = new Date(); 
		this.nowFullYear = this.now.getFullYear()+""; 
		this.year = RegExp.$1+"";
		this.month = RegExp.$2+"";
		this.day = RegExp.$3+"";
		this.controldigits = RegExp.$4+"";
		
		// if the submitted year is eq to or less than 2000 we assume the year is ok
		if (this.year*1 >= 1900 && this.year*1 <= 2000) { 
			this.fullYear = this.year*1;
		} else {
			return false;
		}
		
		var months = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		
		// Leap years
		if (this.fullYear%400 == 0 || this.fullYear%4 == 0 && this.fullYear%100 != 0) { 
			months[1] = 29;
		}
		
		// Check for correct months and days
		if (this.month*1<1 || this.month*1>12 || this.day*1<1 || this.day*1>months[this.month*1-1]) {
			return false;
		}
		
		// The complete personnummer is YYMMDDNNNN
		this.alldigits = this.year.substring(2,4)+this.month+this.day+this.controldigits;
		
		var nn = "";
		// Modulus 10, using 1:s and 2:s on the nine first digits
		for (var n = 0; n < this.alldigits.length; n++) {
			nn += ((((n+1)%2)+1) * this.alldigits.substring(n,n+1));
		}
		
		this.checksum = 0;
		
		// For each digit in personnummer add it to checksum plus the last digit
		for (var n = 0; n < nn.length; n++) {
			this.checksum += nn.substring(n,n+1)*1;
		}
		// function returns true if sum of above code is evenly divisible by 10
		this.valid = (this.checksum%10 == 0) ? true : false;
    //console.log(this.checksum);
    return this.valid;
		// Returns 1 or 0 depending on sex, not used.
		// this.sex = parseInt(this.controldigits.substring(2,3))%2;
  }
  
  // verification for correct email adress
  $('#input_2_7').bind('blur change', function() {
    if (emailpatterncheck($("#input_2_7").val())) {
      emailerror('hide');
      return true;
    } else {
      emailerror('show');
      return false;
    }
  });
  
  // Verification for matching emails
  $("#input_2_31").bind('blur change', function() {
    if (emailmatchcheck($("#input_2_31").val(), $("#input_2_7").val())) {
      emailverifyerror('hide');
      return true;
    } else {
      emailverifyerror('show');
      return false;
     }
  });
  
  // Verification for existing Månadslön
  $("#input_2_14").bind('blur change', function() {
    if (loncheck($("#input_2_14").val())) {
      lonerror('hide');
      return true;
    } else {
      lonerror('show');
      return false;
     }
  });
  
  // Verify adress
  $("#input_2_9_1, #input_2_9_5, #input_2_9_3").bind('blur change', function() {
    if (validateadress($('#input_2_9_1').val(), $('#input_2_9_5').val(), $('#input_2_9_3').val())) {
      return true;
    } else {
      return false;
    }
  });
  
  // Verify kontonummer
 $("#input_2_15, #input_2_16").bind('blur change', function() {
  if (kontonrcheck( $('#input_2_15').val(), $('#input_2_16').val())) {
    kontoerror('hide');
    return true;
  } else {
    kontoerror('show');
    return false;
  }
});

 // Verify name
$("#input_2_3_3_container input, #input_2_3_6_container input").bind('blur change', function() {
  if (validatename($('#input_2_3_3_container input').val(), $('#input_2_3_6_container input').val())) {
    nameerror('hide');
    return true;
  } else {
    nameerror('show');
    return false;
  }
});

  // Verify personnummer
 $("#input_2_6, #input_2_30").bind('change blur', function() {
  if (validatepersonnummer($('#input_2_6').val(), $('#input_2_30').val())) {
    pnrerror('hide');
    return true;
  } else {
    pnrerror('show');
    return false;
  }
});
  
  // Prevent paste operation into email confirmation field
  $("#input_2_31").bind('paste', function() {
    // Currently returns a silent error only but should indocate
    // a nice error because the user might be confused when default
    // operations are expected to work.
    return false;
  });
  
  // We need to bind the pnr century check before the validation, for some reason
  // non-IE browsers will not validate after jQuery modifies val() inside the method
  $('#input_2_6').bind('blur', function() {
  	// Test for centuries and append "19" first if it does not exist 
  	// but only if it is six digits long
  	var id_pnr_date = '#input_2_6';
  	if ($(id_pnr_date).val().substr(0,2) != 19 && $(id_pnr_date).val().length == 6) {
  		$(id_pnr_date).val("19" + $(id_pnr_date).val());
  	}
  });
  
  // Checkbox validation 
  $('#choice_21_1').bind('click', function() {
    if ($('#choice_21_1').is(':checked')) {
       $('.gform_footer input[type=submit]').removeAttr('disabled');
    } else {
       $('.gform_footer input[type=submit]').attr('disabled', 'disabled');
    }
    
  });
  
  
  // Bind the submit function to make sure everything validates
  // The function will stop the submission process if any check
  // returns false
  $('#gform_2').bind('submit', function() {
  

    // This will prevent the form from being submitted without good data
    var err = $.makeArray();
    // Full set
    if ($('#choice_17_0').is(':checked')) {

      // Debug
//      console.log('name: ' + validatename($('#input_2_3_3_container input').val(), $('#input_2_3_6_container input').val()));
//      console.log('pattern: ' + emailpatterncheck($("#input_2_7").val()));
//      console.log('lön: ' + loncheck($("#input_2_14").val()));
//      console.log('match: ' + emailmatchcheck($("#input_2_31").val(), $("#input_2_7").val()));
//      console.log('pnr: ' + validatepersonnummer($('#input_2_6').val(), $('#input_2_30').val()));
//      console.log('kontonr: ' + kontonrcheck($('#input_2_15').val(), $('#input_2_16').val()));
//      console.log('adress: ' + validateadress($('#input_2_9_1').val(), $('#input_2_9_5').val(), $('#input_2_9_3').val()));

      err[0] = validatename($('#input_2_3_3_container input').val(), $('#input_2_3_6_container input').val());
      err[1] = emailpatterncheck($("#input_2_7").val());
      err[2] = loncheck($("#input_2_14").val());
      err[3] = emailmatchcheck($("#input_2_31").val(), $("#input_2_7").val());
      err[4] = validatepersonnummer($('#input_2_6').val(), $('#input_2_30').val());
      err[5] = kontonrcheck($('#input_2_15').val(), $('#input_2_16').val());
      err[6] = validateadress($('#input_2_9_1').val(), $('#input_2_9_5').val(), $('#input_2_9_3').val());
    } else {
    // Returning customer
      // Debug
 //     console.log('pnr: ' + validatepersonnummer($('#input_2_6').val(), $('#input_2_30').val()));
      err[0] = validatepersonnummer($('#input_2_6').val(), $('#input_2_30').val());
    }
      // console.log(err);
      //alert(err);
      //alert($.inArray(false, err));
    // if there is any error
    if ($.inArray(false, err) >= 0) {
      // console.log(err);
      alert('Du har ett eller flera problem med din inmatning, klocka på OK och rätta till innan du kan slutföra din låneansökan.');
      return false;
    } else {
      return true;
    }
    
  });
  
  
  // Error messages
  function nameerror(action) {
      if (action == 'show') {
        // check if it has focus
        $("#field_2_3 .form-error").show();
      } else {
        $("#field_2_3 .form-error").hide();
      }
  }
  function pnrerror(action) {
      if (action == 'show') {
        // check if it has focus
        $("#field_2_6 .form-error").show();
      } else {
        $("#field_2_6 .form-error").hide();
      }
  }
  function emailerror(action) {
      if (action == 'show') {
        // check if it has focus
        $("#field_2_7 .form-error").show();
      } else {
        $("#field_2_7 .form-error").hide();
      }
  }
  function emailverifyerror(action) {
      if (action == 'show') {
        // check if it has focus
        $("#field_2_31 .form-error").show();
      } else {
        $("#field_2_31 .form-error").hide();
      }
  }
  function kontoerror(action) {
      if (action == 'show') {
        // check if it has focus
        $("#field_2_16 .form-error").show();
      } else {
        $("#field_2_16 .form-error").hide();
      }
  }
  function adresserror(action) {
      if (action == 'show') {
        // check if it has focus
        $("#field_2_9 .form-error").show();
      } else {
        $("#field_2_9 .form-error").hide();
      }
  }
  function lonerror(action) {
      if (action == 'show') {
        // check if it has focus
        $("#field_2_14 .form-error").show();
      } else {
        $("#field_2_14 .form-error").hide();
      }
  }
  
  
  
  
  function adderrormessages() {
    // Names
    $("#field_2_3").append('<span class="form-error">Du måste fylla i ditt namn</span>');
    // Personnummer
    $("#field_2_6").append('<span class="form-error">Födelsedatum ogiltigt, ska ha formatet 19770131-1234</span>');
    // email
    $("#field_2_7").append('<span class="form-error">Ej giltig e-postadress</span>');
    // email verify
    $("#field_2_31").append('<span class="form-error">E-postadresserna stämmer ej överens</span>');
    // kontonummer verify
    $("#field_2_16").append('<span class="form-error">Clearingnummer ska vara 4 eller 5 siffror, kontonummer 7 eller fler siffror</span>');
    // adress verify
    $("#field_2_9").append('<span class="form-error">Fyll i din adress</span>');
    // Lön verify
    $("#field_2_14").append('<span class="form-error">Fyll i din lön</span>');
  
  }
  
  // Run it!
  if (!$('#choice_21_1').attr('checked')) {
    $('.gform_footer input[type=submit]').attr('disabled', 'disabled');
  }
  adderrormessages();
});

