$(document).ready(function() {

  // Ga op zoek naar alle "date fields", door de 3 textvelden en hidden input te omsluiten met een <element class="date-field">...</element>
  var dateFields = $('.date-field');
  var i;
  var l = dateFields.length;
  var dateSeperator = '/';

  // Loop door door deze parents
  for (i = 0; i < l; i++) {

    // Vind hier binnen de 3 tekstvelden en het hidden input veld
    var dateField = $(dateFields[i]);
    var inputs = $('input.date-hand', dateField);
    var hidden = $('input.date-pick', dateField);

    // Set initial value in 3 text boxes(when their is a initial value).
    if (typeof(hidden) != 'undefined' && hidden.val() != '') {
      hiddenValue = hidden.val();
      var splitted = hiddenValue.split(dateSeperator);

      if (splitted.length == 3) {

        inputs.eq(0).val(splitted[0]);
        inputs.eq(1).val(splitted[1]);
        inputs.eq(2).val(splitted[2]);
      }
    }


    // Bind de keyup handler
    inputs.bind('keyup', {'currentInputs': inputs, 'currentHidden': hidden}, function(event) {

      // Vind de value en het maxlength attribuut (<input type="text" maxlength="2" />)
      var input = $(this);
      var currentInputs = event.data['currentInputs'];
      var currentHidden = event.data['currentHidden'];
      var val = input.val();
      var maxLength = input.attr('maxlength');

      // Als lengte van value gelijk is aan maxlength ...
      if (val.length === maxLength) {

        // ... vind volgend element
        var next = input.next();

        // ... als deze bestaat en dit is een tekstveld ...
        if (next && next.is(':text')) {

          // ... zet je er de focus op :-)
          next.focus();
        }
      }

      // Update je hidden input (let op volgorde van je velden in de DOM)
      currentHidden.val(currentInputs.eq(0).val() + dateSeperator + currentInputs.eq(1).val() + dateSeperator + currentInputs.eq(2).val());

      if (currentInputs.eq(0).val() != '' && currentInputs.eq(1).val() != '' && currentInputs.eq(2).val().length == 4) {
        FormValidation.changeFragment(currentHidden, true);
      }
    });

  }

  // Initialize zip code fields.
  var zipCodeFields = $('input.zipcodenumbers');

  if (typeof(zipCodeFields) != 'undefined' && zipCodeFields.length > 0) {

    zipCodeFields.each(function(i, e) {
      $parentField = $(this).parent('div.fields');

      var $hiddenField = $('.zipcodehidden', $parentField);

      if ($hiddenField.length > 0 && $hiddenField.val() != '' && $hiddenField.val().length == 6) {
        $('.zipcodenumbers', $parentField).val($hiddenField.val().substring(0, 4));
        $('.zipcodeletters', $parentField).val($hiddenField.val().substring(4, 6));
      }
    });
  }

  var btnAction = $("[name='beoordeelstatus']");
  if (btnAction.length != 0) {
    var form_buttonAction = btnAction.parents("form");
    form_buttonAction.find(":submit").click(function(e) {
        e.preventDefault();
        var btnClickedName = $(this).attr("name")
        btnAction.val(btnClickedName);
        if (btnClickedName == "back_button") {
          form_buttonAction.find("[name='showform']").val("false").change();
        }
        form_buttonAction.submit();
    });
  }

    /**
     * Brochures script.
     */
    if (typeof(brochInputEl) != "undefined") {
        $("div[class^=molist] input:checkbox").each(function() {
            $(this).change(function() {
                var brochValue = brochInputEl.attr("value");
                var valueString = this.value + ",";
                if(this.checked && brochValue.indexOf(valueString) == -1) {
                    brochInputEl.attr("value", brochValue + valueString);
                } else {
                    var re = new RegExp(valueString, "gi");
                    brochInputEl.attr("value", brochValue.replace(re, ""));
                }
            });
        });
    }

    $(':input', $(this)).each(function() {
        var inputName = $(this).attr("name");
        if ($(this).attr("class") == 'date-pick') {
            inputName = inputName.replace(/\./g, '_');
            $('#wmdate_' + inputName).change(function(){date_onchange($('#wmdate_' + inputName))});
        }
    });

    $(':input[name=collectivityrelationname]').val($('#collectivityrelationnameitem').text());
    $(':input[name=collectivityrelationphone]').val($('#collectivityrelationphoneitem').text().replace('-', ''));
    $(':input[name=collectivityaccmanageremail]').val($('#collectivityaccmanageremailitem').text());

    /**
     * Collectiviteit zoeker init.
     */
    initCollectivitySearch();

    /**
     * Werkgevers deelnemers zoeken
     */
    initParticipantSearch();

        // Show/hide the (in)active download links
        $('select.collectivitydropdown').change(function() {
            $('div.participator-init').hide();
            $('#participator-init-' + $(this).val()).show();
        });
        $('div.participator-init').hide();
        $('#participator-init-' + $('select.collectivitydropdown').val()).show();

    var initialsEl = $("input.initials");
    initialsEl.blur(function(){initials_onblur($(this))});

    /**
     * Back button fix, do not validate fields when the back button is pressed.
     * This is fixed by setting the click action to history.back() of the back button.
     */
    $("#advice input[name=wmback]").click(function(e){
        e.preventDefault();
        history.back();
    });

    $('#nagios').each(function() {
      nagiosCollectivitySearch();
    });

});

