Event.observe(window, 'load', initforms);

var eventfields = new Array();

//algemene functies

/**
 * Controleert of een string voorkomt in een array
 */
function in_array(stringToSearch, arrayToSearch) {
  for (s = 0; s < arrayToSearch.length; s++) {
    thisEntry = arrayToSearch[s].toString();
    if (thisEntry == stringToSearch) {
      return true;
    }
  }
  return false;
}

/**
 * Initialise all forms with class "siteform"
 */
function initforms()
{
	buttonStyles();
	resizeParent();
	var container;
  for (var n = 0; n < document.forms.length; n++) {
    if ($(document.forms[n]).hasClassName('siteform')) {
      initform(document.forms[n]);
      container = document.forms[n];
    }
  }
  prefill_address();
  if (container) {
    focus_first_field(container);
  }
}

/**
 * checks if the form is displayed again as a result of validation errors or a "new" form
 * @return boolean
 */
function isValidatedForm(form)
{
  return $(form).getElementsBySelector('.form-errors').length > 0;
}

/**
 * gets all the form elements within the given container
 * @param mixed container reference or id for the container element
 * @return array
 */
function getFormElements(container)
{
  return $(container).getElementsBySelector('input, textarea, select');
}

/**
 * resize parent frame if it exists and has de DYNIFS module loaded
 */
function resizeParent()
{
  if (window.parent && window.parent.DYNIFS) {
  	window.parent.DYNIFS.resize('formulier');
  }
}

/**
 * hide a container and all disables all the form elemens contained within
 * @param mixed container reference or id for the container element
 */
function hideFormPart(container)
{
  $(container).style.display = 'none';
  var e = getFormElements(container);
  for (var i = 0; i < e.length; i++) {
    e[i].disabled = true;
    //remove error help text
    form_help_error_off(e[i]);
  }
  resizeParent();
}

/**
 * display a container and enables all form elements contained within
 * @param mixed container refernece or id for he container element
 */
function showFormPart(container)
{
  var e = getFormElements(container);
  for (var i = 0; i < e.length; i++) {
    e[i].disabled = false;
    if ($(e[i]).hasClassName('error')) {
      form_help_error_on(e[i]);
    }
  }
  for (var i = 0; i < e.length; i++) {
    if (in_array(e[i].id, eventfields)) {
      form_change(e[i], true);
    }
  }
  $(container).style.display = 'block';
  resizeParent();
}

/**
 * Initialise the given container to add dependencies of fields
 *
 * @param mixed container the id of the container or reference to tge container element
 */
function initform(container)
{
  var fields = getFormElements(container);
  var elements = $(container).getElementsBySelector('div, fieldset');
  var classes = new Array();
  var parts = new Array();
  for (var i = 0; i < elements.length; i++) {
    classes = elements[i].className.split(' ');
    for (var j = 0; j < classes.length; j++) {
      parts = classes[j].split('-');
      if ((parts.length > 1) && (parts[1] == 'container') && (fields[0].form.elements[parts[0]])) {
      	//initialiseer afhankelijke velden op niet zichtbaar
      	if (elements[i].id.indexOf(classes[j] + '-custom') != 0) {
      	  hideFormPart(elements[i]);
      	}
      	//voeg events toe
        add_form_events($(container), parts[0]);
      }
    }
  }

  fields = getFormElements(container);
  for (k=0; k < fields.length; k++) {
    if (!fields[k].hasClassName('hasEvents')) {
      fields[k].addClassName('hasEvents');
      Event.observe(fields[k], 'focus', function() {
    		form_help_on(this);
    	});
    	Event.observe(fields[k], 'change', function() {
    	  call_user_func(this.id, this);
    	  ajax_field_update(this);
    	});
    	Event.observe(fields[k], 'blur', function() {
    		form_help_off(this);
    		track_field(this);
    		validate_field(this);
    	});
      if (fields[k].hasClassName('numeric')) {
        Event.observe(fields[k], 'keypress', numbersonly); 
      }
      else if (fields[k].hasClassName('alphanumeric')) {
        Event.observe(fields[k], 'keypress', charactersonly); 
      }
    }
    if ($('zipcode')) {
      Event.observe($('zipcode'), 'blur', prefill_address);
    }
    if ($('zipcode2')) {
      Event.observe($('zipcode2'), 'blur', prefill_address);
    }
    if ($('postcode')) {
      Event.observe($('postcode'), 'blur', prefill_address);
    }
    if ($('housenr')) {
      Event.observe($('housenr'), 'blur', prefill_address);
    }
    if ($('housenr2')) {
      Event.observe($('housenr2'), 'blur', prefill_address);
    }
    if ($('huisnr')) {
      Event.observe($('huisnr'), 'blur', prefill_address);
    }
    if ($('housenumberaddition')) {
      Event.observe($('housenumberaddition'), 'blur', prefill_address);
    }
    if ($('housenrextra')) {
      Event.observe($('housenrextra'), 'blur', prefill_address);
    }
  }
}

