Ext.define("Portfolio.ux.container.Iframe", {

	xtype: "portfolio-ux-container-iframe",

	alternateClassName: [
		"Ext.ux.container.Iframe"
	],

	extend: "Ext.panel.Panel",

	alias: [
		"widget.containeriframe",
		"widget.webcontainer"
	],

	config: {
		iframe: null,
		iframeId: "",
		src: ""
	},

	listeners: {
		afterrender: {
			fn: function(i_container) {

				var i_self = this;

				var i_iframe = i_self.getIframe();
				var s_url = i_self.getSrc();

				if (i_iframe.getEl()) {
					i_iframe.el.dom.src = s_url;
				}
			},
			single: true
		}
	},

	initComponent: function () {

		var i_self = this;

		i_self.callParent();
		var s_id = Ext.id(null, "iframe-");

		var i_component = Ext.widget("component", {
			id: s_id,
			xtype: "component",
			autoEl: {
				tag: "iframe",
				style: "height: 100%; width: 100%; border: none;"
			},
			listeners: {
				load: {
					element: "el",
					fn: function () {

						i_self.setLoading(false);

						var i_iframe = i_self.getIframe();
						var s_url = i_self.getSrc();

						var temp = document.createElement("a");

						temp.href = s_url;

						if (window.location.origin != temp.origin) {
							i_iframe.el.dom.contentWindow.postMessage(Ext.encode({
								id: i_self.getIframeId(),
								originated: window.location.origin
							}), temp.origin);
						}
					}
				},
				render: {
					fn: function () {
						i_self.setLoading(true);
					}
				}
			}
		});

		i_self.setIframe(i_component);
		i_self.setIframeId(s_id);

		i_self.add(i_component);

		i_self.initPostMessage();
	},

	updateSrc: function(s_url) {

		var i_self = this;

		if (i_self.rendered) {

			var i_iframe = i_self.getIframe();

			if (i_iframe.getEl()) {
				i_iframe.el.dom.src = s_url;
			}
		}
	},

	initPostMessage: function() {

		var i_self = this;

		Ext.getWin().on({
			message: {
				fn: function(i_event) {

					var i_browserEvent = i_event.browserEvent;

					var o_data = Ext.decode(i_browserEvent.data) || {};
					var i_frame = i_self.getIframe();

					if (i_frame && (o_data.id == i_self.getIframeId() || i_frame.id == o_data.id) ) {
						if (o_data.close) {
							i_self.close();
						}
						else {
							if (o_data.event) {
								i_self.fireEvent(o_data.event, i_self, o_data);
							}
						}
					}
				}
			}
		});
	}
});