/**
 * Readspeaker scripts
 */
function rsTextSelection() {
  if (document.getSelection) { // older Mozilla versions
    var selectedString = document.getSelection();
  }
  else if (document.all) { // MSIE 4+
    var selectedString=document.selection.createRange().text;
  }
  else if (window.getSelection) { // recent Mozilla versions
    var selectedString=window.getSelection();
  }
  document.rs_form.selectedtext.value = selectedString;
  if (document.rs_form.url) {
    if (!document.rs_form.url.value) {
      if (window.location.href) {
        document.rs_form.url.value=window.location.href;
      }
      else if (document.location.href) {
        document.rs_form.url.value=document.location.href;
      }
    }
  }
}
function copyselected() {
  setTimeout("rsTextSelection()",50);
  return true;
}
function openAndRead() {
    window.open('','rs','width=380,height=180,toolbar=0');
  setTimeout("document.rs_form.submit();",500);
}
document.onmouseup = copyselected;
document.onkeyup = copyselected;

/**
 * Cendris scripts
 */
function document_onready(countryEl, zipcodeEl, housenumberEl, streetEl, residenceEl, valueNL) {
    country_onchange(countryEl, zipcodeEl, housenumberEl, streetEl, residenceEl, valueNL);
}

function country_onchange(countryEl, zipcodeEl, housenumberEl, streetEl, residenceEl, valueNL){
    if (countryEl.length != 0 && streetEl.length != 0 && residenceEl.length != 0) {
        if (countryEl.val().toUpperCase() == valueNL) {
            residenceEl.attr("readOnly","true");
            streetEl.attr("readOnly","true");
        } else {
            streetEl.removeAttr("readOnly");
            residenceEl.removeAttr("readOnly");
        }
        lookupAddress(countryEl, zipcodeEl, housenumberEl, streetEl, residenceEl, valueNL);
    }
}

function phonenumber_onblur(phonenumberEl) {
    if (phonenumberEl) {
        phonenumberEl.val(formatPhonenumber(phonenumberEl.val()));
    }
}

function date_onchange(dateEl) {
    if (dateEl) {
        dateEl.val(formatBirthDate(dateEl.val()));
    }
}

function initials_onblur(initialsEl) {
    if (initialsEl) {
        initialsEl.val(formatInitials(initialsEl.val()));
    }
}

function zipcode_onblur(zipcodeEl) {
    if (zipcodeEl) {
        zipcodeEl.val(formatZipcode(zipcodeEl.val()));
    }
}

