/*
 * TITLE: script for handling relationship widget UI
 * Editor: Hemant/Alan 
 * Description:
 *  functions to handle communication between dbpedia server and localhost here (we send query
 *  using flash script to Dbpedia server, for fetching the relationships between entities)
 */

var RelationshipWidget = (function() { 
	
	// "private static" members (referenced by closure)

	var baseSwfPath = '../widgets/entityRelationship/RelFinder.swf',
	emptyResultsMessage = 'There were no entities found for the chosen event, location, and date.',

	// for building a query string for the swf file.
	// accepts an array of base64 encoded strings which represent entities
	getParams = function(entities) {
		if(!entities || entities.constructor !== Array || entities.length === 0){
			return '';
		}
		var params = '';
		// loop through and append entities to query string
		for(var i=0; i<entities.length; i++){
			params += (i > 0 ? '&' : '?') + 'obj' + (i+1) + '=' + entities[i].base64;
		}
		// add the default base64-encoded URL parameters
		params += '&name=REJwZWRpYQ==&abbreviation=ZGJw&description=TGlua2VkIERhdGEgdmVyc2lvbiBvZiBXaWtpcGVkaWEu&endpointURI=aHR0cDovL2RicGVkaWEub3Jn&dontAppendSPARQL=ZmFsc2U=&defaultGraphURI=aHR0cDovL2RicGVkaWEub3Jn&isVirtuoso=dHJ1ZQ==&useProxy=ZmFsc2U=&method=UE9TVA==&autocompleteLanguage=ZW4=&autocompleteURIs=aHR0cDovL3d3dy53My5vcmcvMjAwMC8wMS9yZGYtc2NoZW1hI2xhYmVs&ignoredProperties=aHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zI3R5cGUsaHR0cDovL3d3dy53My5vcmcvMjAwNC8wMi9za29zL2NvcmUjc3ViamVjdCxodHRwOi8vZGJwZWRpYS5vcmcvcHJvcGVydHkvd2lraVBhZ2VVc2VzVGVtcGxhdGUsaHR0cDovL2RicGVkaWEub3JnL3Byb3BlcnR5L3dvcmRuZXRfdHlwZSxodHRwOi8vZGJwZWRpYS5vcmcvcHJvcGVydHkvd2lraWxpbmssaHR0cDovL3d3dy53My5vcmcvMjAwMi8wNy9vd2wjc2FtZUFz&abstractURIs=aHR0cDovL2RicGVkaWEub3JnL29udG9sb2d5L2Fic3RyYWN0&imageURIs=aHR0cDovL2RicGVkaWEub3JnL29udG9sb2d5L3RodW1ibmFpbCxodHRwOi8veG1sbnMuY29tL2ZvYWYvMC4xL2RlcGljdGlvbg==&linkURIs=aHR0cDovL3B1cmwub3JnL29udG9sb2d5L21vL3dpa2lwZWRpYSxodHRwOi8veG1sbnMuY29tL2ZvYWYvMC4xL2hvbWVwYWdlLGh0dHA6Ly94bWxucy5jb20vZm9hZi8wLjEvcGFnZQ==&maxRelationLegth=Mg==';
		return params;
	},

	getNewWidgetDiv = function(id) {
		return $('<div id="' + id + '">\
			<p>The Entity Relationship Widget requires Flash Player version 9 or higher.\
			<span><a href="http://www.adobe.com/go/getflashplayer"><img\
				src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif"\
				alt="Get Adobe Flash player" /></a></span>\
			</p>\
		</div>');
	};
	
	
	// constructor
	return function(cfg) {

		var that = this;
	
		cfg = cfg || {};
		cfg.flashvars = cfg.flashvars || {};
		cfg.params = cfg.params || {
			wmode: 'opaque',
			menu: 'false',
			scale: 'noScale',
			allowFullscreen: 'true',
			allowScriptAccess: 'always',
			bgcolor: '#FFFFFF'
		};
		cfg.attributes = cfg.attributes || {
			id: cfg.id
		};
		
		cfg.height = cfg.height || '100%';
		cfg.width = cfg.width || '100%';

		var container = typeof cfg.container === 'string' ? $('#' + cfg.container) : cfg.container,
			id = container.attr('id') + '-object',
			currentEntities = [];

			buildForm = function(entities) {
				var label, base64,
					form = $('<form>'),
					listHtml = '<div>';

				for(var i=0; i<entities.length; i++){
					label = entities[i].label;
					base64 = entities[i].base64;
					listHtml += '<input type="checkbox" id="' + label + '" value="' + base64 + '"' + (i < 5 ? 'checked' : '') + ' />\
						<label for="' + label + '">' + label + '</label><br/>';
				}
				listHtml += '</div>';
				list = $(listHtml);

				return form.append(list);
			},

			showForm = function() {
				that.form.dialog({
					modal: true,
					title: 'Entity Selection',
					buttons: {
						'Show Relations': function() {
							var els = that.form.get(0).elements,
								selected = [];
							for(var i=0; i<els.length; i++)
								if(els[i].checked)
									selected.push({
										label: els[i].id,
										base64: els[i].value
									});
							if(selected.length < 2){
								$('<div>Please select at least two entites to show their relations.</div>').dialog({
									title: 'Invalid Selection',
									height: 50,
									width: 430,
									resizable: false,
									buttons: {
										OK: function() {
											$(this).dialog("close");
										}
									}
								});
							}
							else {
								that.form.dialog("close");
								that.show(selected);
							}
						}
					}
				});
				if(!that.form.dialog('isOpen')){
					that.form.dialog('open');
				}
			};
		
		// makes ajax request to server to fetch entities,
		// then displays them as a form with checkboxes so the user can narrow the list
		this.getEntities = function(event, date, clusterLabel) {

			$.getJSON('../widgets/entityRelationship/relationships.php', {
				eventid: event,
				date: date,
				cluster_label: clusterLabel
			}, function(response) {
				
				/* expects a json response of:
				 * {
				 * 		success: Boolean,
				 * 		msg: String (only read if success === false),
				 * 		results: [{
				 *			label: String,
				 *			base64: String (Base64(label))
				 * 		}, {
				 *			label: String,
				 *			base64: String (Base64(label))
				 * 		}]
				 * }
				 */

				container.css('display', 'block');
				if(response.success){
					that.form = buildForm(response.results);
					that.show(response.results.slice(0, 5));
				}
				else {
					container.html(response.msg);
				}
			});
			
		};

		this.show = function(entities) {

			this.currentEntities = entities;
			container
				.empty()
				.append($('<div class="choose-entity-button">').click(showForm))
				.append(getNewWidgetDiv(id));
				
			swfobject.embedSWF(
				baseSwfPath + getParams(this.currentEntities),
				id,
				cfg.width,
				cfg.height,
				"9.0.0",
				"expressInstall.swf",
				cfg.flashvars,
				cfg.params,
				cfg.attributes
			);
		};
		
	};
	
})();

