// Array.contains(element) -- extend Array to get foo.contains('bar'), note that 5 != '5'
Array.prototype.contains = function (element) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) {
      return true;
    }
  }
  return false;
};

// init stuff
$secondForm = false;
$basis_selects   = ['aflossingsvorm1b', 'aflossingsvorm2b', 'rentevastperiode1b', 'rentevastperiode2b'];
$comfort_selects = ['aflossingsvorm1c', 'aflossingsvorm2c', 'rentevastperiode1c', 'rentevastperiode2c'];

// getElem(id) -- saves typing
function getElem(x) {return document.getElementById(x);}

// getRadioValue(name) -- can't use getElem on radiobuttons, so we check the array by name
function getRadioValue(name) {
  radios = document.getElementsByName(name);
  for (i=0; i<(radios.length); i++) {
    if (radios[i].checked) {
      // alert(radios[i].value);
      return radios[i].value;
    }
  }
  return '';
}



// checkdate(d, m, j) -- a *sane* date checker without regex (whodathunkitpossible)
function checkdate(d, m, j) {
  var d = parseInt(d, 10); // document.getElementById('d').value);
  var m = parseInt(m, 10); // document.getElementById('m').value);
  var j = parseInt(j, 10); // document.getElementById('j').value);
  if (isNaN(d) || isNaN(m) || isNaN(j)) {
    // alert('invalid 1');
    return false;
  }
  datum = new Date(j, m-1, d);
  // alert(datum.toLocaleDateString());
  // sanity check
  if ((datum.getDate() != d) || ((datum.getMonth()+1) != m) || (datum.getFullYear() != j)) {
  	// alert(d+' '+datum.getDate());
  	// alert(m+' '+(datum.getMonth()+1));
  	// alert(j+' '+datum.getFullYear());
    return false;
  }
  return true;
}


// fixme(fld) -- corrects invalid field values, called onblur()
function fixme(fld) {
  // commas to dots, multiple dots to a single one, anything not dot or digit to nirvana
  val = fld.value;
  val = parseInt(val, 10);
  // alert(val);
  if ((fld.name == 'bday1') || (fld.name == 'bday2')) {
    fld.value = ((val >= 1) && (val <= 31)) ? Math.round(val) : 1;
  }else if ((fld.name == 'bmonth1') || (fld.name == 'bmonth2')) {
    fld.value = ((val >= 1) && (val <= 12)) ? Math.round(val) : 1;
  }else if ((fld.name == 'byear1') || (fld.name == 'byear2')) {
    now = new Date(); // getYear is broken in FF (non-Y2K), who knew?
    fld.value = ((val >= 1900) && (val <= (now.getFullYear()-18))) ? Math.round(val) : 1900;
  }else if (fld.name == 'inkomen1') {
  	if (isNaN(val)) val = 1000;
    fld.value = val > 5000000 ? 5000000 : (val < 1000 ? 1000 : Math.round(val));
  }else if (fld.name == 'inkomen2') {
  	if (isNaN(val)) val = 0;
    fld.value = val > 5000000 ? 5000000 : Math.round(val);
  }
}

//________________ checks form values before submitting
// checksubmit() /
function checksubmit() {
  var i, $blanks = '';
  var $fields = 'bday1 bmonth1 byear1 samenlevingsvorm1 inkomen1'.split(' ');
  var $radiofields = ['hypotheek', 'geslacht1'];
  var $names = {'bday1': 'Geboortedatum dag', 'bmonth1':'Geboortedatum maand', 'byear1':'Geboortedatum jaar',
        'samenlevingsvorm1': 'Samenlevingsvorm', 'inkomen1':'Inkomen aanvrager', 'hypotheek':'Gewenste hypotheek', 'geslacht1':'Geslacht aanvrager', 'b1': 'Geboortedatum'};
  var $missing = [];
  for (i=0; i<$radiofields.length; i++) {
    if (! getRadioValue($radiofields[i])) $missing.push($radiofields[i]);
  }
  for (i=0; i<$fields.length; i++) {
    var $val = getElem($fields[i]).value;
    if ($val == '' || $val == '0') $missing.push($fields[i]);
  }
  var bday1   = getElem('bday1').value;
  var bmonth1 = getElem('bmonth1').value;
  var byear1  = getElem('byear1').value;
  if ((! $missing.contains('bday1')) && (! $missing.contains('bmonth1')) && (! $missing.contains('byear1'))) {
    if (! checkdate(bday1, bmonth1, byear1)) {
    	$missing.push('b1');
    }
  }
  if ($missing.length > 0) {
    for (i=0; i<$missing.length; i++) $blanks += $names[$missing[i]]+'\n';
    alert('De volgende velden zijn nog niet goed ingevuld:\n' + $blanks);
    return false;
  }
  return true;
}

