/* requires JQuery! */

function SelectorMaximizer(max) {
	this.els = Array();
	this.max = max;
	this.totalFieldElement = null;
}

SelectorMaximizer.prototype.add = function(selectorElement) {
	this.els.push(selectorElement);
	var selectorMaximizer = this;
	$(selectorElement).change(function() {
		selectorMaximizer.selectorChanged();
	});
}

SelectorMaximizer.prototype.setTotalField = function(totalFieldElement) {
	this.totalFieldElement = totalFieldElement;
}

SelectorMaximizer.prototype.getTotal = function() {
	var subTotal = 0;
	for (i = 0; i < this.els.length; i++) {
		subTotal += parseInt(this.els[i].value);
	}
	return subTotal;
}

SelectorMaximizer.prototype.selectorChanged = function() {
	var subTotal = this.getTotal();
	var maxSelectable = this.max - subTotal;

	for (i = 0; i < this.els.length; i++) {
		var selector = this.els[i];
		var options = selector.options;
		var currentValue = parseInt(this.els[i].value);
		for (j = 0; j < options.length; j++) {
			var optionValue = parseInt(options[j].value);
			if (optionValue <= currentValue) {
			} else {
				if ((optionValue - currentValue) <= maxSelectable) {
				} else {
					selector.remove(j);
					j--;
				}
			}
		}
	
		if (maxSelectable > 0) {
			var addRows = currentValue + maxSelectable - (options.length - 1);
			var length = options.length;
			for (j = 0; j < addRows; j++) {
				var newOption = new Option(length + j, length + j);
				try {
					selector.add(newOption, null); // standards compliant
				}
				catch(ex) {
					selector.add(newOption); // IE only, thanks http://www.w3schools.com/htmldom/met_select_add.asp
				}
			}
		}
	}
	
	if (this.totalFieldElement != null) {
		this.totalFieldElement.innerHTML = subTotal;
	}
}

function limitOptionResponses(id, max) {
	var $checkboxes = $('div#option_question_' + id + ' input.question_choice');
	$checkboxes.click(function() {
		if (countCheckboxes(this.form, id) == max) {
			$checkboxes.each(function() {
				if (!this.checked) this.disabled = true;
			});
		} else {
			$checkboxes.each(function() {
				this.disabled = false;
			});
		}
	});
}



function getNumericOrMakeRed(element) {
	if (element.value.trim().isNumeric()) {
		element.style.color = 'black';
		return parseInt(element.value.trim());
	} else if (element.value.trim() == '') {
		element.style.color = 'black';
	} else {
		element.style.color = 'red';
	}
	return 0;
}

function externalLinks() { 
	if (!document.getElementsByTagName) return; 
	var anchors = document.getElementsByTagName("a"); 
	for (var i = 0; i < anchors.length; i++) { 
		var anchor = anchors[i]; 
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank"; 
		}
	}
}

if (window.addEventListener) {
	window.addEventListener('load', externalLinks, false); 
} else if (window.attachEvent) { 
	window.attachEvent('onload', externalLinks);
}

function hoverMouseOver(e) {
	this.src = this.overSrc;
}

function hoverMouseOut(e) {
	this.src = this.outSrc;
}

function hoverImages() {
	if (!document.getElementsByTagName) return; 
	var images = document.getElementsByTagName("img");
	if (images != undefined) hoverize(images);
	var inputs = document.getElementsByTagName("input");
	if (inputs != undefined) hoverize(inputs);
}

function isClass(e, className) {
	var classes = e.className.split(' ');
	for (var i = 0; i < classes.length; i++) {
		if (classes[i] == className) return true;
	}
	return false;
}

function hoverize(elements) {
	for (var i = 0; i < elements.length; i++) {
		var image = elements[i];
		if(isClass(image, 'hover_image')) {
			var n = image.src.lastIndexOf('.');
			var prefix = image.src.substring(0, n);
			var postfix = image.src.substring(n);
			image.outSrc = image.src;
			image.overSrc = prefix + '_over' + postfix;

			image.onmouseover = hoverMouseOver;
			image.onmouseout = hoverMouseOut;
		}
	}
}

String.prototype.isEmail = function() {
	var emailTestRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	return this.match(emailTestRegex) != null;
};

String.prototype.isNumeric = function() {
	return this.match('^[0-9]+$') != null;
};


// two string methods from http://www.ditchnet.org/wp/2005/04/04/i-want-my-javalang/

/**
 *  String convenience method to trim leading and
 *  trailing whitespace.
 *  @returns string
 */
String.prototype.trim = function () {
    return this.replace(/^s*/,'')
                     .replace(/s*$/,'');
};

/**
 *  String convenience method for checking if the
 *  end of this string equals a given string.
 *
 *  @returns boolean
 *  @throws IllegalArgumentException for parameters
 *                          not of type String
 */
String.prototype.endsWith = function (s) {
    if ('string' != typeof s) {
        throw('IllegalArgumentException: Must pass a ' +
            ' string to String.prototype.endsWith()');
    }
    var start = this.length - s.length;
    return this.substring(start) == s;
};

// checks op verplichte open vragen

function getOpenResponseValue(form, num) {
	return form.elements['openResponse[' + num + ']'].value.trim();
}
	
// checks op verplichte meerkeuze vragen met 1 in te vullen keuze per vraag
	
function anyChecked(form, num) {
	window.status = 'anyChecked ' + num;
	var fields = form.elements['optionResponse[' + num + ']'];
	for (var i = 0; i < fields.length; i++) {
		if (fields[i].checked) return true;
	}
	return false;
}

// checks op verplichte meerkeuze vragen met meerdere in te vullen  keuzes per vraag

function manyAnyChecked(form, num, to) {
	window.status = 'manyChecked ' + num;
	var numQuestions = (to - num);
	for (var i = 0; i < numQuestions; i++) {
		if (!anyChecked(form, '' + (num + i))) return false;
	}
	return true;
}

function countCheckboxes(form, num) {
	var fields = form.elements['optionResponse[' + num + '][]'];
	var counter = 0;
	for (i = 0; i < fields.length; i++) {
		if (fields[i].checked) counter++;
	}
	return counter;
}
