// BOOM BOOM BOOM
if (!console) {
	var console = {
		log: function(str) {},
		info: function(str) {},
		debug: function(str) {},
		warn: function(str) {},
		err: function(str) {},
		end: true
	};
};
var debug = false;
if (!debug) { var debug = false; }

if (!opensocial) { var opensocial = {}; }
opensocial.Bizmo = function() {
	var os;
	var $ = jQuery;
	var req = opensocial.Container.get().newDataRequest();
	var osContainer = opensocial.Container.get();
	var val = '';

	var email_regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;


//	this.opensocial_domain = opensocial.Environment.getDomain();
	this.network_domain = "unknown";
	this.owner = {};
	this.viewer = {};
	this.os_token = null;
	this.is_installed = false;
	this.domain = "";
	this.container_name = "unknown";
	this.owner_bizmo_id = false;
	this.linked_bizmo_id = false;
	this.show_demo_swf = false;
	this.editMode = false;
	this.isNetworkApp = false;
	this.flash_container_id = 'flash-container-inner';

	/**
	 * Get jQuery elements once and cache them
	 */
	this.el = {};

	this.objectIsEmpty = function(ob) {
		for (var prop in ob) {
			if (ob.hasOwnProperty(prop)) return false;
		}
		return true;
	};
	this.getDataRequest = function() {
		return opensocial.Container.get().newDataRequest();
	};
	this.getSwf = function(movieName) {
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return window[movieName];
		} else {
			return document[movieName];
		}
	};
	this.send_to_flash = function (value) {
		this.getSwf("demo1").send_to_flash(value);
	};

	this.new_event = function(event) {
		if (debug) console.log("Recieved event:");
		if (debug) console.debug(event);
		if (debug) console.debug(this);
		switch(event.type) {
			case 'itemPurchased':
				this.post_purchase(event);
				break;
			default:
				this.post_activity(event.text);
				break;
		}
		this.send_to_flash("OK, got " + event.type + " event\n");
	};

	this.post_purchase = function(event) {
		if (debug) console.log("post_purchase:");
// 		if (debug) console.debug(this.viewer);
		/**
		* Purchase event object looks like this:
		*/
		// type: "itemPurchased"
		// mediatype: i.e. "Video”
		// mediatitle: i.e. "Remind Me (Royksopp)
		// mediaid: i.e. "123456"
		var params = {};

		/**
			* We want to generate this type of text:
			*/
		// "Andy Schleck has purchased the video Remind Me (Royksopp) from Carlos Sastre"?
		var title = this.viewer.getDisplayName() + " bought the " + event.mediatype  + " <i>" + event.mediatitle + "</i>";
		if (!this.viewer.isOwner()) {
			title += " from " + this.owner.getDisplayName() + "";
		}
		title += '.';

		if (this.container_name == 'MySpace') {
			if (debug) console.info("MySpace doesn't support posting to activity stream in OpenSocial 0.7");
			return false;
		}

		if (this.container_name == "MySpace") {

			if (debug) console.info("Using MySpace Activity Stream");
			params[opensocial.Activity.Field.TITLE_ID] = "Test_Template1";
			params[opensocial.Activity.Field.TEMPLATE_PARAMS] = {"text": event.mediatype  + " <i>" + event.mediatitle + "</i>"};

			var mediaItemArray = [];
			params[opensocial.Activity.Field.MEDIA_ITEMS] = mediaItemArray;

		} else {

			/**
			* Set title on Activity item
			*/
			params[opensocial.Activity.Field.TITLE] = title;
			if (debug) console.log("Set activity title " + title);
		}

		/**
		* Create and post activity
		*/
		var activity = opensocial.newActivity(params);
		if (debug) console.log("Posting activity:");
		if (debug) console.debug(activity);
		opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, this.activity_callback);
	};

	this.activity_callback = function(response) {
		if (debug) console.log("activity_callback");
		if (debug) console.debug(response);
		if (result.hadError()) {
			if (debug) console.warn("Error: " + response.getErrorMessage());
		}
	};

	this.post_activity = function(text) {
		var title = this.viewer.getDisplayName() + " said '" + text + "'";
		if (!this.viewer.isOwner()) {
			title += " using " + this.owner.getDisplayName() + "'s thebizmo";
		}
		if (this.container_name == 'MySpace') {
			if (debug) console.info("MySpace doesn't support posting to activity stream in OpenSocial 0.7");
			return false;
		}
// 				var supported = osContainer.getMySpaceEnvironment().getSupportedPostToTargets();
// // 				var target = MyOpenSpace.PostTo.Targets.PROFILE;
// 				var target = MyOpenSpace.PostTo.Targets.BULLETINS;
// 				var message = opensocial.newMessage(title);
// 				message.setField(opensocial.Message.Field.TITLE, title);
// 				message.setField(opensocial.Message.Field.TYPE, target);
// 				if (debug) console.info("Using MySpace postTo(), message: ");
// 				if (debug) console.log(message);
// 				osContainer.postTo(os_token, message, viewer);
		if (debug) console.log("Posting Activity, Title is " + title);
		var params = {};
		params[opensocial.Activity.Field.TITLE] = title;
		var activity = opensocial.newActivity(params);
		opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() { });
	};

	this.uiDrawMainPanel = function(bizmo_id) {

		if (bizmo_id == 'undefined') {
			bizmo_id = null;
		}

		if (debug) console.log("uiDrawMainPanel, bizmo_id is " + bizmo_id);

		/**
			* Url for bizmo SWF
			*/
		var swfUrl = 'http://' + (use_staging ? 'stage' : 'www') + '.thebizmo.com/flash/bizmo.swf';
		swfUrl += '?topbanner=true&thirdparty=true&thirdpartyname=' + this.container_name + '&u=' + bizmo_id;

		/**
			* Flash embed parameters
			*/
		var params = {
			height: "425",
			width: "420",
			quality: 'high',
			allowScriptAccess: 'always',
			allowNetworking: 'all'
		};
		var flash_vars = {
			topbanner: 'true',
			thirdparty: 'true',
			thirdpartyname: this.container_name,
			u: bizmo_id
		};
		var flash_version_target = "7.0.0";

		var embed_method = 'swfobject15';
		if (!bizmo_id) {
			embed_method = "none";
		}

		/**
		* Use Google Flash util to embed into the #flash-container element
		* 2008-10-27 IN - Not supported by MySpace
		*/
		if (embed_method == 'gadgets') {
			gadgets.flash.embedFlash(swfUrl, this.flash_container_id, flash_version_target, params);
		}

		/**
		* SWFObject 2.1
			* 2008-10-27 IN - Doesn't work in FF3!
		*/
		if (embed_method == 'swfobject2') {
			var attributes = {};
// 			swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);
			swfobject.embedSWF(swfUrl, this.flash_container_id, params.width, params.height, flash_version_target, "expressInstall.swf", flash_vars, params, attributes);
		}

		/**
		* SWFObject 1.5
		* 2008-10-27 IN - Seems to be the Lowest Common denominator
		*/
		if (embed_method == 'swfobject15') {
			if (debug) console.log("uiDrawMainPanel, showing flash " + swfUrl  + " with swfobject15 in #" + this.flash_container_id);
			if (debug) console.debug(params);
			var so = new SWFObject(swfUrl, "bizmo", params.width, params.height, flash_version_target);
			for (var k in flash_vars) {
				so.addVariable(k, flash_vars[k]);
			}
			for (var p in params) {
				so.addParam(p, params[p]);
			}
			so.write(this.flash_container_id);
		}

		if (bizmo_id && this.owner.isViewer()) {
			/**
			 * Set form input value
			 */
			this.el.bizmo_id_input.val(bizmo_id);
		}

		if (this.show_demo_swf) {
// 			var demo_swfUrl = 'http://dev.thebizmo.com/3papps/opensocial/demo1.swf?topbanner=true&u=' + bizmo_id;
			var demo_swfUrl = 'http://bizmoning.dynamitehq.com/opensocial/demo1.swf';
			var demo_params = {
				height: 190,
				width: 420,
				quality: 'high',
				allowScriptAccess: 'always',
				allowNetworking: 'all'
			};
			var demo_flash_vars = {};

			if (embed_method == 'swfobject15') {
				var dso = new SWFObject(demo_swfUrl, "bizmo_demo", demo_params.width, demo_params.height, flash_version_target);
				for (var k in demo_flash_vars) {
					dso.addVariable(k, demo_flash_vars[k]);
				}
				for (var p in demo_params) {
					dso.addParam(p, demo_params[p]);
				}
				dso.write('demo_flash-container');
			}
		}

		try {
			gadgets.window.adjustHeight();
		} catch (e) {}
	};

	this.verifyBizmoId = function(candidate, callback) {
		var verify_url = "http://www.thebizmo.com/3papps/checkmem.php?id=" + candidate + "&r=" + Math.random(); //324232344
		if (debug) console.log("Verifying Bizmo ID via " + verify_url + ": ");
		var params = {};

		this.el.settings_save_button.hide();
		// this.el.save_loading.css("display", "inline");

		gadgets.io.makeRequest(verify_url, function(resp) {
			callback(candidate, resp);
		}, params);
	};

	this.onVerifyBizmoIdResponse = function(bizmo_id, resp) {
		if (debug) console.log("onVerifyBizmoIdResponse resp:");
		if (debug) console.log(resp);
		var app = this.bizmo;
		// app.el.save_loading.css("display", "none");
		app.el.settings_save_button.show();

		if (resp.hasOwnProperty('errorCode')) {
			// handle error
			app.el.flash_container_inner.html("<p>Oops, we had a problem talking to thebizmo server.<br/>Please try again in a minute.</p>");
			app.el.desc_container.css("width", "370px");
			app.el.flash_container.show();
			return;
		}
		var bad_id = resp.text == "0";
		if (bad_id) {
			app.el.flash_container_inner.html("<p>Oops, we couldn't find a valid bizmo with ID <em>" + bizmo_id + "</em>.<br/>Please check your bizmo ID and try again.</p>");
			app.el.desc_container.css("width", "370px");
			app.el.flash_container.show();
			return;
		}

		app.storeBizmoId(bizmo_id);
		app.updateBizmoId(bizmo_id);

	};

	this.uiToggleSettings = function() {
		this.el.settings.toggle();
		try {
			gadgets.window.adjustHeight();
		} catch (e) {}
	};

	this.onSetBizmoId = function(resp) {
		if (debug) console.log("onSetBizmoId, response is: ");
		if (debug) console.log(resp);
// 			if (debug) console.log(resp.get("set_data"));
		if (resp.hadError()) {
			/* The update failed ... insert code to handle the error */
			console.warn("set error: " + resp.get("set_data").getErrorMessage());
			//this.el.debug_container.append(resp.get("set_data").getErrorMessage());
		} else {
			/* The update was successful ... continue execution */
// 				alert("The update was successful ... continue execution");
		}
	};

	this.formValidates = function() {
		var values = {
			nickname: $('#nickname').val(),
			password: $('#password').val(),
			password_verify: $('#password_verify').val(),
			email: $('#email').val(),
			email_verify: $('#email_verify').val(),
			accept_terms: $('#accept_terms').is(':checked') ? 1 : 0
		};
		if (debug) console.log("formValidates");
		if (debug) console.debug(values);

		result = {
			values: values,
			errors: { }
		};

		/**
		* Form validation
		*/
		if (values.nickname.length < 6) {
			result.errors.nickname = error_strings.nickname_too_short;
		}
		if (values.password.length < 6) {
			result.errors.password = error_strings.password_too_short;
		}
		if (values.password != values.password_verify) {
			result.errors.password_verify = error_strings.password_no_match;
		}
		if (values.email == '') {
			result.errors.email = error_strings.email_required;
		}
		if (values.email != values.email_verify) {
			result.errors.email_verify = error_strings.email_no_match;
		}
		if (!email_regex.test(values.email)) {
			result.errors.email = error_strings.email_required;
		}
		if (values.accept_terms != 1) {
			result.errors.accept_terms = error_strings.accept_terms_required;
		}

		return result;
	};

	this.updateBizmoId = function(bizmo_id) {
		if (debug) console.log("Bizmo updateBizmoId");
		this.uiToggleSettings();
		if (this.owner.isViewer()) {
			this.uiDrawMainPanel(bizmo_id);
		}
	};

		this.submitForm = function() {

			if (debug) console.log("submitForm");
			if (!this.owner.isViewer()) {
				/**
				 * Not allowed, sorry
				 */
// 				if (debug) console.log("Viewer is not owner, cannot save settings");
// 				return;
			}
			var bizmo_id = this.el.bizmo_id_input.val();
			req = this.getDataRequest();

			if (bizmo_id) {
				this.verifyBizmoId(bizmo_id, this.onVerifyBizmoIdResponse);

				//this.storeBizmoId(bizmo_id);
				//this.updateBizmoId(bizmo_id);
				return;
			}
			var result = this.formValidates();
			// This line breaks Safari
// 			if (debug) console.debug(result);

			/**
			* Set up or clear error messages
			*/
			var has_errors = false;
			for (var key in result.values) {
				var row = $('.input_row.' + key);
				if (key == 'isEmpty') continue;
				if (result.errors[key]) {
					has_errors = true;
					if (debug) console.log(key + " has an error: " + result.errors[key]);
					row.addClass('error');
// 					$('.error', row).html(result.errors[key]);
// 					$('.error', row).show();
				} else {
					if (debug) console.log(key + " has no error");
					row.removeClass('error');
// 					$('.error', row).hide();
				}
			}

			if (has_errors) {
				return;
			}

			/**
			 * Send request
			 */
// 			me.sendBizmoApiRequest('signup', {
// 				nickname: result.values.nickname,
// 				email: result.values.email,
// 				password: result.values.password
// 			}, me.onSignupResponse);
			this.sendBizmoApiRequest('signup', {
				username: result.values.nickname,
				email: result.values.email,
				password: result.values.password
			}, this.onSignupResponse);
		};

		this.onSignupResponse = function(resp) {
			// NOT IMPLEMENTED IN CURRENT VERSION
			if (debug) console.debug(resp);
			if (resp["errors"] && resp["errors"][0]) {
				$('#error_message').html("<p>" + resp["errors"][0] + "</p>");
				return;
			}
			if (resp["errorMessage"]) {
				$('#error_message').html("<p>" + resp["errorMessage"] + "</p>");
				return;
			}
			var success = resp.data.getElementsByTagName("success")[0].firstChild.nodeValue == "true";
			var message = resp.data.getElementsByTagName("message")[0].childNodes[0].nodeValue;
			if (debug) console.log("onSignupResponse");

			var app = this.bizmo;

			if (success) {
				if (app.owner.isViewer()) {
					app.is_installed = true;
				}
				if (debug) console.log("Signup succeeded");
				var bizmo_id = resp.data.getElementsByTagName("bizmoid")[0].childNodes[0].nodeValue;

				app.storeBizmoId(bizmo_id);
// 				if (!is_installed) {
// // 					$('#sign-up').html("<p>Thank you for using thebizmo 360 microstore</p><p>To finish setting up thebizmo on your profile page, click on the Add Application in <a href=\"" + about_url + "\ target=\"_top\">the about page</a>.</p><p>thebizmo team</p>");
// 					$('#sign-up').html("<p>Thank you for using thebizmo 360 microstore</p><p>To finish setting up thebizmo on your profile page, click on the Add Application in the about page.</p><p>thebizmo team</p>");
// 					return;
// 				};

				if (app.el["app_intro"]) {
					app.el.app_intro.hide();
				}
				if (app.el["installed_bizmo_id"]) {
					app.el.installed_bizmo_id.text(bizmo_id);
				}
				if (app.el["app_installed"]) {
					app.el.app_installed.show();
				}
				if ($('#sign-up-form')[0]) {
					$('#sign-up-form').hide();
				}
				app.uiToggleSettings();

				if (!app.owner.isViewer()) {
					// Redirect somewhere?
				} else {
					app.uiDrawMainPanel(bizmo_id);
				}
				$('#error_message').html("");
				try {
					gadgets.window.adjustHeight();
				} catch (e) {}
				return;
			}
			if (debug) console.log("Signup failed");
			$('#error_message').html("<p>Oops: " + message + "</p>");
			try {
				gadgets.window.adjustHeight();
			} catch (e) {}
// 			alert(message);
		};

		this.sendBizmoApiRequest = function(method_name, params, callback) {

// 			params['isXMLRequest'] = 1;
// 			params['xmloff'] = 0;
			params['noOutput'] = 1;
			var module = 'Bizmo::Gui::Plugin::3rdPartyMember';
			if (method_name == 'signup') {
				method_name = 'register';
				module = 'Bizmo::Gui::User::Profile';
			}

			if (module == 'Bizmo::Gui::Plugin::3rdPartyMember') {
				params['thirdParty'] = params['thirdParty'] || this.container_name;
				params['thirdPartyId'] = params['thirdPartyId'] || this.viewer.getId();
			}

			/**
			 * Build XML
			 */
			var xml = '<'+'?xml version="1.0" encoding="UTF-8"?'+'><xml><module>' + module + '</module>';
			xml += '<method>' + method_name + '</method>';
			xml += "<params>\n";
			/**
			 * TODO: need to escape XML entities!
			 */
			for (var key in params) {
				if (key == 'isEmpty') continue;
				xml += '<' + key.replace( '3', 'thi')  + '>' + params[key] + '</' + key + '>';
			}
			xml += "</params>\n";
                        xml += '</xml>';

			/**
			 * Set up Request object
			 */
			var params = {};
// 			bizmo_api_endpoint += "?xmloff=0";
                        bizmo_api_endpoint = 'http://www.thebizmo.com/3papps/xml-rpc/index.php';
			if (debug) console.log("Sending XML to " + bizmo_api_endpoint + ": ");
			if (debug) console.log(xml);
			params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
			params[gadgets.io.RequestParameters.POST_DATA] = xml;
			params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
			params[gadgets.io.RequestParameters.HEADERS] = {
				"Content-Type": "text/xml"
			};
			gadgets.io.makeRequest(bizmo_api_endpoint, callback, params);
		};

		this.getLinkedBizmoId = function(local_id, callback) {
			this.sendBizmoApiRequest('getBizmoId', {
				"thirdPartyId": local_id
			}, callback);
		};

		this.onGetLinkedBizmoIdResponse = function(resp) {
			if (debug) console.log("onGetLinkedBizmoIdResponse resp:");
			if (debug) console.debug(resp);
 			var result = false;
			var message = "";
			var bizmo_id = null;

			var tmp = resp.data.getElementsByTagName('success');
			if (tmp && tmp.length > 0) {
				result = tmp[0].firstChild.nodeValue == "true";
			}
			if (result) {
				tmp = resp.data.getElementsByTagName('bizmoId');
				if (tmp && tmp.length > 0) {
					bizmo_id = tmp[0].firstChild.nodeValue;
				}
			} else {
				tmp = resp.data.getElementsByTagName('message');
				if (tmp && tmp.length > 0) {
					message = tmp[0].firstChild.nodeValue;
				}
			}
 			if (debug) console.log("result: " + result + " message: " + message + ", bizmo_id: " + bizmo_id);

			this.linked_bizmo_id = bizmo_id; //resp.data.firstChild.firstChild.nextSibling.firstChild.nodeValue;
			if (!result || this.linked_bizmo_id == "this Ning thirdParty relation does not exists") {
				this.linked_bizmo_id = null;
				this.owner_bizmo_id = null;
				return;
			}
			// Force owner_bizmo_id value to match to affect ultimate override
			this.owner_bizmo_id = this.linked_bizmo_id;
			if (debug) console.log("got linked_bizmo_id: " + this.linked_bizmo_id);
		};

		this.storeBizmoId = function(bizmo_id) {
			/**
			 * Set the bizmo_id using container's persistent storage
			 */
// 			if (this.is_installed) {
				if (debug) console.log("1) Storing bizmo id via OS Container " + bizmo_id);
// 				// only "VIEWER" works on MySpace
				req.add(req.newUpdatePersonAppDataRequest(this.getIdSpec("VIEWER"), "bizmo_id", bizmo_id), "set_data");
				req.send(this.onSetBizmoId);
// 			} else {
// 				if (debug) console.log("1) NOT Storing bizmo id via OS Container (app is not installed): " + bizmo_id);
// 			}

			/**
			 * Send request
			 */
			if (debug) console.log("2) storing bizmo id via bizmo API " + bizmo_id);

			var local_id = this.owner.getId();
			if (this.isNetworkApp) {
				local_id = this.network_domain;
			}
			this.sendBizmoApiRequest('add', {
				"thirdPartyId": local_id,
				bizmoId: bizmo_id
			}, this.onStoreBizmoIdResponse);

		};

		this.onStoreBizmoIdResponse = function(resp) {
// 			if (debug) console.log("onStoreBizmoIdResponse resp:");
// 			if (debug) console.log(resp);
		};

		this.onSetInstalledResponse = function(resp) {
// 			if (debug) console.log("onSetInstalledResponse resp:");
// 			if (debug) console.log(resp);
		};

		this.onGetBizmoIdFromBizmo = function(resp) {
			var success = false;
			var message = "";
			var bizmo_id = null;

			var tmp = resp.data.getElementsByTagName('success');
			if (tmp && tmp.length > 0) {
				success = tmp[0].firstChild.nodeValue == "true";
			}
			if (success) {
				tmp = resp.data.getElementsByTagName('bizmoId');
				if (tmp && tmp.length > 0) {
					bizmo_id = tmp[0].firstChild.nodeValue;
				}
			} else {
				tmp = resp.data.getElementsByTagName('message');
				if (tmp && tmp.length > 0) {
					message = tmp[0].firstChild.nodeValue;
				}
			}
 			if (debug) console.log("success: " + success + " message: " + message + ", bizmo_id: " + bizmo_id);
			if (debug) console.log("onGetBizmoIdFromBizmo bizmo_id: " + bizmo_id);
			if (success && bizmo_id && owner.isViewer() && !is_installed) {
				/**
				 * This is a new installation, no bizmo_id in OS container
				 */
				is_installed = true;
				if (debug) console.log("Setting bizmo_id (from API) to: " + bizmo_id);
				me.uiToggleSettings();
				me.storeBizmoId(bizmo_id);
				me.render(bizmo_id);
			}
		};

		/**
		 * Main render function
		 * Defaults to "profile" view - override in subclasses for different views/surfaces
		 */
		this.render = function() {

			if (owner.isViewer()) {
				if (owner_bizmo_id) {
					$('#sign-up-form').hide();
				} else {
					el.settings.show();
					$('#sign-up-form').show();
				}
			}

			/**
			 * Show settings links
			 */
// 			el.settings_links.show();

			/**
			 * Listen for save button click
			 */
			el.settings_save_button.click(function() {
				if (debug) console.log("settings_save_button clicked");
				this.submitForm();
				return false;
			});

			/**
			 * On toggle click, toggle settings visibility
			 */
// 			el.settings_toggle.click(function() {
// 				me.uiToggleSettings();
// 			});

			if (owner_bizmo_id) {

				// Show bizmo
				this.uiDrawMainPanel(owner_bizmo_id);

			} else {

				if (owner.isViewer()) {
// 					el.settings.show();
// 					el.content.html("<p>Hmmm, looks like we couldn't find you yet.  You should add your Bizmo ID in the settings.</p>");
				} else {
					/**
					 * Just show default bizmo to non-owner
					 */
					if (debug) console.log("showing ui panel with default bizmo id: " + default_bizmo_id);
					this.uiDrawMainPanel(default_bizmo_id);
				}
			}
			try {
				gadgets.window.adjustHeight();
			} catch (e) {}

		};

		this.onInitDataRecieved = function(resp) {

			var app = self.bizmo;

			/**
			 * Owner data
			 */
			app.owner = resp.get("owner").getData();
			var owner_id = false;
			if (app.owner != null) {
				owner_id = app.owner.getId();
			} else {
				// We don't have any Owner data
				if (debug) console.info("No Owner data, is app installed?");
				$('#app-installed').hide();
				$('#app-not-installed').show();

				try {
					gadgets.window.adjustHeight();
				} catch (e) {}

// 				el.flash_container.html("<p>Sorry, I couldn't get any data for the app owner</p>");
				//app.el.flash_container.html("<p>To add thebizmo app, simply click the \"Add App\" link above the navigation bar to the left.</p>");
				return;
			}
			if (debug) console.log("owner: ");
			if (debug) console.log(app.owner);

			/**
			 * Viewer data
			 */
			app.viewer = resp.get("viewer").getData();
			var viewer_id = false;
			if (app.viewer != null) {
				viewer_id = app.viewer.getId();
			} else {
				// We don't have any Viewer, perhaps
				// because the App isn't installed
				if (debug) console.info("No Viewer data, is app installed?");
// 				el.flash_container.html("<p>Sorry, I couldn't get any data about you, the viewer</p>");
// 				return;
			}
			if (debug) console.log("viewer: ");
			if (debug) console.log(app.viewer);

			var owner_data = resp.get("owner_data").getData();
			if (debug) console.log("owner_data: ");
			if (debug) console.log(owner_data);

			app.owner_bizmo_id = false;
			if (owner_data && owner_data[owner_id]) {
				app.owner_bizmo_id = owner_data[owner_id]["bizmo_id"];
			};
			if (debug) console.log("Got owner_bizmo_id: " + app.owner_bizmo_id);

			var viewer_data = resp.get("viewer_data").getData();
			if (debug) console.log("viewer_data: ");
			if (debug) console.log(viewer_data);

			app.is_installed = false;
			if (viewer_data && viewer_data[viewer_id]) {
				app.is_installed = viewer_data[viewer_id]["is_installed"];
			};

			/**
			 * Set is_installed flag
			 */
			if (app.viewer != null && app.viewer.isOwner() && !app.is_installed) {
				req = app.getDataRequest();
				req.add(req.newUpdatePersonAppDataRequest(app.getIdSpec("VIEWER"), "is_installed", true), "set_data");
				req.send(app.onSetInstalledResponse);
				app.is_installed = true;
			}

			if (debug) console.log("is_installed: " + (app.is_installed ? 'Yes' : 'No'));

			if (app.owner.isViewer()) {
				app.editMode = true;
			} else {
				app.editMode = false;
			}

			// 'is_network_app' is set externally in the init.js View
			app.isNetworkApp = is_network_app || false; // gadgets.util.hasFeature("ning") && app.owner.getField("ning.creator");

			if (app.isNetworkApp) {
				// send another HTTP request to get the bizmo id for the NETWORK itself
				// 2009-06-03 IN - Tweak as per Ning request; get Info will return useful IDs for the current network
				ning.app.getInfo(function(result) {
					app.onGetInfoResult(result, app);
				});

			} else {
				app.render();
			}

		};

		this.getDomElements = function() {
			return {
		// 		content: $("#main-content"),
				bizmo_id_input: $("#bizmo_id"),
				settings: $("#settings"),
				settings_links: $("#settings-links"),
				settings_toggle: $("#settings-toggle"),
				settings_save_button: $("#settings-save"),
				save_loading: $("#save-loading"),
				debug_container: $("#debug-container"),
				desc_container: $("#desc-container"),
				flash_container: $("#flash-container"),
				flash_container_inner: $("#flash-container-inner")
			};
		};

		this.getIdSpec = function(str) {
			var spec = str;
			if (opensocial_version == 0.8) {
				spec = opensocial.newIdSpec({ "userId" : spec, "groupId" : "SELF" });
			}
			return spec;
		};

		this.init = function() {

			var app = self.bizmo;

			app.el = app.getDomElements();

			app.domain = opensocial.getEnvironment().getDomain();
			var domain_container_map = {
				Ning: /ning\.com$/i,
				MySpace: /myspace\.com$/i,
				Unknown: /.*/i
			};

			for (var key in domain_container_map) {
				var re = domain_container_map[key];
				if (re.test(app.domain)) {
					app.container_name = key;
					break;
				}
			}
			if (debug) console.info("Initialising thebizmo OpenSocial App, Container: " + app.domain + ' / ' + app.container_name);

			if (app.container_name == 'MySpace') {
				app.os_token = MyOpenSpace.MySpaceContainer.OSToken;
			}

			try {
				if (app.container_name == "Ning" && gadgets.util.hasFeature("ning") && ning) {
// 					app.network_domain = ning.core.getNetworkDomain();
					// 2009-06-03 IN - Tweak as per Ning request; get Info will return useful IDs for the current network
// 					ning.app.getInfo(app.onGetInfoResult);
				}
			} catch (e) {
				if (debug) {
					console.error(e.name + " - Cannot get Ning network domain: " + e.message);
					console.debug(e);
				}
			}
			/**
			 * Get Owner and Owner's Bizmo ID
			 */
			req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), "owner");
			req.add(req.newFetchPersonAppDataRequest(app.getIdSpec("OWNER"), "bizmo_id"), "owner_data");
			/**
			 * Get Viewer and Viewer's Bizmo ID
			 */
			req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), "viewer");
			req.add(req.newFetchPersonAppDataRequest(app.getIdSpec("VIEWER"), ["bizmo_id", "is_installed"]), "viewer_data");

			req.send(app.onInitDataRecieved);
		};

		this.onGetInfoResult = function(result, app) {
			if (result.hadError()) {
				if (debug) console.error("Error found!");
			} else {
				if (debug) console.info("Network ID: " + result.getField(ning.app.Field.ID));
				app.network_domain = result.getField(ning.app.Field.ID);
			}
			if (debug)  {
				console.info("Subdomain: " + result.getField(ning.app.Field.SUB_DOMAIN));
				console.info("Domains: " + result.getField(ning.app.Field.DOMAINS));
			}

			var local_id = app.network_domain;
			if (debug) console.log("Getting Bizmo ID for Network ID; " + local_id);
			app.getLinkedBizmoId(local_id, function(resp) {
				app.onGetLinkedBizmoIdResponse(resp);
				app.render();
			});
		};

		this.showEnvironmentDebug = function() {

			this.el.debug_container.append("OpenSocial Version: " + opensocial_version + "<br/>");
			this.el.debug_container.append("OpenSocial Domain: " + this.domain + "<br/>");
			if (this.container_name == "Ning") {
				this.el.debug_container.append("Ning Network Domain: " + this.network_domain + "<br/>");
			}

			/**
			* A bunch of environment/context vars
			*/
			if (this.owner == null) {
				this.el.debug_container.append("Owner: not found<br/>");
				// This should never happen!
			} else {
				this.el.debug_container.append("Owner: " + this.owner.getDisplayName() + " / " + this.owner.getId() + "<br/>");
			}
			if (this.viewer == null) {
				this.el.debug_container.append("Viewer: not found<br/>");
				// This should never happen: Non-logged-in users still have a Viewer object!
			} else {
				this.el.debug_container.append("Viewer: " + this.viewer.getDisplayName() + " / " + this.viewer.getId() + "<br/>");
			}
			if (this.viewer.getId() == "_anonymous") {
				this.el.debug_container.append("Anonymous User: Yes<br/>");
			}
			if (this.is_installed) {
				this.el.debug_container.append("Installed: Yes<br/>");
			} else {
				this.el.debug_container.append("Installed: No<br/>");
			}
			if (this.isNetworkApp) {
				this.el.debug_container.append("App Type: Network<br/>");
			} else {
				this.el.debug_container.append("App Type: Profile<br/>");
			}

		};



// 	for (var key in me) {
// 		this[key] = me[key];
// 	};
//
// 	this.test1_function = function(foo) {
// 		console.log("Test1_function: " + foo + ", owner is");
// 		console.debug(owner);
// 	};
// 	this.test1 = function() {
// 		console.info("Base2 TEST1, owner is ");
// 		console.debug(this.owner);
// 	}
};

