var CtEmailToFriend_Element = Class.create(CtComponent_Abstract, {

	params: null,

	initialize: function(htmlElement) {
		this.reassembly(htmlElement);


		this.element = new Element('div');
		this.id = this.element.identify();
		$$('body')[0].appendChild(this.element);

		this.popup = new CtComponent_Popup();
		this.popup.element.appendChild(this.element);
		this.popup.closeCallback = function() {this.element.hide(); this.smoothClear();}.bind(this);

		CtPage.addComponent(this);
	},

	reassembly: function(htmlElement) {
		this.link = $(htmlElement);
		try	{
			this.link.observe('click', this.clickHandler.bindAsEventListener(this));
			this.url = this.link.readAttribute('href');
		} catch (e) {
			this.link.remove();
		}
	},

	clickHandler: function(event, element) {
		Event.stop(event);
		this.smoothClear(function() {

			this.popup.setLoader();
			var offset = this.link.cumulativeOffsetFixed();
			this.popup.move(offset[0], offset[1]);
			this.popup.show();

			var request = CtPage.getRequest(this.id, 'iframe');
			request.url = this.url;
			request.send();
		}.bind(this));

	},

	refresh: function(response) {
		this.element.show();

		if (!response.content) {
			this.popup.resetLoader();
			this.popup.hide();
			return;
		}

		this.element.update(new Element('div', {'class': 'ctForm'}));

		this.smoothUpdate(this.element.firstDescendant(), response.content, function() {
			this.popup.resetLoader();

			CtForm_Factory.refresh(this.element);
			var form = this.element.down('form');
			if (form) {
				CtPage.componentIsReady(form.identify(), function() {
					CtPage.getComponent(form.identify()).addProcessingFinishCallback(this.sendResponse.bind(this));
				}.bind(this));
			}
		}.bind(this));

	},


	sendResponse: function(response) {
		if (!this.element.down('form')) {
			this.popup.hide(2);
		}
	}


});

var CtEmailToFriend = Class.create(CtComponent_Abstract, {

	elements: {},

	initialize: function() {
		this.elements = {};
		this.reassembly();
	},

	reassembly: function() {

		var elements = $$('.ctEmailToFriend');
		for (var i = 0; i < elements.length; i++) {
			var ident = elements[i].identify();
			if (this.elements[ident]) {
				this.elements[ident].reassembly(elements[i]);
			} else {
				this.elements[ident] = new CtEmailToFriend_Element(elements[i]);
			}
		}
	}
});


CtPage.registerScript("CtEmailToFriend");