function validate_container(container)
{
  var status = -2;
  var elements = getFormElements(container);
  for (var i =0; i < elements.length; i++) {
    if (elements[i].hasClassName('error')) {
      //if status is not set or valid, set to invalid
      if ((status == -2) || (status == 1)) {
        status = -1;
      }
    }
    else if (elements[i].hasClassName('required')) {
      //required element, but not in error state (maybe not visited yet)
      if (elements[i].hasClassName('valid')) {
        if (status == -2) {
          status = 1;
        }
      }
      else {
        //not valid, not in error, but still required...
        //set it to 0
        status = 0;
      }
    }
    else {
      //no error. not required, set to 0 if no other status has been set yet
      if (status == -2) {
        status = elements[i].hasClassName('valid') ? 1 : 0;
      }
      if (elements[i].name.indexOf('[day]') != -1) {
        status = (elements[i].value == '') ? 0 : status;
      }
      if (elements[i].name.indexOf('[month]') != -1) {
        status = (elements[i].value == '') ? 0 : status;
      }
      if (elements[i].name.indexOf('[year]') != -1) {
        status = (elements[i].value == '') ? 0 : status;
      }
    }
  }
  if (status == -2) {
    //hmm noone set a status... assume all went okay
    status = 1;
  }
  
  //apply container status
  if (status == 1) {
    container.removeClassName('form-row-error');
    container.addClassName('form-row-valid');
  }
  if (status == 0) {
    container.removeClassName('form-row-error');
    container.removeClassName('form-row-valid');
  }
  if (status == -1) {
    container.removeClassName('form-row-valid');
    container.addClassName('form-row-error');
  }
}

function validate_update_field(field, status)
{
  var element = $(field);
  var elements = new Array();
  var container = $(field).up('.form-row');
  if (!container) {
    container = $(field).up('.form-text');
  }
  //find related elements
  if (element.id != element.name) {
    var all_elements = element.form.getElements();
    for (var n = 0; n < all_elements.length; n++) {
      if ((all_elements[n].name == element.name) && (all_elements[n].id != element.id)) {
        elements.length++;
        elements[elements.length-1] = all_elements[n];
      }
    }
  }
  
  //set the status for related elements
  for (var n = 0; n < elements.length; n++) {
    switch (status) {
      case 1:
        elements[n].removeClassName('error');
        elements[n].addClassName('valid');
      break;
    }
  }
  
  //set the status for the original element
  switch (status) {
    case 1:
      element.removeClassName('error');
      element.addClassName('valid');
      form_help_error_off(element);
    break;

    case 0:
      element.removeClassName('error');
      element.removeClassName('valid');
      form_help_error_off(element);
    break;

    case -1:
      element.removeClassName('valid');
      element.addClassName('error');
      form_help_error_on(element);
    break;
  }
  
  if (container) {
    validate_container(container);
  }
}

function validate_field(field)
{
  var required = $(field).hasClassName('required');
  var value = $(field).getValue();
  if ((value != '') && (value != null)) {
    //ajax validation request
    if (typeof ajax_validate_url != 'undefined') {
      new Ajax.Request(ajax_validate_url, {
        parameters: {
          fieldname: field.name,
          fieldid: field.id,
          fieldclass: field.className,
          value: value
        },
        onComplete: function(http, json) {
          if (json['status']) {
            $(json['fieldid']).value = json['value'];
            validate_update_field(json['fieldid'], 1);
          }
          else {
            validate_update_field(json['fieldid'], -1);
          }
        }
      });
    }
    else {
      validate_update_field(field, 1);
    }
  }
  else {
    if (required) {
      validate_update_field(field, -1);
    }
    else {
      validate_update_field(field, 0);
    }
  }
}

function getChar(event)
{
  var key;
  if (window.event) {
    //internet explorer
    key = event.keyCode;
  }
  else if (event) {
    //normal browsers
    key = event.which;
  } else {
    //unknown browsers
    return false;
  }  
  return String.fromCharCode(key);
}

function numbersonly(event)
{
  var keychar = getChar(event);
  if (keychar.match(/[a-z]/i)) {
    event.stop();
  }
}

function charactersonly(event)
{
  var keychar = getChar(event);
  if (keychar.match(/[0-9]/i)) {
    event.stop();
  }
}



/**
 * add the onchange event handler to the element(s) with the given id, radiobuttons have multiple items
 * with similar ids (id_value)
 * @param prototypeelement container an element reference extended with prototype (using the $() function)
 * @param string element_id the id of the element to add the events to
 */
