// Returns true if all education related options are filled in. (if applicable)
function checkEducation(prefix) {
	var education  = customCheckSelectedOption(document.getElementById(prefix + '-relation-education'));
	if ( !(education == 5 || education == 4)) {
		return true;
	}
	// occupation on bachelor level
	if ($('#' + prefix + '-relation-hbo_occupation-option-0').is(':checked')) {
		return true;
	}
	// occupation not selected
	if (! $('#' + prefix + '-relation-hbo_occupation-option-1').is(':checked')) {
		return false
	}

	// if family member with hbo is answered, return true, else return false
	if ($('#' + prefix + '-relation-family_member_with_hbo-option-0').is(':checked')) {
		return true;
	}
	if ($('#' + prefix + '-relation-family_member_with_hbo-option-1').is(':checked')) {
		return true;
	}

	return false;
}

function customCheckPostalCodeAndHouseNumber(postalCodeDigitsID, postalCodeCharsID, houseNumberID) {

	var postalCodeDigitsID = postalCodeDigitsID || null;
	var postalCodeCharsID = postalCodeCharsID || null;
	var houseNumberID = houseNumberID || null;

	var postalCodeDigitsNode = document.getElementById(postalCodeDigitsID);
	if (postalCodeDigitsNode == null) return false;
	var postalCodeDigits = postalCodeDigitsNode.value;
	var postalCodeCharsNode = document.getElementById(postalCodeCharsID);
	if (postalCodeCharsNode == null) return false;
	var postalCodeChars = postalCodeCharsNode.value;
	var houseNumberNode = document.getElementById(houseNumberID);
	if (houseNumberNode == null) return false;
	var houseNumber = houseNumberNode.value;

	// Postalcode digits
	postalCodeRegEx = /^[0-9]{4}$/;
	if (!postalCodeDigits.match(postalCodeRegEx) || parseInt(postalCodeDigits) < 1000) return false;

	// Postalcode characters
	alphaRegEx = /^[a-zA-Z]{2}$/;
	if (!postalCodeChars.match(alphaRegEx)) return false;

	// House number
	numberRegEx = /^[0-9]{1,5}$/;
	if (!houseNumber.match(numberRegEx) || parseInt(houseNumber) < 1) return false;

	return true;
}


function customSetSelectedOption(id, index) {
	var id = id || null;
	var index = index || null;
	var selectNode = document.getElementById(id);
	var options = selectNode.getElementsByTagName('option');
	options[index].selected = 'selected';
}


function customCheckRequiredFields(ids) {
	var ids = ids || null;
	var count = 0;

	// Default fields
	var fieldIDs = ids['ids'];
	if (!customCheckFields(fieldIDs)) return false;

	// Fields dependent on a value selected
	var dependentIDs = ids['dependent'];
	count = dependentIDs.length;
	for (var i = 0; i < count; i++) {

		if (!customCheckDependentField(dependentIDs[i][0], dependentIDs[i][1])) return false;
	}
	return true;
}


// Check if input value is ok of a form element in the array depending on which item is selected
// Make sure the ids are in the right order (same order as the select)
function customCheckDependentField(selectID, ids) {
	var selectID = selectID || null;
	var ids = ids || null;
	var minIndex = 0;
	var selected, options;
	var selectNode = document.getElementById(selectID);
	options = selectNode.getElementsByTagName('option');
	// If first option has value 0, ignore it
	if (options[0].value == '0') minIndex = 1;
	selected = customCheckSelectedOption(selectNode);
	if (!selected) return false;
	// selected id minus option with value 0,
	// see customCheckSelectedOption for - 1
	selected = selected - minIndex - 1;
	itemID = ids[selected];
	if (!customCheckFields(new Array(itemID))) return false;
	return true;
}


// Check if input values are ok
function customCheckFields(ids) {
	var ids = ids || null;
	var count = ids.length;
	var id, itemNode, itemName;

	for (var i = 0; i < count; i++) {
		id = ids[i];
		itemNode = document.getElementById(id);
		if (itemNode == null) {
			alert('Item with id '+id+' not found');
			return false;
		}
		itemName = itemNode.nodeName.toLowerCase();
		switch (itemName) {
			case 'input' :
				if (!customCheckInputValue(itemNode)) return false;
				break;
			case 'div' :
				if (!customCheckDivInput(itemNode)) return false;
				break;
			case 'select' :
				if (!customCheckSelectedOption(itemNode)) return false;
				break;
			default :
				alert('No functionality yet for '+itemName);
		}
	}
	return true;
}

function customCheckInputValue(inputNode) {
	var inputNode = inputNode || null;
	var inputType = inputNode.type;
	switch (inputType) {
		case 'radio' :
			if (!customCheckRadioInput(inputNode)) return false;
			break;
		case 'hidden' :
		case 'text' :
			if (!customCheckTextInput(inputNode)) return false;
			break;
		default :
			alert('No functionality yet for '+inputType+' input');
	}
	return true;
}

function customCheckDivInput(divNode) {
	var divNode = divNode || null;
	var inputNodeList = divNode.getElementsByTagName('input');
	var numInputs = inputNodeList.length;
	if (numInputs < 1) {
		alert('No input found in div '+divNode.id);
		return false;
	}
	if (numInputs > 1) alert('More than 1 input found in div '+divNode.id);
	var inputNode = inputNodeList[0];
	if (!customCheckInputValue(inputNode)) return false;
	return true;
}

