/*	
This file handles all processing related the to HBX
Admin app. To get this to appear on your page, simply
add the following call to the bottom of your page:

<script type="text/javascript">
	var hbx = new HBXAdmin(	url,
							ajaxUrl,
							{ options });
</script>

Where 'url' is the URL of the current page, 'ajaxUrl' is the URL
of the Ajax service that's going to handle all of the calls, and
'options' is a hash of other values you want the system to be aware
of (such as any variables that might exist on the page that you
want your processor to be aware of).

Example call:

<script type="text/javascript">
	var hbx = new HBXAdmin(	'#cgi.server_name##cgi.script_name#?#cgi.query_string#',
							'hbx.cfc?method=dispatch',
							{ 	titlelist:'something^goes^here',
								site_id:1701,
								gender:'male',
								age:'28',
								skill:'competitive' });
</script>
*/


var HBXAdmin = Class.create();

HBXAdmin.prototype = {
	
	initialize: function(url,ajaxUrl,options) {
			
		// create some constants for the page
		this.ajaxUrl = ajaxUrl;
		this.url = url;
		this.options = $H(options);
		this.FIELDS_PER_COLUMN = 8;
		
		// create the admin and insert it inline
		this.drawAdmin();
	},
	
	drawAdmin: function() {

		var callback = function(result) {

			var fields = $H(this.unJSON(result.responseText));
		
			var html_out = '<div id="hbx_admin">';
			html_out += '<div id="hbx_status">';
			html_out += '	<h2>HBX Admin</h2>';
			html_out += '	<div id="hbx_add_account_container"></div>';
			html_out += '	<div id="hbx_tag"></div>';
			html_out += '	<div style="clear:both;"></div>';
			html_out += '</div>';
			html_out += '<div id="hbx_body" style="display:none;">';
			html_out += '	<form id="hbx_form" name="hbx_form">';
			html_out += '		<input type="hidden" name="page_id" id="page_id" value="" />';
			html_out += '		<input type="hidden" name="acct" id="acct" value="" />';
			html_out += '		<h1 id="hbx_title"></h1>';
			html_out += '		<div id="hbx_required_fields">';
			html_out += '			<label for="pn">Page Name</label>';
			html_out += '			<input type="text" name="pn" id="pn" value="" />';
			html_out += '			<label for="mlc">Content Category</label>';
			html_out += '			<input type="text" name="mlc" id="mlc" value="" />';
			html_out += '			<input type="button" name="commit" id="commit" value="Save Values" onclick="hbx.setValues($(\'hbx_form\'));return false;"/>';
			html_out += '			<a href="#" id="hbx_show_all_link" onclick="hbx.showOptionalVariables();return false;">Show all HBX Variables &raquo;</a>';
			html_out += '		</div>';
			html_out += '		<div id="hbx_optional_fields" style="display:none;">';
			
								var counter = 0;
								var max_fields = 8;
								fields.each(function(field) {
									counter += 1;
									if(counter == 1) {
										html_out += '<div class="column">';
									}
									
									html_out += '<label for="' + field.id + '">' + field.name + '</label>';
									html_out += '<input type="text" name="' + field.id +'" id="' + field.id + '" value="" />';
									
									if(counter == max_fields) {
										html_out += '</div>';
										counter = 0;
									}
								} );
								if(counter != max_fields) {
									html_out += '</div>';
								}
			
			html_out += '		</div>';
			html_out += '			<div id="hbx_close">';
			html_out += '				<a href="#" onclick="hbx.hideBody();return false;">X Close Admin</a>';
			html_out += '			</div>';
			html_out += '		</form>';
			html_out += '	</div>';
			html_out += '</div>';
		
			new Insertion.Top($$('body').first(), html_out);
			
			// initialize the admin with the top bar info
			this.getStatus(this.url);
			this.getAvailableAccounts(this.url);
		}.bind(this);
		
		this.ajaxCall('','getVariables',null,callback);
	},
	
	ajaxCall: function(element,method,params,callback) {
		
		var jsonCall = $H({ method:method, params:params, id:0 }).toJSON();
		
		new Ajax.Updater(	element,
							this.ajaxUrl, 
							{ 	asynchronous: true,
								parameters: "request="+encodeURIComponent(jsonCall),
								evalScripts: false,
								onComplete: callback } );
	},
	
	getStatus: function() {
		var params = { url:this.url, options:this.options };
		var callback = function(result) {
			this.updateTag(this.unJSON(result));
		}.bind(this);
		
		this.ajaxCall('','getStatus',params,callback);
	},
	
	getAvailableAccounts: function() {
		var params = { url:this.url, options:this.options };
		var callback = function(result) { 
			this.updateAvailable(this.unJSON(result));
		}.bind(this);

		this.ajaxCall('','getAvailableAccounts',params,callback);
	},
	
	getValuesForAccount: function(account) {
		var params = { url:this.url, account:account, options:this.options };
		var callback = function(result) { 
			var values = this.unJSON(result)[0];
			this.updateVariables($H(values.variables),values.id);
			this.setTitle(values.account.name,values.account.id);
			this.showBody();
		}.bind(this);
		
		this.ajaxCall('','getValues',params,callback);
	},
	
	addAccount: function(account) {
		var params = { url:this.url, account:account, options:this.options };
		var callback = function(result) {
			var market = this.unJSON(result);
			this.getStatus();
			this.getAvailableAccounts();
			this.getValues(market.id,market.name);
		}.bind(this);
		
		this.ajaxCall('','addAccount',params,callback);
	},
	
	removeAccount: function(account) {
		var params = { url:this.url, account:account, options:this.options };
		var callback = function() {
			this.hideBody();
			this.getStatus();
			this.getAvailableAccounts();
		}.bind(this);
		
		this.ajaxCall('','removeAccount',params,callback);
	},
	
	setValues: function(form) {
		var params = { url:this.url, options:this.options, variables:Form.serialize(form).toQueryParams() };
		var callback = function() {
			this.hideBody();
			this.getStatus();
			this.getAvailableAccounts();
		}.bind(this);
		
		this.ajaxCall('','setValues',params,callback);
	},
	
	updateTag: function(values) {
		var html_out = '<span class="hbx_' + values.status + '">' + values.status + '</span> tagged with ';
		values.accounts.each(function(account) {
			html_out += '<a href="#" title="' + account.id + '" onclick="hbx.getValuesForAccount(\'' + account.id + '\',\'' + account.name + '\');return false;">' + account.name + '</a> ';
		});
		html_out += '</span>';
		
		$('hbx_tag').innerHTML = html_out;
	},
	
	updateAvailable: function(values) {
		
		var html_out = '<a href="#" id="hbx_add_account_link" onclick="hbx.showAdd();return false;">+ Add another account</a>';
		html_out += '<span id="hbx_new_account" style="display: none;">';
		html_out += '	<form id="hbx_new_account_form" onsubmit="hbx.addAccount($F(account));return false;">';
		html_out += '		<select name="account">';
		html_out += '			<option value="">Select...</option>';
		html_out += '			<option value=""></option>';
		
		values.accounts.each( function(account) {
			html_out += '			<option value="' + account.id + '">' + account.name + '</option>';
		} );

		html_out += '		</select>';
		html_out += '		<input type="submit" name="submit" value="Add" />';
		html_out += '	</form>';
		html_out += '</span>';
		
		$('hbx_add_account_container').innerHTML = html_out;	
	},
	
	updateVariables: function(variables,id) {
		variables.each(function(pair) {
			if($(pair.key)) {
				$(pair.key).value = pair.value;
			}
			$('page_id').value = id;
		});
	},
	
	setTitle: function(text,account) {
		$('hbx_title').innerHTML = text + " <span class=\"hbx_remove_link\">(<a href=\"#\" onclick=\"hbx.removeAccount('"+account+"');return false;\">Remove this account</a>)</span>";
	},
	
	showAdd:function() {
		$('hbx_add_account_link').hide();
		$('hbx_new_account').show();
	},
	
	showBody: function() {
		if (!Element.visible('hbx_body')) {
			new Effect.BlindDown('hbx_body');
		}
	},
	
	hideBody: function() {
		if (Element.visible('hbx_body')) {
			new Effect.BlindUp('hbx_body');
		}
	},
	
	showOptionalVariables: function() {
		if (!Element.visible('hbx_optional_fields')) {
			new Effect.BlindDown('hbx_optional_fields');
		}
	},
	
	unJSON: function(text) {
		return text.evalJSON(true);
	}

}