//_________________ -- checks the second form values before submitting, is called in checkSecondForm
// checksubmit2() /
function checksubmit2() {
  var i, $blanks = '', $missing = [];
  var errorMsg = '';
  var $fields = 'bedrag_te_financieren bedrag_executiewaarde bedrag_leningdeel1 looptijd1'.split(' ');
  var $names = {
  	'bedrag_te_financieren':'Totaal hypotheekbedrag',
  	'bedrag_executiewaarde':'Executiewaarde',
  	'bedrag_leningdeel1':'Lening(1) bedrag',
  	'bedrag_niet_aftrekbaar1':'Lening(1) Niet aftrekbaar deel',
  	'aflossingsvorm1b':'Lening(1) aflossingsvorm',
  	'aflossingsvorm2b':'Lening(2) aflossingsvorm',
  	'rentevastperiode1b':'Lening(1) rentevastperiode',
  	'rentevastperiode2b':'Lening(2) rentevastperiode',
  	'aflossingsvorm1c':'Lening(1) aflossingsvorm',
  	'aflossingsvorm2c':'Lening(2) aflossingsvorm',
  	'rentevastperiode1c':'Lening(1) rentevastperiode',
  	'rentevastperiode2c':'Lening(2) rentevastperiode',
  	'looptijd1':'Lening(1) looptijd',
  	'bedrag_boeterente':'Boeterente',
  	'bedrag_renteverlies_bouw':'Renteverlies tijdens bouw',
  	'lenpluslenfails':' - Leningdeel 1 en Leningdeel 2 zijn samen niet het hypotheekbedrag.',
  	'looptijd2verplichtbijl2': 'Lening(2) looptijd'
  	};
  $hyp = parseInt(getRadioValue('hypotheek'), 10);
  if ($hyp == 1) {
  	// $fields = $fields.concat($comfort_selects);
  	$fields.push('aflossingsvorm1c');
  	$fields.push('rentevastperiode1c');
  }else{
  	$fields.push('aflossingsvorm1b');
  	$fields.push('rentevastperiode1b');
  }
  // obligatory fields
  for (i=0; i<$fields.length; i++) {
    var $val = getElem($fields[i]).value;
    if ($val == '' || $val == 0 || isNaN($val)) $missing.push($fields[i]);
  }
  // optional values, but if supplied, should be numeric
  var $numerics = ['bedrag_renteverlies_bouw', 'bedrag_boeterente'];
  for (i=0; i<$numerics.length; i++) {
    var $val = getElem($numerics[i]).value;
    if ($val != '') if (isNaN(parseInt($val, 10))) $missing.push($numerics[i]);
  }
  // check for some logic errors
  var l1 = parseInt(getElem('bedrag_leningdeel1').value, 10);
  if (isNaN(l1)) l1 = 0;
  var l2 = parseInt(getElem('bedrag_leningdeel2').value, 10);
  if (isNaN(l2)) l2 = 0;
  if ((l1 + l2) != parseInt(getElem('bedrag_te_financieren').value, 10)) {
    $missing.push('lenpluslenfails');
  }
  // if leningdeel 2, check extra fields
  if (l2 != 0) {
  	l2fields = ($hyp == 1) ? ['aflossingsvorm2c', 'rentevastperiode2c'] : ['aflossingsvorm2b', 'rentevastperiode2b'];
    for (i=0; i<l2fields.length; i++) {
      var $val = getElem(l2fields[i]).value;
      if ($val == '') $missing.push(l2fields[i]);
    }
  	var lt2 = parseInt(getElem('looptijd2').value, 10);
  	if (isNaN(lt2)) {
  		$missing.push('looptijd2verplichtbijl2');
  	}
  }
  
  if ($missing.length > 0) {
    for (i=0; i<$missing.length; i++) $blanks += '- ' + $names[$missing[i]]+'\n';
    errorMsg = $blanks;
  }
  if (errorMsg != '') {
    alert('De volgende velden zijn nog niet goed ingevuld:\n' + errorMsg);
    return false;
  }
  return true;
}

//__________________________________ -- shows / hides the right select menus, based on the chosen mortgage type from form 1
// stap2ShowHideSelects(hypotheek) /
function stap2ShowHideSelects() {
	// alert(typeof $hypotheek + ': ' + $hypotheek);
  if (parseInt($hypotheek, 10) == 1) {
    // alert('Comfort');
  	for (i=0; i<$basis_selects.length; i++) {
      $('#'+$basis_selects[i]).hide();
      $('#'+$comfort_selects[i]).show();
    }
  }else{
    // alert('Basis');
  	for (i=0; i<$basis_selects.length; i++) {
      $('#'+$basis_selects[i]).show();
      $('#'+$comfort_selects[i]).hide();
    }
  }
}

