// JavaScript for Champalimaud

function setCookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires ) {
        expires = expires * 1000;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name+'='+escape( value ) +
        ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
        ( ( path ) ? ';path=' + path : '' ) +
        ( ( domain ) ? ';domain=' + domain : '' ) +
        ( ( secure ) ? ';secure' : '' );
}


document.write('<link rel="stylesheet" href="/styles/js.css" type="text/css" media="screen" />');
//document.write('<link rel="stylesheet" href="/styles/cf-sIFR.css" type="text/css" media="all" />');
//document.write('<link rel="stylesheet" href="/styles/sIFR-screen.css" type="text/css" media="screen" />');
//document.write('<link rel="stylesheet" href="/styles/sIFR-print.css" type="text/css" media="print" />');

var CF   = new Object();
CF.inits = $A();

// ----- SUBMENU HELPER ---------------------------------------------------

CF.SubMenu = {
	element : undefined,
	init : function() {
		this.element = $('nav_categories');
		if (!this.element) return;
		var url = location.href;
		this.element.getElements('a').each(function(el){
			if (el.href != url) return;
			var li = el.getParent();
			li.addClass('active');
			
			// check for parent
			do {
				li = li.getParent();
				if (li.getTag() == 'li') {
					li.addClass('open');
					el.getParent().addClass('open');
				}
			} while (li != this.element)
			
			
			
		},this);
	}
}
CF.inits.push('SubMenu');

// ----- DROPDOWN CLASS ---------------------------------------------------

CF.DropDown = new Class({
 initialize : function(el) {
  this.element = el;
  this.title   = el.getElement('a');
  this.items   = el.getElement('ul');
  this.container = $('nav');

  // build div
  this.subMenu = new Element('div', {
   /*'styles' : {
    'min-width' : (this.element.getSize().size.x + 20)
   },*/
   'class':'dropdown'
  });
  
  new Element('li', {'class':'first'}).adopt(this.title.clone()).injectTop(this.items);
  this.items.injectInside(this.subMenu);
  
  this.element.addEvent('mouseenter',this.show.bind(this));
  this.subMenu.addEvent('mouseleave',this.hide.bind(this));
 },
 show : function() {
  var position = this.element.getPosition();
  this.subMenu.setStyles({
   'top'  : (position.y - 3),
   'left' : (position.x)
  });
  this.subMenu.injectInside(document.body);
 },
 hide : function() {
  this.subMenu.remove();
 }
});

CF.DropDowns = {
 init : function() {
  $('nav').getElement('ul').getChildren().each(function(el){
   if (el.getElement('ul')) {
    new CF.DropDown(el);
   }
  });
 }
}
CF.inits.push('DropDowns');


// ----- SEARCH NEWS BY MONTH ---------------------------------------------------

CF.NewsByMonth = {
 form : undefined,
 list : undefined,
 url  : undefined,
 jump : function() {
  if (!this.list.value) return;
  var year  = this.list.value.substring(0,4);
  var month = this.list.value.substring(4,6);
  window.location = this.url + year + '/' + month + '/';
 },
 init : function() {
  this.form = $('newsbymonth');
  this.list = $('date');
  if (!this.form || !this.list) return;
  this.url = this.form.getProperty('action');
  this.list.addEvent('change',this.jump.bind(this));
 }
}
CF.inits.push('NewsByMonth');


// ----- SEARCH NEWS BY CATEGORY ---------------------------------------------------

CF.NewsByCategory = {
 form : undefined,
 list : undefined,
 url  : undefined,
 jump : function() {
  if (!this.list.value) return;
  var category = this.list.value;
  window.location = this.url + 'category/' + category + '/';
 },
 init : function() {
  this.form = $('newsbycategory');
  this.list = $('category');
  if (!this.form || !this.list) return;
  this.url = this.form.getProperty('action');
  this.list.addEvent('change',this.jump.bind(this));
 }
}
CF.inits.push('NewsByCategory');


// ----- SHOW FILE INPUTS ---------------------------------------------------

CF.Form = {
 form : undefined,
 validator : undefined,
 list : undefined,
 addLink : undefined,
 maxFiles : 0,
 shown    : 0,
 addFile : function(e) {
  var ev = new Event(e);
  ev.preventDefault();
  var li = $E('li.hidden',this.list);
  if (li) {
   li.removeClass('hidden');
   this.shown++;
  }
  if (this.shown == this.maxFiles) {
   this.addLink.remove();
  }
 },
 checkForm : function(e) {
  var ev = new Event(e);
  if (this.validator.validate())
   return true;
  else
   ev.stop();
 },
 init : function() {
 
  if (this.form = $('nomination_form')) {  
   this.validator = new CF.FormValidator(this.form)
   this.form.addEvent('submit',this.checkForm.bindAsEventListener(this));
  }
 
 this.list = $('filelist');
  if (!this.list) return;
  
  this.maxFiles = $ES('li.hidden',this.list).length;
  
  this.addLink = new Element('a', {
   'href' : '#filelist',
   'events' : {
    'click' : this.addFile.bind(this)
   }
  }).appendText('Add another file');
  
  var span = $E('span.help',this.list);
  this.addLink.injectInside(span);
 }
}
CF.inits.push('Form');