function add_form_events(container, element_id)
{
  //record the field
  if (!in_array(element_id, eventfields)) {
    eventfields.length++;
    eventfields[eventfields.length - 1] = element_id;
  }

  //singular input
  var element = $(element_id);
  //stupid IE bug! $('bkr') matched id bkr_yes....
  if (element && (element.id != element_id)) {
    element = false;
  }
  if (element) {
    Event.observe(element, 'change', function() {
      form_change(this);
    });
    form_change(element, true);
  }
  else {
    var elements = container.select('input[type="radio"][name="' + element_id + '"]');
    for (var i = 0; i < elements.length; i++) {
      Event.observe(elements[i], 'click', function() {
        form_change(this);
      });
      form_change(elements[i], true);
    }
  }

  //combined date input
  //year
  element = $(element_id + '_year');
  if (element) {
    Event.observe(element, 'change', function() {
      form_date_change(this);
    });
    form_date_change(element, true);
  }
  //month
  element = $(element_id + '_month');
  if (element) {
    Event.observe(element, 'change', function() {
      form_date_change(this);
    });
    form_date_change(element, true);
  }
  //day
  element = $(element_id + '_day');
  if (element) {
    Event.observe(element, 'change', function() {
      form_date_change(this);
    });
    form_date_change(element, true);
  }
}

function get_date_value(id)
{
  var d = '';
  if ($(id + '_day')
  && ($(id + '_day').selectedIndex != -1)
  && ($(id + '_day').options[$(id + '_day').selectedIndex].value != '')) {
    d += $(id + '_day').options[$(id + '_day').selectedIndex].value + '-';
  }
  else {
    d += '01-';
  }
  if ($(id + '_month')
  && ($(id + '_month').selectedIndex != -1)
  && ($(id + '_month').options[$(id + '_month').selectedIndex].value != '')) {
    d += $(id + '_month').options[$(id + '_month').selectedIndex].value + '-';
  }
  else {
    d += '00-';
  }
  if ($(id + '_year')
  && ($(id + '_year').selectedIndex != -1)
  && ($(id + '_year').options[$(id + '_year').selectedIndex].value != '')) {
    d += $(id + '_year').options[$(id + '_year').selectedIndex].value;
  }
  else {
    d += '0000';
  }
  return d;
}

function ajax_field_update(element)
{
  if (typeof ajax_update_url != 'undefined') {
    switch (element.tagName) {
      case 'SELECT' :
        if (element.id.indexOf('_') != -1) {
          var id = element.id.split('_');
          var value = get_date_value(id[0]);
        }
        else {
          var value = element.options[element.selectedIndex].value;
        }
      break;
      default:
        var value = element.value;
      break;
    }
    new Ajax.Request(ajax_update_url, {
      parameters: {
        field: element.name,
        value: value
      }
    });
  }
}

/**
 * execute a custom event handler if it exists
 * @param string the id of the field the custom handler is called for
 * @param element parameter reference to the element the function is called for or called on
 */
function call_user_func(functionname, parameter)
{
  if (functionname.indexOf('-') > 0) {
    functionname = functionname.split('-')[0];
  }
    
  if (eval('typeof(field_' + functionname + ')') == 'function')
  {
    eval( 'field_' + functionname + '(parameter);');
  }

  if (functionname.indexOf('_') > 0) {
    var name = functionname.split('_')[0];
    call_user_func(name, parameter);
  }
  else {
    var name = functionname;
  }

  var match = name.match(/^[a-z]*/)[0];
  if (match != name) {
    call_user_func(match, parameter);
  }

}

/**
 * de onchange handler for singular fields
 *
 * @param element element Het element waarvan de onchange is getriggered
 * @param boolean notevent true voor direct aanroepen ipv uit event; wordt o.a. gebruikt tijdens initialisatie
 */
function form_change(element, notevent)
{
  if (typeof notevent == "undefined") {
    notevent = false;
  }
  //if (!notevent) ajax_field_update(element);
  call_user_func(element.id, element);
  switch (element.tagName) {
    case 'SELECT' :
      var value = element.options[element.selectedIndex].value;
    break;
    case 'INPUT' :
      var value = element.value;
      if ((element.type == 'radio') && !((element.checked) || (!notevent))) {
        return;
      }
    break;
  }
  var id = element.id;
  if (element.type == 'radio') {
    id = element.id.split('_')[0];
  }
  var elements = $(element.form).getElementsBySelector('.' + id + '-container');
  for (var i = 0; i < elements.length; i++) {
    if (elements[i].id == id + '-container-' + value) {
      showFormPart(elements[i]);
    }
    else {
      if (elements[i].id.indexOf(id + '-container-custom') != 0) {
        hideFormPart(elements[i]);
      }
    }
  }
}

