Element.addMethods({
	
	getColor: function(element, hex) {
		var color = new RGBColor(element.getStyle('color'));
		if (hex) {
			color = color.toHex().toLowerCase();
		}
		return color;
	},
	
	getBackgroundColor: function(element, hex) {
		var color = new RGBColor(element.getStyle('background-color'));
		if (hex) {
			color = color.toHex().toLowerCase();
		}
		return color;
	}
	
});

Event.addBehavior({

	'body':function () {
		var links = $$('a');
		var ramp = {};
		var original_color = '#888888';
		var highlight_color = '#ffffff';

		links.invoke('observe', 'mouseover', function() {
			if (!this.hasClassName('current')) {
				this.setStyle({'color': '#555'});
				beginRamp(this, ramp, 20, 50, highlight_color);
			}
		});

		links.invoke('observe', 'mouseout', function() {
			if (!this.hasClassName('current')) {
				beginRamp(this, ramp, -40, 50, original_color);
			}
		});
	},

	'#secret_link':function () {
		$('updated_at').observe('dblclick', function() {
			$('secret_link').toggle();
		});
	},

	'a.video_choice:click':function () {
		$$('.video_choice').invoke('removeClassName', 'current');
		$$('.video').invoke('hide');
		$('video_'+this.id.split("_").last()).show();
		this.addClassName('current');

		return false;
	},

	'#nav a.current:click':function () {
		return false;
	},

	'#submit:click':function() {
		if ($F('sent') == 'true') {
			alert('your message has already been sent!');
			return false;
		} else {
			form = this.form;
			errors = validate($(form));
			if (errors) {
				var error_container = new Element('ul', {'id': 'error'});
				
				errors.each(function(e) {
					var error = new Element('li').update(e);
					error_container.insert({bottom: error});
				});
					
				if ($('error')) {
					$('error').replace(error_container);
				} else {
					$('wrapper').down('div').insert({top: error_container});
				}

				$$('.blackbox').first().scrollIntoView(true);
				return false;
			}
		}
	},

	'#newsletter_group:change': function() {
		var selected_region = $(this).getValue();
		var form_action = "http://lists.matthewschoening.com/mailman/subscribe/MatthewSchoening_" + selected_region;
		$(this).form.action = form_action;
	},
	
	'#signup_newsletter:click': function() {
		if ($F('newsletter_group').blank()) {
			alert('Please select a region!');
			return false;
		}
	}

});

function beginRamp(element, ramp, val, frequency, final_color)
{
	var key = element.identify();
	clearInterval(ramp[key]);
	ramp[key] = setInterval(function() { 
		var should_stop = rampColor(element, val, final_color);
		if (should_stop) {
			clearInterval(ramp[key]);
			element.setStyle({'color': final_color});
			delete(ramp[key]);
		}
	}, frequency);
}

function rampColor(el, val, dest) {
	var rgb = el.getColor();
	var dest_rgb = new RGBColor(dest);
	var dest_hex = parseInt(/[0-9a-f]+/i.exec(dest_rgb.toHex()), 16);

	var colors = function(color) {
		var colors = [];

		['r', 'g', 'b'].each(function(color) {
			colors.push((val < 0 && rgb[color] <= dest_rgb[color]) || (val > 0 && rgb[color] >= dest_rgb[color]) ? dest_rgb[color] : rgb[color] + val);
		});
		
		return colors;
	}()

	new_color = 'rgb(' + colors.join(',') + ')';
	el.setStyle({'color': new_color});
	var hex = parseInt(/[0-9a-f]+/i.exec(el.getColor(true)), 16);
	return val < 0 ? (hex <= dest_hex) : (hex >= dest_hex);
}

function validate(the_form) {
	var inputs = the_form.select('input', 'textarea');
	var errors = {};
	inputs.each(function(e){
		if (e.type != 'hidden' && e.type != 'submit') {
			var val = $F(e);
			var name = e.name.match(/\[(.*)\]/).last();
			
			if (e.name.match(/^required/)) {
				if (val.blank()) {
					errors[name] = 'blank';
				}
			}
			if (!errors[name] && (name == 'email' && !valid_email(val)) || 
									 	(name == 'phone' && !valid_phone(val))) {
				errors[name] = 'invalid';
			}

			if (errors[name]) {
				e.previous('label').addClassName('invalid');
			}
			else {
				e.previous('label').removeClassName('invalid');
			}

		}
	});
	return Object.keys(errors).length > 0 ? format_errors(errors) : false;
}

function format_errors(errors) {
	return Object.keys(errors).collect(function(e) {
		switch (errors[e]){
		case 'blank':
			return e + ' cannot be blank';
		case 'invalid':
			return e + ' is invalid';
		}
	});
}

function valid_email(email) {
	return /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i.test(email);
}

function valid_phone(phone) {
	return /^[()0-9\s\.\+\-x]*$/i.test(phone);
}