$(document).ready(function(){
	
  $('#calculate1').click(function(){
    if (checksubmit()) {
      $hypotheek          = getRadioValue('hypotheek');
      $geslacht1          = getRadioValue('geslacht1');
      $geslacht2          = getRadioValue('geslacht2');
      $bday1              = getElem('bday1').value;
      $bmonth1            = getElem('bmonth1').value;
      $byear1             = getElem('byear1').value;
      $bday2              = getElem('bday2').value;
      $bmonth2            = getElem('bmonth2').value;
      $byear2             = getElem('byear2').value;
      $samenlevingsvorm1  = getElem('samenlevingsvorm1').value;
      $inkomen1           = getElem('inkomen1').value;
      $inkomen2           = getElem('inkomen2').value;
      // if (! ($income && $duration && $percent)) return false;
      $('#arena1').hide();
      // is this the first time they submitted the first form?
      if ($secondForm == false) { // so the code in this 'if' only runs *once*.
        $('.contenthide').hide();
        $('#loaderDiv').show();
        $('#arena2').load(
          "assets/php/maandlasten1.php",
          {hypotheek: $hypotheek, geslacht1: $geslacht1, geslacht2: $geslacht2, bday1: $bday1, bmonth1: $bmonth1, byear1: $byear1, bday2: $bday2,   bmonth2: $bmonth2, byear2: $byear2, samenlevingsvorm1: $samenlevingsvorm1, inkomen1: $inkomen1, inkomen2: $inkomen2},
          function() {
          	// $('#arena2').show();
          	$secondForm = true;
            $('#loaderDiv').hide();
            $('.contenthide').show();
            // show/hide the right select menus
            stap2ShowHideSelects($hypotheek);
          	// bind some code to the buttons in the new form, back and forward:
          	$('#backtostart').click(function() {
              $('#arena2').hide();
              $('#arena1').show();
            });
          	$('#calculate2').click( function() { 
              checkSecondForm();
            });
        	}
        );
      }else{
      	// there is already a hidden second form in arena2, show it
      	$('#arena1').hide();
        $('#arena2').show();
        // show/hide the right select menus
        stap2ShowHideSelects();
        // somehow check if type of mortgage (basic vs comfort) was changed, reload select options if so.
      }
    }
  });
  
  function checkSecondForm() {
    var i, post_data = {};
    if (checksubmit2()) {
      // get form inputs from the first step in the hidden div "arena1"
      var fields = 'bday1 bmonth1 byear1 samenlevingsvorm1 inkomen1 bday2 bmonth2 byear2 inkomen2'.split(' ');
      $hypotheek = parseInt(getRadioValue('hypotheek'), 10);
      post_data.hypotheek = $hypotheek;
      post_data.geslacht1 = getRadioValue('geslacht1');
      post_data.geslacht2 = getRadioValue('geslacht2'); 
      for (i=0; i<fields.length; i++) {
        eval('post_data.' + fields[i] + ' = getElem(\'' + fields[i] + '\').value;');
      }
      // get current form's vars by id
      fields = 'bedrag_te_financieren bedrag_executiewaarde bedrag_renteverlies_bouw bedrag_boeterente bedrag_leningdeel1 bedrag_niet_aftrekbaar1 niet_aftrekbaar_na1 looptijd1 bedrag_verzekering1 bedrag_leningdeel2 bedrag_niet_aftrekbaar2 niet_aftrekbaar_na2 looptijd2 bedrag_verzekering2'.split(' ');
      if ($hypotheek == 1) {
      	fields = fields.concat($comfort_selects);
      }else{
      	fields = fields.concat($basis_selects);
      }
      for (i=0; i<fields.length; i++) {
        eval('post_data.' + fields[i] + ' = getElem(\'' + fields[i] + '\').value;');
      }
      // get radiobutton values by name
      fields = 'ind_aank_oversluiting ind_nieuw_bestaand ind_taxatiekosten ind_nhg'.split(' ');
      for (i=0; i<fields.length; i++) {
        eval('post_data.' + fields[i] + ' = getRadioValue(\'' + fields[i] + '\');');
      }
      $('#arena2').hide();
      $('#loaderDiv').show();
      $('.contenthide').hide();
      $('#arena3').load(
        'assets/php/maandlasten2.php',
        post_data,
        function() {
          $('#loaderDiv').hide();
          $('.contenthide').show();
          $('#arena3').show(); // just in case it was hidden before
        	$('#backtosecond').click(function() {
            $('#arena3').hide();
            $('#arena2').show();
          });
        }
      );
    }
  }
  
});