/**
 * the onchange handler for date fields made of three pulldowns (day, month, year)
 *
 * @param element element Het element waarvan de onchange is getriggered
 * @param boolean notevent true voor direct aanroepen ipv uit event; wordt o.a. gebruikt tijdens initialisatie
*/
function form_date_change(element, notevent)
{
  if (typeof notevent == "undefined") {
    notevent = false;
  }
  //if (!notevent) ajax_field_update(element);
  call_user_func(element.id, element);
}


/**
 * form_help
 * toggles element's help div on
 */
function form_help_on(element)
{
	var name = element.id
	if (!$(name+'-help')) {
	  name = element.id.match(/^[a-z]*/);
	}
	if ($(name+'-help')) {
		if ($(name+'-help').innerHTML != '') {
			$(name+'-help').removeClassName('hidden');
		}
		resizeParent();
	}
}

/**
 * form_help
 * toggles element's help div off
 */
function form_help_off(element)
{
	var name = element.id
	if (!$(name+'-help')) {
	  name = element.id.match(/^[a-z]*/);
	}
	if ($(name+'-help')) {
	  if ($(name+'-help').hasClassName('form-help')) {
		  $(name+'-help').addClassName('hidden');
		  resizeParent();
	  }
	}
}

/**
 * form_help
 * toggles element's help div on
 */
function form_help_error_on(element)
{
	var name = element.id
	if (!$(name+'-help')) {
	  name = element.id.match(/^[a-z]*/);
	}
	if ($(name+'-help')) {
		if ($(name+'-help').innerHTML != '') {
		  $(name+'-help').addClassName('form-error');
		}
	}
}

function field_exists(name, number)
{
  if ($(name + number.toString()) && ($(name + number.toString()).disabled == false)) return true;
  if ($(name + number.toString() + '_year') && ($(name + number.toString() + '_year').disabled == false)) return true;
  if ($(name + number.toString() + '_month') && ($(name + number.toString() + '_month').disabled == false)) return true;
  if ($(name + number.toString() + '_day') && ($(name + number.toString() + '_day').disabled == false)) return true;
  return false
}

function field_has_error(name, number)
{
  var e = false
  if ($(name + number.toString())) {
    e = (e || $(name + number.toString()).hasClassName('error'));
  }
  if ($(name + number.toString() + '_year')) {
    e = (e || $(name + number.toString() + '_year').hasClassName('error'));
  }
  if ($(name + number.toString() + 'month')) {
    e = (e || $(name + number.toString() + '_month').hasClassName('error'));
  }
  if ($(name + number.toString() + 'day')) {
    e = (e || $(name + number.toString() + '_day').hasClassName('error'));
  }
  return e;
}

/**
 * form_help
 * toggles element's help div off
 */
function form_help_error_off(element)
{
	var name = element.id
	if (!$(name+'-help')) {
	  name = element.id.match(/^[a-z]*/);
	}
	if ($(name+'-help')) {
	  //check all numbered fields with the same name
	  //income1, income2, income3 etc.
	  //if none are in error state, the help-text can be displayed as normal help text
	  var error = false;
	  var n = 1;
	  while (field_exists(name, n)) {
	    error = error || field_has_error(name, n);
	    n++;
	  }
	  if (!error) {
		  $(name+'-help').removeClassName('form-error');
	  }
	}
}

/**
 * set the value on a pulldown element, if it exists in the option list
 *
 * @param element element the element to set the value on
 * @param string value the value to set
 */
function select_set_value(element, value)
{
  for (var i  = 0; i < element.options.length; i++) {
    if (element.options[i].value == value) {
      element.selectedIndex = i;
      if (typeof(element.onchange) == 'function') {
        element.onchange(element, true);
      }
    }
  }
}

/**
 * Gets address from webservice
 */
function prefill_address()
{
  var zipcode = '';
  var housenr = '';
  var housenumberaddition = '';
  
  if ($('zipcode') && (!$('zipcode').disabled)) {
    zipcode = $('zipcode').value;
  }
  if ($('zipcode2') && (!$('zipcode2').disabled)) {
    zipcode = $('zipcode2').value;
  }
  if ($('postcode') && (!$('postcode').disabled)) {
    zipcode = $('postcode').value;
  }
  if ($('housenr') && (!$('housenr').disabled)) {
    housenr = $('housenr').value;
  }
  if ($('housenr2') && (!$('housenr2').disabled)) {
    housenr = $('housenr2').value;
  }
  if ($('huisnr') && (!$('huisnr').disabled)) {
    housenr = $('huisnr').value;
  }
  if ($('housenumberaddition') && (!$('housenumberaddition').disabled)) {
    housenumberaddition = $('housenumberaddition').value;
  }
  if ($('housenrextra') && (!$('housenrextra').disabled)) {
    housenumberaddition = $('housenrextra').value;
  }

	if ((zipcode.match(/^[1-9][\d]{3}\s?(?!(sa|sd|ss|SA|SD|SS))([a-zA-Z]{2})?$/i)) && (housenr.match(/^\d+$/))) {
		new Ajax.Request('/ajaxpostcode/postcode', {
			asynchronous:true,
			evalScripts:false,
			parameters: {
			  zipcode: zipcode,
			  housenr: housenr,
			  housenumberaddition: housenumberaddition
			},
			onComplete: function(response, json) {
			  if (json['valid']) {
  				for (var i in json) {
  					if ($(i)) {
  					  $(i).value = json[i];
  					  validate_update_field($(i), 1);
  					}
  				}
			  }
			  else {
			    for (var i in json) {
  					if ($(i)) {
  					  
  					}
  				}
			  }
			}
		});
	}
	else {
		return false;
	}
}

