/*
** JavaScript for NVJ
** Uses Mootools v1.11
** Build 20080619
*/

var NVJ = new Object;

// Some configuration
NVJ.Config = {
	"formFields" : {
		"email" : {
			"feedback"	: "Het e-mailadres is niet correct",
			"filter"	: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
		},
		"zip" : {
			"feedback"	: "De postcode is niet correct",
			"filter"	: /^([0-9]{4})(\s{1})?([a-zA-Z]{2})$/
		},
		"phone" : {
			"feedback"	: "Het telefoonnummer is niet correct",
			"filter"	: /^0([0-9]{9})$/
		},
		"date" : {
			"feedback"	: "Het datumveld is niet correct (dd-mm-jjjj)",
			"filter"	: /^\d{2}\-\d{2}\-\d{4}$/
		},
		"numeric" : {
			"feedback"	: "U dient hier alleen cijfers in te vullen",
			"filter"	: /^\d+$/
		},
		"license" : {
			"feedback"	: "Kenteken is niet correct",
			"filter"	: /^([0-9]|[A-Z]){2}\-?([0-9]|[A-Z]){2,3}\-?([0-9]|[A-Z]){2}$/i
		}
	},
	"errors" : {
		"postcode"		: "Postcode is niet correct",
 		"gebdat"		: "Geboortedatum is niet valide (dd-mm-jjjj)",
 		"rekeningnr"	: "Rekeningnummer mag alleen uit cijfers bestaan",
 		"kenteken"		: "Kenteken is niet correct"
	},
	"searchEngines" : {
		"nvj": {
			"name": "NVJ",
			"url": "",
			"returnValue": true
		},
		"freelancejournalist": {
			"name": "Freelancejournalist",
			"url": "http://www.defreelancejournalist.nl/?search=nvj&sel_medium=select&src_medium[0]=print&src_medium[1]=internet&src_medium[2]=radio&src_medium[3]=televisie&src_trefwoord=",
			"returnValue": false
		},
		"fotojournalist": {
			"name": "Fotojournalist",
			"url": "http://www.defotojournalist.nl/search.php?q=",
			"returnValue": false
		}
	}
};


// ----- ZOEKEN

NVJ.Zoeken = {
	machines: NVJ.Config.searchEngines,
	element: undefined,
	label: undefined,
	actief: undefined,
	items: $A(),
	submit: function(e){
		if (this.machines[this.actief].returnValue) return true;
		new Event(e).stop();
		var q = $('zoekveld').value;
		if (!q.length) return false;
		window.location.href = this.machines[this.actief].url + q;
	},
	swap: function(e,m,parent){
		if (e) new Event(e).stop();

		this.actief = m;
		Cookie.set('machine',m,{duration:365,path:'/'});
		$$('#zoeken .actief').removeClass('actief');
		parent.addClass('actief');
		this.label.setHTML('Zoeken in '+this.machines[m].name);
	},
	init: function(){
		this.element = $$('#zoeken form')[0];
		if (!this.element) return;
		this.label = this.element.getElement('label');
		this.element.addEvent('submit',this.submit.bindAsEventListener(this));
		this.actief = (Cookie.get('machine') != 'undefined' && Cookie.get('machine')) ? Cookie.get('machine') : 'nvj';
		
		var mach, par;
		var ul = new Element('ul').injectTop(this.element);

		for (var i in this.machines) {
			var a  = new Element('a',{'href':'#'+i}).appendText(this.machines[i].name);
			var li = new Element('li');
			li.injectInside(ul);
			a.injectInside(li);
			a.addEvent('click',this.swap.bindAsEventListener(this,[i,li]));
			if (i == this.actief) {
				mach = i;
				par = li;
			}
		}
		this.swap(false,mach,par);
		
	}
};


/*
-- FORM VALIDATION
---------------------------------------------------*/