function lookupAddress(countryEl, zipcodeEl, housenumberEl, streetEl, residenceEl, valueNL) {

    if (countryEl.length != 0 && countryEl.val() == valueNL) {
        var xmlhttp;
        if (streetEl.length != 0 && residenceEl.length != 0 && zipcodeEl.length != 0 && housenumberEl.length != 0) {
            var zipcode = zipcodeEl.val();
            var housenumber = housenumberEl.val();

            if (zipcode != "" && housenumber != "" && validZipcode(zipcode) && validHousenumber(housenumber)) {
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else if (window.ActiveXObject) {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                else {
                    alert("Your browser does not support XMLHTTP!");
                }

                //Add the spinner
                //var spinner = $( '<span class="spinner" style="display:block"><img src="/static/freestyle/sites/zenz/_images/read-only.gif" width="16" height="16" /></span>' );
                //streetEl.after(spinner);

                var url = "/web/wcbservlet/com.gxwebmanager.solutions.zenzwebservice.zipcodeservlet?zipcode=" + zipcode + "&housenumber=" + housenumber;
                if(typeof(usecendris) != 'undefined' && usecendris) {
                    url = "/web/wcbservlet/com.gxwebmanager.solutions.cendris.cendrisservlet.servlet?zipcode=" + zipcode + "&housenumber=" + housenumber;
                }
                xmlhttp.onreadystatechange = _stateChanged;
                xmlhttp.open("GET", url, true);
                xmlhttp.send(null);
                var xmlHttpTimeout = setTimeout(function(){
                    xmlhttp.abort();
                    streetEl.removeAttr("readOnly");
                    residenceEl.removeAttr("readOnly");
                }, 5000);
            }
        }
    }

  function _stateChanged() {
    if (xmlhttp.readyState == 4) {
      clearTimeout(xmlHttpTimeout);
      _completeAddress(xmlhttp.responseText);
    }
  }

  function _completeAddress(response) {
    //First remove spinner
      //alert('must remove spinner..');
      //if( spinner ) spinner.remove();

    var status;
    var street;
    var residence;
    try {
      var browserName = navigator.appName;
      var xmlDoc;
      if (browserName == "Microsoft Internet Explorer") {
          xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async="false";
          xmlDoc.loadXML(response);

          status = getZipcodeCheckValueIE(xmlDoc, "status");
          street = getZipcodeCheckValueIE(xmlDoc, "straatnaam");
          residence = getZipcodeCheckValueIE(xmlDoc, "woonplaats");
      } else {
          //Firefox, Mozilla, Opera, etc.
          var parser = new DOMParser();
          xmlDoc = parser.parseFromString(response,"text/xml");

          status = getZipcodeCheckValue(xmlDoc, "status");
          street = getZipcodeCheckValue(xmlDoc, "straatnaam");
          residence = getZipcodeCheckValue(xmlDoc, "woonplaats");
      }
    } catch(e) {
      // alert(e.message);

      // Enable street and residence
      streetEl.removeClass("grey");
      streetEl.removeAttr("readOnly");
      residenceEl.removeClass("grey");
      residenceEl.removeAttr("readOnly");

      return;
    }



    if (status == 1) {
      streetEl.val(street);
      residenceEl.val(residence);

      residenceEl.attr("readOnly","true");
      streetEl.attr("readOnly","true");

      streetEl.addClass("grey");
      residenceEl.addClass("grey");
    } else {
      // Enable street and residence
      streetEl.removeClass("grey");
      streetEl.removeAttr("readOnly");

      residenceEl.removeClass("grey");
      residenceEl.removeAttr("readOnly");
    }
  }
}

function formatInitials(initials) {
    initials = initials.toUpperCase();
    initials = initials.replace(/[^a-zA-Z\u00c0-\u00dd]/g, "");
    var arrayInitials = initials.split('');
    initials = arrayInitials.join(".");
    if (initials != '') {
        initials += '.';
    }
    return initials;
}

function formatZipcode(zipcode) {
    zipcode = zipcode.replace(/\s+/g, '');
    return zipcode;
}

function formatBirthDate(birthdate) {
    if (birthdate.match(/\d{8}/)) {
        birthdate = birthdate.substr(0,2) + '/' + birthdate.substr(2,2) + '/' + birthdate.substr(4,4);
    }
    birthdate = birthdate.replace(/-+/g, '/');
    return birthdate;
}

 function formatPhonenumber(phonenumber) {
    phonenumber = phonenumber.replace(/\s+/g, '');
    phonenumber = phonenumber.replace(/-+/g, '');
    return phonenumber;
}

function validZipcode(value) {
    return /^[1-9]{1}[0-9]{3}[a-zA-Z]{2}$/.test(value);
}

function validHousenumber(value) {
    return /^[0-9]+$/.test(value);
}

function getZipcodeCheckValue(xmlDoc, name) {
    var node = xmlDoc.evaluate("//member[name = '" + name + "']/value/string", xmlDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null );
    return node.singleNodeValue.textContent;
}

function getZipcodeCheckValueIE(xmlDoc, name) {
    xmlDoc.setProperty('SelectionLanguage', 'XPath');
    var node = xmlDoc.selectSingleNode("//member[name = '" + name + "']/value/string")
    var value = node.text;
    return value;
}

/**
 * Statistics methods
 */
function statisticsEvent(event) {
    if(event != "") {
        var s=s_gi(s_account);          // create s (SiteCatalyst) object
        s.linkTrackVars='events';   // specify variables to track
        s.linkTrackEvents=event;    // specify events to track
        s.events=event;       // populate event variable
        s.tl(this,'o', event);      // send request
    }
}

function statisticsEventNewletterSubscribe(gender) {
    var event = "event42";
    var s=s_gi(s_account);          // create s (SiteCatalyst) object
    s.linkTrackVars='events,prop12,eVar12';    // specify variables to track
    s.linkTrackEvents=event;    // specify events to track
    s.events=event;       // populate event variable
    s.eVar12=s.prop12=gender;
    s.tl(this,'o', event);      // send request
}

/**
 * Interactive forms methods
 */
function checkAge(birthdateString, minAge, maxAge, compareToday, currentDateOverride) {
    if (birthdateString == null || birthdateString == '') {
        return false;
    }
    if (compareToday === null || compareToday === '') {
        compareToday = true;
    }

    // Get current date
    var currentDate = new Date();
    if (typeof(currentDateOverride) != "undefined") {
        var date = parseDate(currentDateOverride);
        if (date != null) {
            currentDate = date;
        }
    }

    // Get min max dates
    var minDate = new Date(currentDate);
    var maxDate = new Date(currentDate);

    if (compareToday === false) {
        minDate = new Date(currentDate.getFullYear() - maxAge, 0, 1);
        maxDate = new Date(currentDate.getFullYear() - minAge + 1, 0, 1);
    } else {
        minDate.setFullYear(currentDate.getFullYear() - maxAge - 1);
        maxDate.setFullYear(currentDate.getFullYear() - minAge);
    }

    // Parse birthdate
    var birthdate = parseDate(birthdateString);
    var today = new Date();

    // Check birthdate
    if (birthdate != null && birthdate > minDate && birthdate <= maxDate) {
        return true;
    } else if (birthdate != null && birthdate >= currentDate && birthdate <= today.addMonths(9)){
      return true;
    } else {
        return false;
    }
}

/**
 * Check if person with birthdate "b" is 18 at contractdate "a"
 */
function isEighteen(a, b) {
    if (a.getFullYear() - b.getFullYear() < 18) {
        return false;
    }
    if (a.getFullYear() - b.getFullYear() > 18) {
        return true;
    }
    if (a.getFullYear() - b.getFullYear() == 18) {
        if (a.getMonth() < b.getMonth()) {
            return false;
        }
        if (a.getMonth() > b.getMonth()) {
            return true;
        }
        if (a.getDate() < b.getDate()) {
            return false;
        }
        if (a.getDate() >= b.getDate()) {
            return true;
        }
    }
}


/**
 * Interactive forms methods
 */
function getAge(birthdateString, compareStartNextYear) {
    if (birthdateString == null || birthdateString == '') {
        return null;
    }

    // Parse birthdate
    var birthdate = parseDate(birthdateString);

    // Get current date
    var currentDate = new Date();

    if (compareStartNextYear) {
        currentDate = new Date(currentDate.getFullYear()+1, 0, 1);
    }

    // Check birthdate
    if (birthdate != null) {
        var age = currentDate.getFullYear() - birthdate.getFullYear();

        // Check if a correction is needed
        if(currentDate.getMonth() - birthdate.getMonth() < 0
            || (currentDate.getMonth() - birthdate.getMonth() == 0
                && currentDate.getDate() - birthdate.getDate() < 0)) {
          age -= 1;
        }

        return age;
    } else {
        return null;
    }
}
/**
 * Parses a date string. (e.g. dd/mm/yyyy or dd-mm-yyyy)
 * @param dateString
 * @returns {Date}
 */
function parseDate(dateString) {
    // Replace '-'
    dateString = dateString.replace(/-/gi, '/');
    // Split into values
    var dateValues = dateString.split("/");
    if (dateValues.length == 3) {
        var day = dateValues[0];
        var month = dateValues[1] - 1;
        var year = dateValues[2];
        // Create date object
        var date = new Date(year, month, day);

        // Check if date is valid
        var isDate = (date.getMonth() == month && date.getDate() == day && date.getFullYear() == year);
        if (isDate) {
            return date;
        } else {
            return null;
        }
    } else {
        return null;
    }
}

/**
 * Checks a date.
 * @param dateString
 * @param minDateString
 * @param maxDateString
 * @returns {Boolean}
 */
function checkDate(dateString, minDateString, maxDateString) {
    // Get date
    var date = (dateString == "current") ? new Date() : parseDate(dateString);
    if (date != null) {
        // Get min & max dates
        var minDate = (minDateString == "current") ? new Date() : parseDate(minDateString);
        var maxDate = (maxDateString == "current") ? new Date() : parseDate(maxDateString);
        // Check date
        if (minDate != null && maxDate != null && date > minDate && date < maxDate) {
            return true;
        } else if (minDate != null && maxDate == null && date > minDate) {
            return true;
        } else if (minDate == null && maxDate != null && date < maxDate) {
            return true;
        }
    }
    return false;
}

/**
 * Clear a value for a form field. Different types need special handling.
 * This is a private utility function(could better be moved to library).
 */
function clearValue(obj) {
    if (obj.attr("type") == 'radio' || obj.attr("type") == 'checkbox') {
        obj.attr('checked', false);
    } else if(obj.is('select')) {
        obj.val('');
        var resetText = obj.find('option:selected').text();
        obj.prev().find('span').text(resetText);
    } else {
        obj.val('');
    }
}

/**
 * Shifts values up when an item 'additem' is removed.
 * @param the container for the add item rows(direct parent of the items)
 */
function shiftValues(rowNumber, allItems) {
    // When last row is removed, just delete the values. There is nothing to shift.
    // e.g. allItems[i+1] will be undefined in the next default loop.
    if (allItems.length-1 == rowNumber) {

        if (jQuery(allItems[allItems.length-1])) {
            var fromFields = $(':input, select',jQuery(allItems[allItems.length-1])).not(':button, :submit, :reset');
            fromFields.each(function() {
                clearValue($(this));
            });
        }
    }

    // Start moving values from item+1 to the deleted item. NOTE: the rows above the deleted one
    // can be ignored.
    for (i=rowNumber; i < allItems.length-1; i++) {

        if (typeof allItems[i] != 'undefined' && typeof allItems[i+1] != 'undefined') {
            // Item to copy to.
            var thisItem = jQuery(allItems[i]);
            var nextAddItem = jQuery(allItems[i+1]);

            // Copy the field values.
            var fromFields = $(':input, select',nextAddItem).not(':button, :submit, :reset');
            var clearLastForm = (i+1 == allItems.length-1);

            fromFields.each(function() {
                var fieldName = $(this).attr('name');

                if (fieldName != '') {
                    var value = $(this).val();

                    // Get the field to copy to.
                    var toFieldName = fieldName.replace('.' + (i+1), '.' + i);
                    var expr = '"[name=' + toFieldName + ']"';
                    var toField = jQuery(expr, thisItem);

                    // For checkboxes we pass the array of values.
                    if ($(this).attr("type") == 'radio') {
                        if ($(this).is(":checked")) {
                            var theCheckedValue = $(this).val();
                            toField.each(function() {
                                if (theCheckedValue == $(this).val()) {
                                    $(this).attr('checked', true);
                                } else {
                                    $(this).attr('checked', false);
                                }
                            });
                        }
                    } else if ($(this).attr("type") == 'checkbox') {
                        var theCheckedValue = $(this).val();
                        var isChecked = $(this).is(':checked');
                        toField.each(function() {
                            if (theCheckedValue == $(this).val()) {
                                if (isChecked) {
                                    $(this).attr('checked', true);
                                } else {
                                    $(this).attr('checked', false);
                                }
                            }
                        });
                    } else if($(this).is('select')) {
                        toField.val(value);
                        var toFieldtext = toField.find('option:selected').text();
                        toField.prev().find('span').text(toFieldtext);
                    } else {
                        toField.val(value);
                    }

                    if (clearLastForm) {
                        clearValue($(this));
                    }
                }
            });
        }
    }
    return true;
}

/**
 * Initializes the repeat with button field.
 */
function initRepeatButton(repeatId, maxRepeats, removeButtonHtml) {
    var repeatClass = ".repeatbutton" + repeatId;
    var countClass = ".repeatbuttoncount";
    var repeatElementClass = ".formsectionelement";
    var removeButtonClass = ".removebutton";
    var firstRemoveButtonClass = ".formsectionelement:first .removebutton";
    var addButtonClass = ".addbutton";

    // Check if repeat is already initialized
    if (maxRepeats > 1 && $(repeatClass).find(firstRemoveButtonClass).length == 0) {
        $(repeatClass).each(function(i) {

            // Set remove buttons
            $(this).find(repeatElementClass).each(function(i) {
                var countField = $(this).parents(repeatClass).find(countClass);
                var countValue = parseInt(countField.val());
                // Add button html
                $(this).append(removeButtonHtml);
                var removeButton = $(this).find(removeButtonClass);
                if (countValue == 1 && i == 0) {
                    removeButton.css("display", "none");
                }
                // Set onclick
                removeButton.click(function(e) {
                    e.preventDefault();
                    // Shift value up
                    var shifted = shiftValues(i, $(this).parents(repeatClass).find(repeatElementClass));
                    if (shifted) {
                        // Set count field
                        var countField = $(this).parents(repeatClass).find(countClass);
                        var countValue = parseInt(countField.val());
                        if (countValue > 1) {
                            var newCountValue = countValue - 1;
                            countField.val(newCountValue).change();
                            // Show/hide buttons
                            if (newCountValue == 1) {
                                // Hide first remove button
                                $(this).parents(repeatClass).find(firstRemoveButtonClass).css("display", "none");
                            } else if (newCountValue < maxRepeats) {
                                // Show add button
                                $(this).parents(repeatClass).find(addButtonClass).css("display", "block");
                            }
                        }
                    }
                });
            });

            // Set add buttons
            if ($(this).find(countClass).val() == maxRepeats) {
                $(this).find(addButtonClass).hide();
            }
            $(this).find(addButtonClass).each(function(i) {
                $(this).click(function(e) {
                    e.preventDefault();
                    // Set count field
                    var countField = $(this).parents(repeatClass).find(countClass);
                    var countValue = parseInt(countField.val());
                    if (countValue < maxRepeats) {
                        var newCountValue = countValue + 1;
                        countField.val(newCountValue).change();
                        // Show/hide buttons
                        if (newCountValue == maxRepeats) {
                            // Hide add button
                            $(this).css("display", "none");
                        } else if (newCountValue > 1) {
                            // Show first remove button
                            $(this).parents(repeatClass).find(firstRemoveButtonClass).css("display", "block");
                        }
                    }
                });
            });
        });
    }
}

/**
 * Initializes the collectivity search.
 */
var collectivityOnChangeFired = false;
function initCollectivitySearch() {
    if ($(".collectiviteit").length > 0) {

        // Set collectivities
        $(".collectiviteit").each(function() {
            var collectivity = $(this);
            // Init
            searchCollectivity(collectivity);

            // Set input field event
            collectivity.find(".collectiviteit-input").change(function() {
                collectivityOnChangeFired = true;
                searchCollectivity(collectivity);
            });

            // Set button event
            collectivity.find(".collectiviteit-button").click(function(e) {
                e.preventDefault();
                if (!collectivityOnChangeFired) {
                    searchCollectivity(collectivity);
                }
            });

            // Set adjust button event
            collectivity.find(".collectiviteit-button-adjust").click(function(e) {
                collectivityOnChangeFired = false;
                e.preventDefault();
                adjustCollectivity(collectivity);
            });

        });
    }
}

/**
 * Searches for a collectivity.
 * @param collectivity
 */
function searchCollectivity(collectivity) {
    var inputElement = collectivity.find(".collectiviteit-input");
    var inputElementValue = inputElement.val();
    var formattedDatumValue = "";
    var inputDatumElementValue = $("input[name$=ingangsdatum]").val().replace(/\s+/g, '');
    if(typeof(inputDatumElementValue) != "undefined") {
        var dateYear = inputDatumElementValue.substr(6,4);
        var dateMonth = inputDatumElementValue.substr(3,2);
        var dateDay = inputDatumElementValue.substr(0,2);
        formattedDatumValue = dateYear + "-" + dateMonth  + "-" + dateDay ;
    }
    if (inputElementValue != "" && inputElementValue != 0) {
        $.getJSON(collectivityLink,
            {
                collectivityid: inputElementValue,
                peildatum: formattedDatumValue
            },
            function(data) {
                // Check if a collectivity is found
                if (data != null && data.collectiviteit != null) {
                    // Get collectivity
                    var collectiviteit = data.collectiviteit;
                    var naam = collectiviteit.naam;
                    var opmerking = collectiviteit.opmerking;

                    // Fill hidden fields
                    $("#wmtext_collectiviteitenzoeker_collectiviteitsnaam").val(naam);
                    $("#wmtext_collectiviteitenzoeker_opmerking").val(opmerking);

                    // Check if opmerking is empty or is dummy service
                    if (opmerking == "" || naam == ("CommercieleNaam_" + inputElementValue)) {
                        // Hide input & show text
                        inputElement.hide();
                        collectivity.find(".collectiviteit-text").html(naam).show();

                        // Show adjust button & hide get button
                        collectivity.find(".collectiviteit-button").hide();
                        collectivity.find(".collectiviteit-button-adjust").show();
                    } else {
                        // Empty collectivity id & hide input element
                        inputElement.val("");
                        inputElement.hide();
                        // Show text with description
                        var text = naam + "<br><br><i>" + opmerking + "</i>";
                        collectivity.find(".collectiviteit-text").html(text).show();
                        // Show adjust button & hide get button
                        collectivity.find(".collectiviteit-button").hide();
                        collectivity.find(".collectiviteit-button-adjust").show();
                    }
                    // Hide extra text
                    collectivity.find(".fieldinfoExtra").hide();
                } else {
                    // Show extra text
                    collectivity.find(".fieldinfoExtra").show();
                    // Empty hidden fields
                    $("#wmtext_collectiviteitenzoeker_collectiviteitsnaam").val("");
                    $("#wmtext_collectiviteitenzoeker_opmerking").val("");
                    $("#wmtext_collectiviteitenzoeker_collectiviteitsnummer").val("");
                    // Hide collectivity text
                    collectivity.find(".collectiviteit-text").html("");
                    collectivity.find(".collectiviteit-text").hide();

                    // Hide extra text
                    collectivity.find(".fieldinfoExtra").hide();

                    // Show text with description
                    var opmerking = data.result.opmerking;
                    if(opmerking != null) {
                      collectivity.find(".fieldinfoExtra").show();
                    }
                }
            }
        );
    } else {
        // Empty collectiviteitsnummer in case it is 0
        inputElement.val("");
        // Empty hidden fields
        $("#wmtext_collectiviteitenzoeker_collectiviteitsnaam").val("");
        $("#wmtext_collectiviteitenzoeker_opmerking").val("");
        // Hide collectivity text
        collectivity.find(".collectiviteit-text").html("");
        collectivity.find(".collectiviteit-text").hide();
        // Hide extra text
        collectivity.find(".fieldinfoExtra").hide();
    }
}

/**
 * Searches for a collectivity.
 * @param collectivity
 */
function nagiosCollectivitySearch() {
    var inputElementValue = $.trim($('#nagios').html());
    var formattedDatumValue = '2011-01-01';
    if (inputElementValue != "" && inputElementValue != 0) {
        $.getJSON(collectivityLink,
            {
                collectivityid: inputElementValue,
                peildatum: formattedDatumValue
            },
            function(data) {
                // Check if a collectivity is found
                if (data != null && data.collectiviteit != null) {
                    // Get collectivity
                    var collectiviteit = data.collectiviteit;
                    var naam = collectiviteit.naam;
                    var opmerking = collectiviteit.opmerking;
                    $('#nagios').html(naam);
                } else {
                  $('#nagios').html('Een fout is opgetreden bij het ophalen van de collectiviteit');
                }
            }
        );
    } else {
      $('#nagios').html('Er kon geen collectiviteitnummer worden gevonden!');
    }
}

/**
 * Make the collectivity adjustable.
 * @param collectivity
 */
function adjustCollectivity(collectivity) {
    // Show input
    collectivity.find(".collectiviteit-input").show();
    // Hide text
    collectivity.find(".collectiviteit-text").html("");
    collectivity.find(".collectiviteit-text").hide();
    // Show search button
    collectivity.find(".collectiviteit-button").show();
    // Hide adjust button
    collectivity.find(".collectiviteit-button-adjust").hide();
}

/**
 * Get a date object from a date string that matches the format "dd-mm-yyyy".
 */
function getDate(dateString) {
    if (dateString != "") {
        regExp = new RegExp("^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$","");

        if (regExp.test(dateString)) {
            splitted = dateString.split('-');

            if (splitted.length == 3) {
                dd = splitted[0];
                mm = splitted[1];
                yyyy = splitted[2];

                var d = new Date(mm + "/" + dd + "/" + yyyy);
                isDate = (d.getMonth() + 1 == mm && d.getDate() == dd && d.getFullYear() == yyyy);
                return d;
            }
        }
    }
    return null;
}

/**
 * Date format validation, checks if a date string matches the format "dd-mm-yyyy" and whether the date exists.
 */
function isValidDateString(dateString) {
    return (getDate(dateString) != null);
}

// Variable will be set to true by entering an invalid date and cleared upon fixing the date
var blockDeleteSubmit = false;

/**
 * Validations for the employers participants search form.
 */
function initParticipantSearch() {
  // Clicking a href submits form
  $("#participator-submit").click(function() {
        $("#participator-search").submit();
        return false;
  });

  // Reformat 8 digit date to "dd-mm-yyyy"
  $("#ps-birthdate").blur(function() {
    value = $(this).val();
    regExp = new RegExp("^[0-9]{8}$","");

    if (regExp.test(value)) {
      $(this).val(value.substring(0, 2) + "-" + value.substring(2, 4) + "-" + value.substring(4, 8));
    }

  });

  // Instant error checks for date range inputs
  $("input.pr-daterange").blur(function() {
  var value = $(this).val();
  var id = $(this)[0].id;
  var dateRange = document.getElementById("date_range_values_"+ id);
    var startRangeValue = "";
    var endRangeValue = "";
    var today  = new Date();
    var month = today.getMonth() + 1;
    if( month.length = 1){
      month = '0'+month;
    }
  var day = today.getDate();
  var year = today.getFullYear();


    if(dateRange != null){
      dateRangeValues = dateRange.value;
      rangeValues = dateRangeValues.split(";");
      startRangeValue = rangeValues[0];
      endRangeValue = rangeValues[1];

      if(startRangeValue == undefined){
        startRangeValue = "1880-01-01";
      }
      if(endRangeValue == undefined){
        endRangeValue = year + "-" + month + "-" + day;
      }
    }else{
      startRangeValue = "1880-01-01";
      endRangeValue = year + "-" + month + "-" + day;
    }

    if (value != "") {
        // Reformat 8 digit date to "dd-mm-yyyy"
        regExp = new RegExp("^[0-9]{8}$","");

        if (regExp.test(value)) {
            value = value.substring(0, 2) + "-" + value.substring(2, 4) + "-" + value.substring(4, 8);
            $(this).val(value);
        }

        if (isValidDateString(value)) {
            var theDate = getDate(value);
            var today = new Date();
            var searchValue = "-";
            var replaceValue = "/";
            var longAgo = new Date('1880/01/01');

            var sdate= replaceAll(startRangeValue, searchValue, replaceValue);
            var startDate = new Date(sdate);

            var edate= replaceAll(endRangeValue, searchValue, replaceValue);
            var endDate = new Date(edate);

            if (theDate.zeroTime() >= startDate.zeroTime() && theDate.zeroTime() <= endDate.zeroTime()) {
                $(this).parents(".field").removeClass("error");
                blockDeleteSubmit = false;
            } else {
                $(this).parents(".field").addClass("error");
                blockDeleteSubmit = true;
            }
        } else {
            $(this).parents(".field").addClass("error");
            blockDeleteSubmit = true;
        }
    } else {
        $(this).parents(".field").removeClass("error");
        blockDeleteSubmit = false;
    }
  });


  // Validate search form on submit
  $("#participator-search").submit(function() {
    var errorText = "";

    // Birthdate should be a valid date
    value = $(this).find("input[name=searchbirthdate]").val();

    if (value != "") {
        if (isValidDateString(value)) {
            var theDate = getDate(value);
            var today = new Date();
            var longAgo = new Date('1880/01/01');

            if (theDate < today && theDate > longAgo) {
                isDate = true;
            } else {
                isDate = false;
            }
        } else {
            isDate = false;
        }
    } else {
        isDate = true;
    }

    if (!isDate) {
      errorText = errorText + "<li>Ongeldige datum.</li>";
      $(this).find("input[name=searchbirthdate]").parents(".field").addClass("error");
    } else {
      $(this).find("input[name=searchbirthdate]").parents(".field").removeClass("error");
    }

    // BSN can only consist of 8 or 9 numbers
    value = $(this).find("input[name=searchbsn]").val();
    regExp = new RegExp("^[0-9]{8,9}$","");

    if (value != "" && !regExp.test(value)) {
      errorText = errorText + "<li>BSN mag alleen uit 8 of 9 cijfers bestaan.</li>";
      $(this).find("input[name=searchbsn]").parents(".field").addClass("error");
    } else {
      $(this).find("input[name=searchbsn]").parents(".field").removeClass("error");
    }

    // Relation id can only consist of 8-10 numbers
    /*var value = $(this).find("input[name=searchrelationid]").val();
    var regExp = new RegExp("^[0-9]{8,10}$","");

    if (value != "" && !regExp.test(value)) {
      errorText = errorText + "<li>Relatienummer moet uit minimaal 8 en maximaal 10 cijfers bestaan.</li>";
      $(this).find("input[name=searchrelationid]").parents(".field").addClass("error");
    } else {
      $(this).find("input[name=searchrelationid]").parents(".field").removeClass("error");
      if (value.length < 10 && value.length > 0) {
        $(this).find("input[name=searchrelationid]").val("00".substring(value.length - 8) + value);
      }
    }*/


    // Display errors if there were any
    if (errorText != "") {
      errorText = "<h2>Let op! Wilt u de volgende velden alstublieft (juist) invullen?</h2><ul>" + errorText + "</ul>";
      $("#errorholder").html(errorText).show();
      return false;
    } else {
      $("#errorholder").html("").hide();
      return true;
    }
  });
}

function replaceAll(txt, replace, with_this) {
    return txt.replace(new RegExp(replace, 'g'),with_this);
  }