function focus_first_field(container)
{
  var fields = getFormElements(container);
  var f = false;
  var n = 10000000;
  for (var k=0; k < fields.length; k++) {
    if (!fields[k].disabled && (fields[k].type != 'hidden') && (fields[k].tabIndex < n) && (!$(fields[k]).hasClassName('skipfocus'))) {
      f = fields[k];
      n = f.tabIndex;
    }
  }
  if (f) {
    if ((f.type == 'text') || (f.tagName == 'SELECT')) {
      f.focus();
    }
  }
}


//fieldspecific functions

/**
 * adjust the emplyment field based on the date in the workingsince date pulldowns
 */
function field_workingsince(element)
{
  if (!isValidatedForm(element.form)) {
    var name = element.id.split('_')[0];
    var n = name.match(/[0-9]*$/)[0];
    var e_month = $(name + '_month');
    var e_year = $(name + '_year');
    var month = e_month.options[e_month.selectedIndex].value;
    var year = e_year.options[e_year.selectedIndex].value;
    if ((year > 0) && (month > 0)) {
      var ws = new Date(year, month, 1);
      var thedate = Math.floor(ws.getTime()/1000);
      var now = Math.round(new Date().getTime()/1000);
      var delta = 1 * 365 * 24 * 60 * 60;
      if ((now - thedate) > delta) {
        //langer dan 2 jaar geleden
        select_set_value($('employment' + n), '1');
      }
      else {
        //korter dan 2 jaar geleden
        select_set_value($('employment' + n), '6');
      }
    }
  }
}

/**
 * adjust the partneremployment field based on the date in the partnerworkingsince date pulldowns
 */
function field_partnerworkingsince(element)
{
  if (!isValidatedForm(element.form)) {
    var name = element.id.split('_')[0];
    var n = name.match(/[0-9]*$/)[0];
    var e_month = $(name + '_month');
    var e_year = $(name + '_year');
    var month = e_month.options[e_month.selectedIndex].value;
    var year = e_year.options[e_year.selectedIndex].value;
    if ((year > 0) && (month > 0)) {
      var ws = new Date(year, month, 1);
      var thedate = Math.floor(ws.getTime()/1000);
      var now = Math.round(new Date().getTime()/1000);
      var delta = 1 * 365 * 24 * 60 * 60;
      if ((now - thedate) > delta) {
        //langer dan 2 jaar geleden
        select_set_value($('partneremployment' + n), '1');
      }
      else {
        //korter dan 2 jaar geleden
        select_set_value($('partneremployment' + n), '6');
      }
    }
  }
}

/**
 * hide or display the extra children fields based on the amount of children selected
 */
function field_children(element)
{
  if (element.options[element.selectedIndex].value != '0' && $('family').options[$('family').selectedIndex].value == 'O') {
    showFormPart('children-container-custom');
  }
  else {
    hideFormPart('children-container-custom');
  }
}

/**
 * display family options based on the value of the family pulldown
 */
function field_family(element)
{
  if (element.options[element.selectedIndex].value != 'O') {
    //container for partner information
    showFormPart('family-container-custom');
    //container for partner income
    showFormPart('family-container-customincome');
  }
  else {
    hideFormPart('family-container-custom');
    hideFormPart('family-container-customincome');
  }
  field_children($('children'));
}

/**
 * load an extra incomesource form part and insert it into the form
 * or disable the following blocks if "geen" is selected
 */
function field_incomesource(element)
{
  var e = $(element.id + '-ajax');
  if (e) {
    if (element.options[element.selectedIndex].value != 'geen') {
      e.id = element.id + '-container-customajax';
      new Ajax.Updater(e, '/leningaanvraag/inkomen', {
        parameters: {
          n: element.id.match(/[0-9]*$/)[0]
        },
        onComplete: function() {
          initform(e);
          form_change(element, true);
          e.show();
        }
      });
    }
  }
  else {
    e = $(element.id + '-container-custom');
    if (e) {
      if (element.options[element.selectedIndex].value == 'geen') {
        hideFormPart(element.id + '-container-custom');
      }
      else {
        showFormPart(element.id + '-container-custom');
      }
    }
  }
}