NVJ.FormValidator = new Class({
 
 initialize : function(form) {
  this.form     = form;
  this.errors   = 0;
  this.isValid  = 0;
  
  this.missing  = $A();
  this.faulty   = $A();
  
  this.items    = NVJ.Config.formFields;
  this.disabled = false;
  this.errorClassName = 'fout';

  this.errorContainer = new Element('span',{'class':this.errorClassName});
 },
 
 cleanUp : function() {
  // reset errors
  this.errors = 0;

  // remove error message
  try { this.errorContainer.remove(); } catch (x) {}

  // set reset feedback arrays
  this.missing = $A();
  this.faulty  = $A();
  this.radio   = $H();
  
  // remove old classNames, remove feedback messages
  $ES('.'+this.errorClassName+', div.feedback',this.form).each(function(el){
    if (el.hasClass(this.errorClassName)) { el.removeClass(this.errorClassName); }
    if (el.hasClass('feedback')){ el.remove(); }
  },this);
 },
 
 showError : function() {
  // create error message
  var txt = "<span class='alert'>Let op!</span> Er %w %x veld%y niet goed ingevuld. "
          + "Controleer alle rode velden en verzend het formulier daarna nog een keer.";
  txt = txt.replace('%w', (this.errors == 1 ? 'is' : 'zijn'));
  txt = txt.replace('%x',  this.errors);
  txt = txt.replace('%y', (this.errors == 1 ? '' : 'en'));
  
  if (this.missing.length) {
   txt +=" Ontbrekende velden: "
       + this.missing.join(', ')
       + ". ";
  }
  if (this.faulty.length) {
   txt +='<div>'
       + this.faulty.join('<br />')
       + '</div>';
  }

  //$('validationerrors').appendChild(msg);
  
  // append msg to first el, fade from yellow
  this.errorContainer.injectAfter($('verstuur'));
  this.errorContainer.setHTML(txt);
 },
 
 // show feedback per input field
 showFeedback : function(node,txt) {
  var fb = new Element('span',{'class':'fout feedback'}).appendText(txt);
  var parent = node.getParent();
  var el = (parent.getTag() == 'label') ? parent : node;
  fb.injectAfter(el.getNext());
 },
 
 addMissing : function(node) {
  if (!node) return;
  var txt = node.title || node.name;
  this.missing.push(txt);
 }, 
 
 addFaulty : function(node,text) {
  if (!node) return;
  var txt = NVJ.Config.errors[node.name] || text;
  this.faulty.push(txt);
 },
 
 // validate form function
 validate : function() {
  //DEBUG
  //var time1 = new Date().getTime();
  this.cleanUp();
  
  // check each field in this form
  var fields = $ES('input, select, textarea', this.form);
  for (var i = 0; i < fields.length; i++) {
   // store in tmp var
   var F = $(fields[i]);
   
   // required checkbox check
   var missing_checkbox = (F.hasClass('required') && F.type == 'checkbox' && !F.checked) ? true : false;
   var missing_radiobut = (F.hasClass('required') && F.type == 'radio' && !F.checked) ? true : false;
   
   // required radiobuttons
   if (F.hasClass('require_one') && F.type == 'radio' && !this.radio.hasKey(F.name)) {
    var selector = 'input[name='+F.name+']';
    var isChecked = false;
    $ES(selector,this.form).each(function(el){
     if (el.checked) { isChecked = true; }
    });
    if (!isChecked) { missing_radiobut = true; }
    this.radio.set(F.name,true);
   }
   
   // required fields
   if ((F.hasClass('required') && F.value.length == 0) || missing_checkbox || missing_radiobut) {
    this.errors++;
    F.addClass(this.errorClassName);
    this.addMissing(F);
    var title = F.title || 'Dit veld';
    this.showFeedback(F,title+" mag niet leeg zijn"); // feedback for empty required fields
    continue;
   }

   // check field for types
   for (name in this.items) {
    var type = this.items[name];
    if (!F.hasClass('required') && F.value.length == 0) continue; // not required and empty? skip!
    if (F.hasClass(name) && !F.value.test(type.filter)) { // apply regexp filter
     this.errors++;                        // crank up error count
     F.addClass(this.errorClassName);      // add missing class
     this.showFeedback(F,type.feedback); // show feedback
     this.addFaulty(F,type.feedback); // add faulty
    } 
   }
  }

  // if we have errors, show error message
  if (this.errors > 0) {
   this.showError();
   this.isValid = 0;
   //DEBUG
   //var time2 = new Date().getTime();
   //alert(time2-time1);
   return false;
  } else {
   this.isValid = 1;// form validated!
   return true;
  }
 }
});



window.addEvent('domready',function(){
	$$('form.validate').each(function(el){
		var form = new NVJ.FormValidator(el);
		el.addEvent('submit',function(ev){
			if (!form.validate()) {new Event(ev).stop()}
		});
	});
	NVJ.Zoeken.init();
});
