var charsRemaining = {
	init: function(elementId, maxChars, responseId) {
		var ele = $(elementId);
		var response = $(responseId);
		if(ele && response) {
			this.changeValue(elementId, maxChars, responseId);
			ele.addEvent('keyup', function() {
				this.changeValue(elementId, maxChars, responseId);
				if(ele.value.length > maxChars) {
					ele.value = ele.value.substring(0, maxChars);
					alert('You have exceeded the ' + maxChars + ' character limit.');
				}
			}.bind(this));
		} else {
			alert(elementId + ' or ' + responseId + ' doesn\'t exist');
		}
	},
	changeValue: function(elementId, maxChars, responseId) {
		$(responseId).innerHTML = (maxChars - $(elementId).value.length);
	}
}

var fancifyButtons = {
	
	init: function(matchString) {
		$$(matchString).each(function(ele) {
			
			// hide the submit
			ele.style.top = '-1000px';
			ele.style.position = 'absolute';
			
			// create the new fancier one
			var newEle = new Element('span', {
				'class': 'gradientButton'
			});
			
			var newEleA = new Element('a', {
				'href': window.location,
				'text': ele.value
			});
			
			newEleA.addEvent('click', function(e) {
				var ev = new Event(e).stop();
				var p = this.getParent('form').submit();
			});
			
			newEleA.inject(newEle);
			newEle.inject(ele, 'after');
			
		});
	}
}

var tooltips = {

	init: function() {

		$$('a[rel=tooltips]').each(function(el) {
			el.rev = el.title;
			el.title = '';
		});	
		
		$$('a[rel=tooltips]').addEvents({
			'click': function(el) {
				var e = new Event(el).stop();
			},
			'mouseenter': function(el) {
				tooltips.triggerHover(this);
			},
			'mouseleave': function(el) {
				if($('tooltips')) {
					$('tooltips').destroy();
				}
			}
		});
	},
	triggerHover: function(el) {

		var newEle = new Element('div', {
			'id': 'tooltips',
			'class': 'tooltips',
			'text': el.rev, 
			'styles': {
				'top': el.getPosition().y,
				'left': el.getPosition().x + el.getSize().x + 2
			},
			'opacity': 0
		});
		
		newEle.inject(document.body);
		newEle.style.position = 'absolute';
		newEle.tween('opacity', 1);
	}
}

window.addEvent('domready', function() {
	$$('a[rel=external]').set('target', '_blank');
	fancifyButtons.init('input[class=fancify]');
	tooltips.init();
});