function field_partnerincomesource1(element)
{
	if (element.options[element.selectedIndex].value == 'geen') {
		showFormPart('generaltaxreduction-row');
	}
	else {
		hideFormPart('generaltaxreduction-row');
	}
}

/**
 * load an extra partnerincomesource form part and insert it into the form
 */
function field_partnerincomesource(element)
{
  var e = $(element.id + '-ajax');
  if (e) {
    if (element.options[element.selectedIndex].value != 'geen') {
      e.id = element.id + '-container-customajax';
      new Ajax.Updater(e, '/leningaanvraag/inkomen', {
        parameters: {
          n: element.id.match(/[0-9]*$/)[0],
          partner: 1
        },
        onComplete: function() {
          initform(e);
          form_change(element, true);
          e.show();
          //showFormPart(e);
        }
      });
    }
  }
  field_partnerincomesource1($('partnerincomesource1'));
}

/**
 * load an extra loans form part and insert it into the form
 */
function field_currentloans(element)
{
  var e = $(element.id + '-ajax');
  if (e) {
    if (element.options[element.selectedIndex].value != 'nee') {
      e.id = element.id + '-container-customajax';
      new Ajax.Updater(e, '/leningaanvraag/lening', {
        parameters: {
          n: element.id.match(/[0-9]*$/)[0]
        },
        onComplete: function() {
          initform(e);
          form_change(element, true);
          e.show();
          //showFormPart(e);
        }
      });
    }
  }
}


/**
 * field event handler for loan validation
 * since it is on a hidden field, it only gets called at the initialisation of the document
 * it installs custom event handlers on the fields and buttons in the amount checks
 */
function field_messagetotal(element)
{
  element.form.onsubmit = checkloans;
  $('message-desiredamount-raise').onclick = raisedesiredamount;
  $('message-desiredamount-explain').onclick = explaindesiredamount;
  $('message-desiredamount-change').onclick = changedesiredamount;
  //execute checkloans to hide or show the desired amount message fields based on the form values
  checkloans();
}

/**
 * retrieve a field as integer value
 * return integer
 */
function getintvalue(fieldname)
{
  var value = $(fieldname).value.replace(/\./, '');
  if (value.match(/^\d*$/) == value) {
    return parseInt(value);
  }
  return false;
}

/**
 * validate the desired amount against the current loans
 * adjust the form to allow the user to raise the amount or give an explanation
 * @return boolean
 */
function checkloans()
{
  var desiredamount = getintvalue('desiredamount');
  var n = 1;
  var loantotal = 0;
  var loan = 0;
  while ($('remaindebt' + n)) {
    if (($('currentloans' + n).selectedIndex == 0) && ($('redeem' + n + '_1').checked)) {
      loan = getintvalue('remaindebt' + n);
      if (loan) {
        loantotal += loan;
      }
    }
    n++;
  }
  if (desiredamount) {
    $('message-desiredamount').innerHTML = desiredamount.toString();
  }
  else {
    $('message-desiredamount').innerHTML = '';
  }
  $('message-loanstotal').innerHTML = loantotal.toString();

  $('messagetotal-container-customraise').hide();
  $('messagetotal-container-customexplain').hide();
  if ((desiredamount > 0) && (desiredamount <= loantotal)) {
    $('messagetotal-container-custom').show();
    //if the amounts are not right, but an explaination is given, allow the form to be submitted
    if (($('messagetotal').value == 'explain') && ($('loansexplanation').value != '')) {
      $('messagetotal-container-customraise').hide();
      showFormPart('messagetotal-container-customexplain');
      return true;
    }
    else {
      $('messagetotal-container-customraise').hide();
      $('messagetotal-container-customexplain').hide();
      return false;
    }
  }
  else {
    $('messagetotal-container-custom').hide();
    return true;
  }
}

/**
 * adjust the form when the user presses the "raise" button in the amount check
 */
function raisedesiredamount()
{
  //copy the current desired amount
  $('newdesiredamount').value = $('desiredamount').value;
  //save the choise in the form
  $('messagetotal').value = 'raise';
  //display form parts
  showFormPart('messagetotal-container-customraise');
  hideFormPart('messagetotal-container-customexplain');
}

/**
 * adjust the form when the user presses the "explain" button in the amount check
 */
function explaindesiredamount()
{
  //save the choise in the form
  $('messagetotal').value = 'explain';
  //display the form parts
  showFormPart('messagetotal-container-customexplain');
  hideFormPart('messagetotal-container-customraise');
}

/**
 * change the amount and re-validate the desired amounts with the current loans
 */
