/*
Script: feedburner_email.js
	Contains <FeedBurner>

Author:
	Alan Roemen
	August 16, 2010

Class: FeedBurner

Options:
	id: ID of the popup box. Default: 'fb-form'
	title: Title text in popup. Default: 'Sign up to have blog posts sent to your inbox.'
	subscribe_image: Submit image. Default: '/images/button_subscribe.gif'
	offset: Popup offsets. Default: {x: 0, y: 0}
*/

var FeedBurner = new Class({
	options: {
		'id': 'fb-form',
		'title': 'Sign up to have blog posts sent to your inbox.',
		'subscribe_image': '/images/button_subscribe.gif',
		'offset': {x: 0, y: 0}
	},

	initialize: function(selector, options) {
		this.links = $$(selector);
		if (this.links.length <= 0) return;
		this.setOptions(options);

		this.active = false;
		this.popup = {
			'active': false,
			'box': new Element('div', {'id': this.options.id}).adopt(this.build_box())
		}

		this.links.addEvent('click', this.open.bindWithEvent(this));
  },

	build_box: function() {
		return new Element('form', {
			'action': 'http://feedburner.google.com/fb/a/mailverify',
			'method': 'post',
			'target': 'popupwindow',
			'events': {'submit': this.submit.bindWithEvent(this)}
		}).adopt([
			new Element('p', {
				'class': this.options.id + '-title',
				'events': {'click': this.close.bind(this)}
			}).setHTML(this.options.title),
			new Element('div', {'class': this.options.id + '-container'}).adopt([
				new Element('label').setHTML('Email Address:'),
				new Element('input', {'type': 'text', 'name': 'email'}),
				new Element('input', {'type': 'hidden', 'value': '', 'name': 'uri'}),
				new Element('input', {'type': 'hidden', 'value': 'en_US', 'name': 'loc'}),
				new Element('input', {'type': 'image', 'src': this.options.subscribe_image})
			])
		]);
	},

	open: function(e) {
		e = new Event(e); e.stop();
		if (this.active !== false) { this.close(); return; }

		e.target = $(e.target);
		if (e.target.getTag() != 'a') e.target = e.target.getParent();
		
		this.active = {
			'link': e.target,
			'uri': e.target.getProperty('href').replace(/\#/g, '')
		}

		var cords = this.active.link.getCoordinates();
		this.popup.box.inject($$('body')[0]);
		this.popup.box.getElement('form').setProperty('class', this.active.uri);
		this.popup.box.getElement('input[name=uri]').setProperty('value', this.active.uri);
		this.popup.box.setStyles({
			'position': 'absolute',
			'top': cords.top.toInt() + this.options.offset.y.toInt(),
			'left': cords.left.toInt() + this.options.offset.x.toInt()
		});
	},

	submit: function(e) {
		window.open(
			'http://feedburner.google.com/fb/a/mailverify?uri=' + this.active.uri,
			'popupwindow',
			'scrollbars=yes, width=550, height=520'
		);
		this.close.delay(2000, this);
	},

	close: function() {
		this.active = false;
		this.popup.box.remove();
	}
});

FeedBurner.implement(new Events, new Options);