function customCheckRadioInput(radioNode) {
	var radioNode = radioNode || null;
	var name = radioNode.name;
	var radioNodes = document.getElementsByName(name);
	var count = radioNodes.length;
	for (i = 0; i < count; i++) {
		if (radioNodes[i].checked) return true;
	}
	return false;
}

function customCheckTextInput(textNode) {
	var textNode = textNode || null;
	var textValue = textNode.value;

	// If trimmed input value is empty
	var trimmedInput = textValue.replace(/^\s+|\s+$/g, '');
	if (trimmedInput != '' && trimmedInput != 0) {
		return true;
	}
	return false;
}

// Check if an option is selected
// Return the selected option index if found, false otherwise
function customCheckSelectedOption(selectNode) {
	var count = selectNode.options.length;
	if (count < 1) return false;
	var options = selectNode.getElementsByTagName('option');
	var minIndex = 0;
	var selected;

	// If first option has value 0, ignore it
	if (options[0].value == '0') minIndex = 1;
	selected = selectNode.options.selectedIndex;
	if (selected >= minIndex && selected < count) {
		// Return selected + 1 to make sure value isn't 0 (false)
		return selected + 1;
	}
	return false;
}


// These checks are used in the inventory form, this is done here because the parser
// translates && into &amp;&amp;.
function customCheckInventory(region,value,type)
{
    if(type == "jewelry")
    {
        if((region < 4 && value > 5000) || (region >= 4 && value > 2500))
            return true;
        else
            return false;
    }
    if(type == "audio_visual")
    {
        if((region < 3 && value > 7500) ||(region >= 3 && value > 5000))
            return true;
        else
            return false;
    }
    return false;
}
// also an inventory form, to display or dont display the
function customCheckInventoryExtra(region,value,type,locks,windows,alarm,alarm_link)
{
    if(type == "jewelry")
    {
        if((region < 4 && value > 5000) || (region >= 4 && value > 2500))
        {
           if(region < 4 && locks && windows)
                varreturn = (value-5000);
           else if(region == 4 && locks && windows && alarm)
                varreturn = (value-2500);
           else if(region > 4 && locks && windows && alarm && alarm_link)
                varreturn = (value-2500);
           else
                varreturn = 0;

            return varreturn;
        }
        else
            return 0;
    }
     if(type == "audio_visual")
    {
        if((region < 4 && value > 7500) || (region >= 3 && value > 5000))
        {
           if(region < 3 )
                varreturn = 0;
           else if(region == 3 && locks && windows)
                varreturn = (value-5000);
           else if(region == 4 && locks && windows && alarm)
                varreturn = (value-5000);
           else if(region > 4 && locks && windows && alarm && alarm_link)
                varreturn = (value-5000);
           else
                varreturn = 0;

           return varreturn;
        }
        else
            return 0;
    }
    return 0;
}

/****
 * Author: Gert-Jan Jansma <g.jansma@drecomm.nl>
 *
 * Compare age between date of birth and a given date || age (e.g: 1986-01-28 / 2003-01-28 or 1986-01-28 / 2)
 * Returns false when the result is less than 18
 */

function custom_ageComparison(dateofbirth, comparison) {
	var dateofbirth = ($(dateofbirth).val()) ? new Date($(dateofbirth).val().replace(/-/g,'/').substr(0,10)) : null;
	var currentDate = new Date();
	var element		= comparison || null;
	var comparison 	= $(comparison).val() || null;
	var validAge	= false;
	var minimumAge 	= 18;
	var userAge		= 0;
	if(dateofbirth && comparison){
		if(comparison.length < 3) dateofbirth.setDate(dateofbirth.getDate() - 1);
		if(!((currentDate.getMonth() > dateofbirth.getMonth()) || (currentDate.getMonth() == dateofbirth.getMonth() & currentDate.getDate() > dateofbirth.getDate()))){
			dateofbirth.setFullYear(dateofbirth.getFullYear() + 1);
		}
		if(comparison.length > 2){
			comparison = new Date(comparison.replace(/-/g,'/').substr(0,10)) || null;
			if(!((dateofbirth.getMonth() > comparison.getMonth()) || (dateofbirth.getMonth() == comparison.getMonth() & dateofbirth.getDate() > comparison.getDate()))){
				comparison.setFullYear(comparison.getFullYear() + 1);
			}
			userAge = (comparison.getFullYear() - dateofbirth.getFullYear());
		} else {
			userAge = ((currentDate.getFullYear() - dateofbirth.getFullYear()) - parseInt(comparison));
		}
		if(userAge < minimumAge){
			return false;
		}
	}
	return true;
}

/**
 * Checks age by date of birth on date specified by on-xxx parameters
 * On-xxx parameters are optional. Current date will be used when that is the case
 */
function customGetAgeByDate(dobYear, dobMonth, dobDay, onYear, onMonth, onDay) {
	if (!dobYear || !dobMonth || !dobDay || !onYear || !onMonth || !onDay) return false;

	if (onMonth > dobMonth) {
		return onYear - dobYear;
	} else if (onMonth < dobMonth) {
		return onYear - dobYear - 1;
	} else {
		if (onDay >= dobDay) {
			return onYear - dobYear;
		} else {
			return onYear - dobYear - 1;
		}
	}
}
