/**
 * This File handles User input Validation
 * Mostly called by 'validation_helper.rb'
 */

var minus_fields = 0;

// switch a certain element valid or invalid
// 0 for invalid, 1 for valid
function setV(selector,state) {
	var neg = 'validate_negative';
	var pos = 'validate_positive';
	var elt = $(selector);
	if (state == 1)	{
		elt.removeClass(neg);
		elt.addClass(pos);
	} else {
		elt.removeClass(pos);
		elt.addClass(neg);
	}
}

window.setTimeout("refresh_all_inputs()", 400);

// refresh all validations
function refresh_all_inputs() {
  $('input').trigger('keyup');		  
	// slow
  $('input:radio').trigger('onchange');		  
  $('select').trigger('onchange');		  
}

// --- validate existance of a certain element
//     element can be searched for by a jQuery selector
//     for example for radio button not empty behavior
//     use 'input:radio[name=name]'
//     the validation-class-attribute gets written to
//     the x'th parent element if param parental is supplied
function validate_radio_not_empty(selector, parental) {
	var pp = $(selector);
	// var pp = $(selector+':first');
//	alert(selector + "\n" + pp.length);
//  var cname = selector+':checked';
//  var elt = $(cname);
	var elt = pp.parent().parent().find(':checked');
//	alert(pp.attr('id')+"\n" + cname + "\n"+elt.length);

//	alert(typeof(parental));
	if (typeof(parental) == 'number')
		for (var i = 0; i < parental; i++) {
			pp = pp.parent();
//			alert(pp.attr('id') + "\n" + pp.attr('class'));
		}
	if (elt.length > 0)	setV(pp,1);	else setV(pp,0);
	validate_form('validate_form');
}

// --- this function returns class='validate_negative' if textfield is empty
//	   else class='validate_positive'
//	   @params: textfield.id
// function validate_not_empty(textfield_id) {
function validate_not_empty(selector) {
	// for down-compatibility with old param style:	
	if (typeof(selector) == 'string')
		if (selector[0] != '#') selector = '#' + selector;

	if ($(selector).val() == '')
		setV(selector,0);
	else
		setV(selector,1);

	//if ($('#submit').length > 0) validate_form('validate_form');
	validate_form('validate_form');
}

// deprecated
// use instead validate_not_empty
//function validate_select(element) {}


// --- this function validates certain format of password
//     currently minimum length 


// --- this function assigns class='validate_negative'
//     if password is not valid or passwords do not match
//	   @params: a (mandatory), b (optional confirmation field)
//	   if no parameter b is supplied the id of the 
//	   confirmation input field has to have the same id
//	   as the main password field plus the suffix
//	   "_confirmation" so the method is ablte to find it
function confirm_password(a,b) {
	a = $(a);
	if (b != undefined)
	 	b = $(b);
	else {
		var id = a.attr('id');
	  var regex = /_confirmation$/; 
		if (id.match(regex)) {
			b = $('#'+id.replace(regex, '')); 
			var dummy = a; 	a = b; b = dummy
		}
		else
			b = $('#'+id+'_confirmation');
	}
	// test match
	var aState = 0, bState = 0;
	if (a.val() == b.val())	bState = 1;
	// test password length
	if (a.val().length > 3) aState = 1;
	setV(a,aState);
	setV(b,bState);

	//if ($('#submit').length > 0) validate_form('validate_form');
	validate_form('validate_form');

}

// --- validates an EMail textField 
//	   @params: element node or jquery selector
function validate_email(element) {
//	var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
	var re = /^[A-Za-z0-9.!\#\$\%\&'*+-\/=\?\^_`\|\~]+@[A-Za-z0-9\-\.]+$/;
	element = $(element);
	var result = 0;  if (element.val().match(re)) {result = 1}
	setV(element,result);
	validate_form('validate_form');
}

// --- validate form
//     based upon elements carrying class 'validate_negative'
//	   @params: form.name
function validate_form(form_name) {
	var button = $("[name='commit']:first");
	if (button.length < 1)
		return ;
	return setSubmit($('.validate_negative').length);
}

// --- enable or disable submit button
//     based upon remaining invalid field count
function setSubmit(remaining) {
	var src_result, wording;
	var disabled = false; var DS = 'disabled';
	var button = $("[name='commit']:first");
  var src_path = '../images/buttons/'+ button.attr('title');
  var	src_on = src_path + '.png';
  var	src_off = src_path + '_inactive.png';
	var plural = "Es Fehlen noch " + remaining + " Pflichtfelder.";
	var singular = "Es fehlt noch 1 Pflichtfeld.";
	var ready = "Du kannst das Formular jetzt abschicken.";
	if (remaining == 0) {
		// enable
		src_result = src_on;
		wording = ready;
	} else {
		// disable
		src_result = src_off;
		disabled = true;
		if (remaining > 1)
			wording = plural;
		else		
			wording = singular;
	}
	(disabled) ? button.attr(DS, DS) : button.removeAttr(DS);
//	button.attr('src', src_result);
  $('#submit').html(wording);
}

// --- substracts a certain number of fields from validation
//	   @params: number
function set_minus_fields(nr) {
    minus_fields = nr;
    validate_form('validate_form');
}