// ----- ADD CLASSES TO LINKS --------------------------------------------

CF.Links = {
 types : ['pdf','doc','ppt','wmv','jpg','mov'],
 init : function() {
  $$('#content a').each(function(el){
   var ext = el.getProperty('href').split('.');
   var className = false;
   if (!(className = ext[(ext.length - 1)])) return;
   if (!this.types.contains(className)) return;
   el.addClass(className);
  },this);
 }
}
CF.inits.push('Links');

// ----- SIFR ------------------------------------------------------------

CF.Sifr = {
 init : function() {
 	if(typeof sIFR == "function") {
   // This is the preferred "named argument" syntax
   sIFR.replaceElement(named({sSelector:"h1", sFlashSrc:"/sifr/helvetica_h1.swf", sColor:"#FFFFFF", sLinkColor:"#000000", sBgColor:"#FB0000", sHoverColor:"#000000", sWmode: "opaque", nPaddingTop:0, nPaddingBottom:0}));
	};
 }
}
//CF.inits.push('Sifr');

// ----- COMMENT FORM ------------------------------------------------------------

CF.CommentForm = {
	form : undefined,
	validator : undefined,
	checkForm : function(e){
	  var ev = new Event(e);
	  if (this.validator.validate())
	   return true;
	  else
	   ev.stop();
	},
	init : function() {
		this.form = $('comment_form');
		if (!this.form) return;

	 	this.validator = new CF.FormValidator(this.form)
		this.form.addEvent('submit',this.checkForm.bindAsEventListener(this));
	}
}
CF.inits.push('CommentForm');

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

CF.FormValidator = new Class({
 
 initialize : function(form) {
  this.form     = form;
  this.errorContainer = $('errorcontainer');
  this.errors   = 0;
  this.isValid  = 0;
  
  this.missing  = $A();
  this.faulty   = $A();

  this.disabled = false;
  this.errorClassName = 'missing';
  this.markParent = true;
  
  this.items    = {
   "email" : {
    "feedback" : "Incorrect email address",
    "filter"   : /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
   },
   "zip" : {
    "feedback" : "Incorrect zip code",
    "filter"   : /^([0-9]{4})(\s{1})?([a-zA-Z]{2})$/
   },
   "phone" : {
    "feedback" : "Incorrect phone number",
    "filter"   : /^0([0-9]{9})$/
   },
   "numeric" : {
    "feedback" : "Please enter numbers only",
    "filter"   : /^\d+$/
   }
  };
 },
 
 cleanUp : function() {
  // reset errors
  this.errors = 0;
  
  // remove error message
  this.errorContainer.setHTML('');
  
  // set reset feedback arrays
  this.missing = $A();
  this.faulty  = $A();
  this.radio   = {};
  
  // 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 msg = new Element('p');
  var txt = "We found %x error%y in your submission. "
          + "Please check all the marked fields and try again.";
  txt = txt.replace('%x',  this.errors);
  txt = txt.replace('%y', (this.errors == 1 ? '' : 's'));
  
  this.errorContainer.appendChild(msg);
  
  // append msg to first el, fade from yellow
  msg.setHTML(txt);
 },
 
 // show feedback per input field
 showFeedback : function(node,txt) {
  var fb = new Element('div');
  fb.className = 'alert feedback';
  fb.appendChild(document.createTextNode(txt));
  node.parentNode.appendChild(fb);
 },
 
 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 = text;
  this.faulty.push(txt);
 },
 
 markAsError : function(node) {
  if (!node) return;
  if (this.markParent)
   node.getParent().addClass(this.errorClassName);
  else
   node.addClass(this.errorClassName);
 },
 
 // 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[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[F.name] = true;
   }
   
   // required fields
   if ((F.hasClass('required') && F.value.length == 0) || missing_checkbox || missing_radiobut) {
    this.errors++;
    this.markAsError(F);
    this.addMissing(F);
    //this.showFeedback(F,"Dit veld mag niet leeg zijn"); // feedback for empty required fields
    continue;
   }
   
   // check for confirm:other_id class names
   var confirm = false;
   if (confirm = F.className.match(/confirm:([\-_a-z0-9]+)/i)) {
    var other = $(confirm[1]);
    if (other && F.value != other.value) {
     this.errors++;
     this.markAsError(F);
     this.markAsError(other);
     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
     this.markAsError(F);                  // 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.disabled) {
   this.showError();
   this.isValid = 0;
   //DEBUG
   //var time2 = new Date().getTime();
   //alert(time2-time1);
   return false;
  } else {
   this.isValid = 1;// form validated!
   return true;
  }
 }
});



// ----- PROCESS INITS ---------------------------------------------------

CF.inits.each(function(method){
 window.addEvent('domready',CF[method].init.bind(CF[method]));
});


// tmp helper function

function show(tmp) {
 var out;
 for (var i in tmp) {
  out += i +': '+ tmp[i] +'\n';
  for (var j in tmp[i]) {
   out += '\t'+ j +': '+ tmp[i][j] +'\n';
  }
 }
 alert(out);
}