function changedesiredamount()
{
  $('desiredamount').value = $('newdesiredamount').value;
  if (checkloans()) {
    $('desiredamount').form.submit();
  }
}

/**
 * shows the additional form fields required by the subsubject field
 */
function contact_additional()
{
	if ($('subject-action')){
		if ($('advisor').value == '') {
			if ($('subject').options[$('subject').selectedIndex].value == 'mortgage') {
				hideFormPart('subject-action');
			}
			else if ($('subject').options[$('subject').selectedIndex].value == 'loan') {
			  if ($('advisor').selectedIndex != '-1' && ($('advisor').options[$('advisor').selectedIndex].value == '') && ($('advisor').options[$('advisor').selectedIndex].text != '')) {
				  showFormPart('subject-action');
			  }
			  else {
			    hideFormPart('subject-action');
			  }
			}
			else {
			  showFormPart('subject-action');
			}
	
			if ($('phonerequired')) {
			  if ($('subsubject').options[$('subsubject').selectedIndex].value == 5) {
			    $('phonerequired').show();
			  }
			  else {
			    $('phonerequired').hide();
			  }
			}
	    
			//show company name when 'intermediar worden' is selected.
			if ($('subsubject').options[$('subsubject').selectedIndex].value == 14) {
			  $('companynamecnt').show();
			} 
			else {
			  $('companynamecnt').hide();
			}
			 
			new Ajax.Request('/contactopnemen/additional', {
					asynchronous:true,
					evalScripts:false,
					parameters: {
					  subject: $('subject').value,
					  subsubject: $('subsubject').value
					},
					onComplete: function(response, json) {
						hideFormPart('fr-date');
						hideFormPart('fr-time');
						hideFormPart('fr-amountincrease');
						hideFormPart('fr-amountwithdrawal');
						hideFormPart('fr-contractnr');
	
						var fieldcount = 0;
						for (var i in json) {
							if ($('fr-' + json[i])) {
							  showFormPart('fr-' + json[i]);
							  fieldcount++;
							}
						}
						if (fieldcount > 0) {
							showFormPart('additional-information');
						}
						else {
							hideFormPart('additional-information');
						}
					}
				});
		}
		else {
			hideFormPart('subject-action');
			hideFormPart('additional-information');
		}
	}
  office_image();
}

function field_subsubject()
{
	contact_additional();
}

//Formatting amounts
function number_format(number) {
  number = Math.round(number).toString();
  if (number.length > 6) {
    number = number.slice(0, -6) + '.' + number.slice(number.length-6);
  }
  if (number.length > 3) {
    number = number.slice(0, -3) + '.' + number.slice(number.length-3);
  }
  return number;
}

function roundSliderValue(value, type) {
	var factor = 50;
	if (type != 'undefined' && type == 'maandlasten+hypotheekcalculator') {
		factor = 5000;
	}
	if (type != 'undefined' && ((type == 'maandlasten+leningcalculator') || (type == 'maandlasten'))) {
		factor = 500;
		if (value >= 20000) {
		  factor = 1000;
		}
	}
	return value = value - (value % factor);
}

/**
 * office_image
 * toggles office image div on or off
 */
function office_image()
{
	if ($('office')) {
		if (  ($('advisor').selectedIndex == -1)
		   || ($('advisor').options[$('advisor').selectedIndex].value != '')
		   || ($('advisor').options[$('advisor').selectedIndex].text == '') ) {
			$('office').style.display = 'none';
		}
		else {
			$('office').style.display = 'block';
		}
	}
}

function update_advisor()
{
  new Ajax.Updater('advisor-container',	'/ajaxpostcode/advisor', {
    asynchronous:true,
    evalScripts:false,
    parameters:'zipcode=' + $('zipcode').value + '&office=true&type=' + $('subject').value,
    onComplete: function() {
      initform('advisor-container');
      field_advisor();
    }
  });
}

function update_referer(form)
{
	new Ajax.Updater(
		'referersub-container',
		'/afabfieldoption/suboptions',
		{
			asynchronous:true,
			evalScripts:false,
			parameters:'field=referer&form='+form+'&option='+$('referer').value
		}
	);
}

function updatePartnerCarrousel(next)
{
		setTimeout(function () {
				new Ajax.Updater(
					'banken-caroussel',
					'/partner/updateblock',
					{
						asynchronous:true,
						evalScripts:false,
						parameters:'partner='+next,
						onComplete: function(response, json) {
							updatePartnerCarrousel(json['next']);
						}
					}
				);
			}, 8000);
}

