
var FIDO2 = {
	_options: [],

	Widget: function(options) {
		this._options = options;
		qs = window.location.search;
		pos = qs.indexOf("sid=");
		if (pos != -1 && qs.length > 36) {
			options.sid = qs.substr(pos+4, 32);
			qs = qs.replace("sid=" + options.sid, "");
		}
		
		pos = qs.indexOf("id=");
		if (pos != -1 && qs.length > 39) {
			options.id = qs.substr(pos+3, 36);
		}
		
		if (options.type == 'signup') {
			return this.signup();
		}
		if (options.type == 'quicksignup') {
			return this.quicksignup();
		}

		return false;
	},

	signup: function() {
		var script = document.getElementById("FidoFormJS");
		this._options.uri = "http://" + this._options.client + ".fido-2.net/subscribers/signup";

		var qs = this._loadQueryString(['css', 'sid', 'email', 'id']);
		this._options.uri += (qs != '') ? "?" + qs : "";
		
		var iframe = this._createIframe();
		script.parentNode.replaceChild(iframe, script);		
	},

	quicksignup: function() {
		var script = document.getElementById("FidoFormJS");
		this._options.uri = "http://" + this._options.client + ".fido-2.net/subscribers/quicksignup";

		var qs = this._loadQueryString(['css', 'sid', 'email', 'id', 'publication_id']);
		this._options.uri += (qs != '') ? "?" + qs : "";
		
		var iframe = this._createIframe();
		script.parentNode.replaceChild(iframe, script);		
	},

	_loadQueryString: function(keys) {
		var params = [];
		for(i=0; i<keys.length; i++) {
			key = keys[i];
			if (this._options[key] && this._options[key] != '') {
				params.push(key + "=" + this._options[key]);
			}
		}
		return params.join("&");
	},

	_createIframe: function() {
		var iframe;
		try {
			// For brain-dead IE...
			iframe =
				document.createElement (
					'<iframe'
					+ " id='fidoIframe'"
					//+ " onload='FIDO.adjustHeight(iframe);'"
					+ " height='" + this._options.height + "'"
					+ " width='" + this._options.width + "'"
					+ " style='" + this._options.style + "'"
					+ " frameborder='0'"
					+ " scrolling='yes'"
					+ '>'
				);
		} catch (e) {
			iframe = document.createElement ('iframe');
			//iframe.onload = function() { FIDO.adjustHeight (iframe) };
			iframe.setAttribute ('id', 'fidoIframe');
			if (this._options.style && this._options.style != "") iframe.setAttribute ('style', this._options.style);
			iframe.setAttribute ('width', this._options.width + 'px');
			iframe.setAttribute ('height', this._options.height + 'px');
			iframe.setAttribute ('scrolling', 'no');
			iframe.setAttribute ('frameborder', '0');
		}
		iframe.setAttribute ('src', this._options.uri);
		return iframe;
	},

	_adjustHeight: function(iframe) {
		// Will only work if iframe source and parent are on same domain (protocol, subdomain.hostname, port)
		var height = iframe.contentWindow.document.body.scrollHeight;
		iframe.height = height;
	}
}

FIDO2.Widget(FidoOptions);


