var TitleChanger = new Class({
  initialize: function() {
  	this.timer = null;
		this.sections = $$('div.section');
		this.loadTitles();
		this.start();
  },
	loadTitles: function() {
		this.sections.each(function(section) {
			section.pageTitle = section.getAttribute('title');
      section.removeAttribute('title');
		});
	},
	start: function() {
		this.timer = this.setTitle.periodical(20, this);
	},
	stop: function() {
		this.timer = $clear(this.timer);
	},
	setTitle: function() {
		document.title = this.getCurrentSection().pageTitle;
	},
	getCurrentSection: function() {
		var current = null;
    this.sections.each(function(section){
			if (window.getScrollTop() >= section.getTop() - Math.ceil(window.getHeight() / 2)) {
        current = section;
      }
		});
    return current;
	}
});

var ContactForm = new Class({
	initialize: function() {
		this.form = $('contact_form');
		this.submit_button = $('submit_button');
		this.message = null;
		if (this.form) {
			this.form.onsubmit = this.doForm.bindWithEvent(this);
			this.createMessageArea();
			//this.showMessageArea();
		}
	},
	createMessageArea: function() {
		this.message = new Element('div');
		this.message.addClass('alert');
		this.message.injectBefore(this.submit_button.getParent());
		this.message.innerHTML = '&nbsp;';
		this.message.oldMarginBottom = this.message.getStyle('margin-bottom');
		this.message.visible = false;
		this.message.colorChange = new Fx.Style(this.message, 'background-color', {duration:500});
		//alert(this.message.oldHeight);
		this.message.setStyles({
			'opacity'       : 0.0
		});
	},
	showMessageArea: function() {
		var marginChange = new Fx.Styles(this.message, {duration: 150, transition: Fx.Transitions.linear});
		marginChange.start({
			'opacity'       : 1.0
		});
		this.message.visible = true;
		this.message.state = true;
	},
	setMessage: function(message) {
		this.message.innerHTML = message;
		if (!this.message.visible) {
			this.showMessageArea();
		} else {
			if (this.message.state) {
				this.message.colorChange.start(new Color('#000'));
			} else {
				this.message.colorChange.start(new Color('#4c4c4c'));
			}
			this.message.state = !this.message.state;
		}
	},
	doForm: function(event) {
		var event = new Event(event);
		event.preventDefault();
		var errors = this.validate();
		if (errors.length > 0) {
			var message = '';
			errors.each(function(error) {
				message = message + error + ', '
			});
			this.setMessage('Whoops: <strong>' + message.substring(0, message.length - 2) + '</strong>');
		} else {
			this.setMessage('Sending message&#8230;');
			this.submit_button.disabled = true;
			obj = this;
			var myXHR = new XHR({
			  method: 'get',
			  onSuccess: function() {
			    obj.submit_button.disabled = false;
			    obj.setMessage('Message sent! Thanks!');
			    $('contact_name').value = '';
			    $('contact_email').value = '';
			    $('contact_message').value = '';
			  },
			  onFailure: function() {
			    obj.submit_button.disabled = false;
			    obj.setMessage('Doh! There was an error on the server. Try sending again please!');
			  }
			}).send('/send?name=' + $('contact_name').getValue() + '&email=' + $('contact_email').getValue() + '&message=' + $('contact_message').getValue() + '&ajax=true');
		}
	},
	validate: function() {
		var errors = new Array();
		if ($('contact_name').getValue().trim() == "") errors.push('name was left blank');
		if ($('contact_email').getValue().trim() == "") {
		  errors.push('email address was left blank');
		} else if(!/^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i.test($('contact_email').getValue())) {
		  errors.push('that doesn\'t look like a valid email address');
		}
		if ($('contact_message').getValue().trim() == "") errors.push('message was left blank');
		return errors;
	}
});

var NavScroller = new Class({
  initialize: function(title_changer) {
    this.changer = title_changer;
    this.loadLinks();
    this.attachEvents();
  },
  loadLinks: function() {
    this.links = $$('ul.navigation li a');
  },
  attachEvents: function() {
    this.links.each(function(link) {
      link.onclick = this.moveWindow.bindWithEvent(this);
    }, this)
  },
  moveWindow: function(event) {
    var event = new Event(event);
		event.preventDefault();
		var element = this.getElementFromLink(event.target);
		if (window.getScrollTop() != element.getTop()) {
		  if (window.getScrollTop() > element.getTop()) { // Up
		    var calc = function(e) { return (window.getScrollTop() - Math.ceil((window.getScrollTop() - e.getTop()) / 2));}
        var comp = function(e) { return (window.getScrollTop() <= e.getTop()); }
		  } else { // Down
		    var calc = function(e) { 
           if ((window.getScrollHeight() - window.getHeight()) < e.getTop()) {
             return (window.getScrollTop() + Math.ceil(Math.abs(((window.getScrollHeight() - window.getHeight()) - window.getScrollTop()) / 2)));
           } else {
             return (window.getScrollTop() + Math.ceil((e.getTop() - window.getScrollTop()) / 2));
           }
         }
         var comp = function(e) { 
           return (window.getScrollTop() >= e.getTop() || window.getScrollTop() >= (window.getScrollHeight() - window.getHeight())); 
         }
		  }
		  
		  var changer = this.changer;
		  changer.stop();
		  var timer = (function() {
		    window.scrollTo(0, calc(element));
		    if (comp(element)) {
		      $clear(timer);
		      changer.start();
		      if (!window.khtml) {
             window.location.hash = element.getAttribute('id');
           }
		    }
		  }).periodical(50);
		}
  },
	getElementFromLink: function(link) {
	  return $(link.getAttribute('href').replace(/#/, ''));
	}
});

window.addEvent('domready', function() {
	var changer = new TitleChanger();
	var form = new ContactForm();
	var scroller = new NavScroller(changer);
});