function track_field(element)
{
	if (element) {
		var par = $(element);
		var pc = 0;

		do {
			if (par) {
				par = par.up();
			}
			pc++;
		}
		while (par && par.tagName != 'FIELDSET' && par.tagName != 'FORM' && par.tagName != 'BODY' && pc < 5);

		var legend = '';

		if (par && par.tagName == 'FIELDSET') {
			var legs = par.getElementsBySelector('legend');

			if (legs.length > 0) {
				legend = legs[0].innerHTML;
			}
		}

		var form = ''

		for (var n = 0; n < document.forms.length; n++) {
	    if ($(document.forms[n]).hasClassName('siteform')) {
	      form = document.forms[n].name;
	    }
	  }
	  if (undefined !== window.pageTracker) {
	    pageTracker._trackPageview('/' + form + '/' + legend + '/' + element.name);
	  }
	}
}

function field_advisor()
{
  contact_additional();
}

function hide_adviseur()
{
  hideFormPart('subject-container-customadvisor');
  showFormPart('subject-container-customaddress');
}

function show_adviseur()
{
  showFormPart('subject-container-customadvisor');
  hideFormPart('subject-container-customaddress');
}

function field_subject()
{
  contact_additional();
  if ($('subject').selectedIndex != -1) {
    if ($('subject').options[$('subject').selectedIndex].value != 'mortgage') {
      hide_adviseur();
    }
    else {
      show_adviseur();
    }
  }
}

/**
 * load an extra opleiding form part and insert it into the form
 * or disable the following blocks if "nee" is selected
 */
function field_opleiding(element)
{
  var e = $(element.id + '-ajax');
  if (e) {
    if (element.options[element.selectedIndex].value != 'nee') {
      e.id = element.id + '-container-customajax';
      new Ajax.Updater(e, '/jobopenings/opleiding', {
        parameters: {
          n: element.id.match(/[0-9]*$/)[0]
        },
        onComplete: function() {
          initform(e);
          form_change(element, true);
          e.show();
        }
      });
    }
  }
  else {
    e = $(element.id + '-container-custom');
    if (e) {
      if (element.options[element.selectedIndex].value == 'nee') {
        hideFormPart(element.id + '-container-custom');
      }
      else {
        showFormPart(element.id + '-container-custom');
      }
    }
  }
}

/**
 * load an extra werkverleden form part and insert it into the form
 * or disable the following blocks if "nee" is selected
 */
function field_baan(element)
{
  var e = $(element.id + '-ajax');
  if (e) {
    if (element.options[element.selectedIndex].value != 'nee') {
      e.id = element.id + '-container-customajax';
      new Ajax.Updater(e, '/jobopenings/werkverleden', {
        parameters: {
          n: element.id.match(/[0-9]*$/)[0]
        },
        onComplete: function() {
          initform(e);
          form_change(element, true);
          e.show();
        }
      });
    }
  }
  else {
    e = $(element.id + '-container-custom');
    if (e) {
      if (element.options[element.selectedIndex].value == 'nee') {
        hideFormPart(element.id + '-container-custom');
      }
      else {
        showFormPart(element.id + '-container-custom');
      }
    }
  }
}

/**
 * handle button mousover styling
 */
function afabbuttonmouseover(button)
{
	Event.observe(
	  button.identify(),
	  'mouseover',
	  function() { 
	  	var par = this.up('div');
	  	var par2 = par.up('div');
	  	this.addClassName('hover');
	  	par.addClassName('afabbutton-inner-hover'); 
	  	par2.addClassName('afabbutton-outer-hover');
	  }
	);
	Event.observe(
	  button.identify(),
	  'mouseout',
	  function() { 
	  	var par = this.up('div');
	  	var par2 = par.up('div');
	  	this.removeClassName('hover');
	  	par.removeClassName('afabbutton-inner-hover');
	  	par2.removeClassName('afabbutton-outer-hover');
	  }
	);  
}

function buttonStyles()
{
	var buttons = $$('.afabbutton-inner button');
	
	for (var b = 0; b < buttons.length; b++) {
	  afabbuttonmouseover(buttons[b]);
	}
	
	if ($('img-vrijblijvend-aanvragen')) {
		Event.observe(
		  'img-vrijblijvend-aanvragen',
		  'mouseover',
		  function() { 
		  	this.src= '/img/buttons/hover/vrijblijvend-aanvragen.gif';
		  }
		);
		Event.observe(
		  'img-vrijblijvend-aanvragen',
		  'mouseout',
		  function() { 
		  	this.src= '/img/buttons/vrijblijvend-aanvragen.gif';
		  }
		);
	}
	
  if ($('img-maximale-hypotheek')) {
		Event.observe(
		  'img-maximale-hypotheek',
		  'mouseover',
		  function() { 
		  	this.src= '/img/buttons/hover/maximale-hypotheek.gif';
		  }
		);
		Event.observe(
		  'img-maximale-hypotheek',
		  'mouseout',
		  function() { 
		  	this.src= '/img/buttons/maximale-hypotheek.gif';
		  }
		);
	}

}