// form validation - it's pretty ugly
function validate_form(form)
{
  // verify empty function fields
  for(var i=0; i < form.elements.length; i++)
  {
    el = form.elements[i];
    if(el.hasClass('required') && el.value == el.title)
    {
      alert( 'Sorry, ' + el.title.substr(0, el.title.length - 2).capitalize() + ' is required.');
      el.focus();
      el.select();
      return false;
    }
  }
  
  // validate email address
  var email_re = /^(([^<>()[\]\\.,;:\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,}))$/
  if(!form.email.value.match(email_re))
  {
    alert('Invalid email address');
    form.email.focus();
    form.email.select();
    return false;
  }
  
  // reset default place holder values to empty if they are still set
  if(form.phone.value == form.phone.title)
    form.phone.value = '';
  if(form.message.value == form.message.title)
    form.message.value = '';
    
  // passed everything so submit the form
  form.submit();
  return false;
}

// portfolio image rotater
var Portfolio = {
  // initialize
  init: function(){
    // loop through the definition lists
    $ES('dl dt', 'main').each(function(el){
      // loop through all the links and add the events
      $ES('a', el).each(function(link){
        link.onclick = this.rotate.pass(link);
      }, this);
    }, this);
  },
  
  // change image
  rotate: function(link){
    var image = $E('img', link.parentNode);
    image.setAttribute('src', link.getAttribute('href'));
    return false;
  }
}
window.addEvent('domready', Portfolio.init.bind(Portfolio));

// accessible contact form
window.addEvent('domready', function(){
  form = $('contact-form');
  form.onsubmit = function(){ return validate_form(this); }
  
  // place labels as placeholder text
  for(var i=0; i<form.elements.length; i++)
  {
    el = form.elements[i];
    el.title = el.value;
    if(el.type != 'submit') {
      el.onfocus = function(){
        if(this.value==this.title) this.value = '';
      }
      el.onblur = function(){
        if(this.value=='') this.value = this.title;
      }
    }
  }
  
  // replace submit button with link
  var input = $E('p input', form);
  var link = new Element('a', {
    'href': 'javascript://',
    'events': {
      'click': function(){
        validate_form(form);
      }
    }
  });
  link.setText(input.value);
  input.replaceWith(link);
});