/*
 * Initialize a variable for editing, clear template input, and load new data into it.
 * */
function _variableEditor(varName, options) {// constructor for the main class
	if(this.name==null || !this.name )	{
		this.name='_variableEditor';
	}

	if(varName==null) {
		varName = '';
	}

	this.object = {};
	this.object.textElement = options.textElement;
	this.object.attributeName = options.attributeName;
	this.object.control = options.control;

	this.varName = varName;

	variableEditor = this;

	$('variableEditor_text_').value = '%'+varName+'%';

	this.reposition();

	$('variableEditorElement').show();

	this.refreshFilters(null, null);
}

_variableEditor.prototype.destroy=function (){

}

/*
 * Close the editing window
 * */
_variableEditor.prototype.close=function (fastClose){
	if(fastClose==true) {
		$('variableEditorElement').hide();
		var rows = $('variableEditorElement').select('tbody.functionAttributesRow');
		rows.each(function(e){e.remove();});
	}else {
		new Effect.Shrink('variableEditorElement', {
			direction:'top-right',
			duration: 0.5,
			afterFinish:function(){
				var rows = $('variableEditorElement').select('tbody.functionAttributesRow');
				rows.each(function(e){e.remove();});
			}
		});
	}

	variableEditor = null;
}

/*
 * Move the editing window
 * */
_variableEditor.prototype.reposition=function (){
	var panel3_position = $('panel_3').positionedOffset();
	var editorDimensions = $('variableEditorElement').getDimensions();

	var x = panel3_position.left-editorDimensions.width+2;
	var y = panel3_position.top+1;
	$('variableEditorElement').setStyle({'top': y+'px', 'left': x+'px'});
}

/*
 * Validate the filter by calling a server-side script, mark invalid entries accordingly
 * */
_variableEditor.prototype.refreshFilters=function (tbody, element){
	var text = this.varName;
	this.reposition();

	var functionSeparator = '';

	if(text!='') {
		functionSeparator = '|';
	}

	// compose the string to be sent to the server
	$('functionAttributesContainer').select('tbody.functionAttributesRow').each(function(tbody, idx){
		var inputValue = $F(tbody.select('select.dummy_select').first());
		if(inputValue!='' && inputValue!='-') {
			var selectedFunction = inputValue;
			var params = '';

			var paramSeparator = ':';
			tbody.select('input.dummy_param').each(function(input, index){
				var inputValue = $F(input);
				params+=paramSeparator+$F(input);
				paramSeparator=':';
			});

			text+=functionSeparator+selectedFunction+params;
			functionSeparator='|';
		}
	});

	$('variableEditor_text_').value = '%'+text+'%';

	// insert the text into the associated control...if any control is defined
	if(this.object.textElement && this.object.control) {
		insertTextAt('%'+text+'%', this.object.textElement);
		this.object.control.onChange(null, this.object.attributeName,'queue');
	}

	var url = "AJAXRequest.validateVariableEditBox.php?text=" + encodeURIComponent($F('variableEditor_text_'));
	new Ajax.Request(url, {
		method: 'post',
		onSuccess: function(transport, JSON) {
			var inputElement = $('variableEditor_text_');
			var rows = $('variableEditorElement').select('tbody.functionAttributesRow');
			rows.each(function(e){e.removeClassName('invalid');});
			$('variableEditor_status_').removeClassName('valid');
			$('variableEditor_status_').removeClassName('invalid');

			// mark the editor window with the new hints from the server
			if(JSON) {
				inputElement.removeClassName('invalid');
				if(JSON.error.invalidInput) {
					inputElement.addClassName('invalid');

					// highlight the row marked by functionIndex
					rows[JSON.error.functionIndex].addClassName('invalid');

					$('variableEditor_status_').addClassName('invalid');
					$('variableEditor_status_').update(JSON.error.internalError);
				}else {
					$('variableEditor_status_').update(JSON.result);
					$('variableEditor_status_').addClassName('valid');
				}
			}
		}.bind(this)
	});
}

/*
 * Add a new function to the list
 * */
_variableEditor.prototype.addFunction=function (options){
	if(options==null) {
		options = {};
	}

	var rows = $('variableEditorElement').select('tbody.functionAttributesRow');
	if(rows.length>25) {
		updatePageStatus({text:"the limit of elements was reached",status:'error'});
		return false;
	}

	var clone = templateFunctionAttributes.createClone($('functionAttributesContainer'), {});
	var increment=clone.readAttribute('increment');

	// build the function selector
	var attr =  $('dummy_functionAttributes_');
	var select = $('functionAttributes_'+increment+'__type_');

	select.innerHTML = attr.innerHTML;

	// build the parameters list
	var paramContainer = $('functionAttributes_'+increment+'__params_');

	initTooltips(false, $('functionAttributesContainer'));

	if(this.selectedRow) {
		this.selectedRow.removeClassName('selected');
	}

	clone.addClassName('selected');
	this.selectedRow = clone;

	this.updateFunctionList(clone);
	this.refreshFilters(null, null);
}

/*
 * Update the function list and perform any misc operations that are needed (reindex the list for now)
 * */
_variableEditor.prototype.updateFunctionList=function (clone, options){
	if(options==null) {
		options = {};
	}

	$('functionAttributesContainer').select('td.dummy_counterContainer').each(function(el, idx){
		el.update((idx+1)+".");

	});
}

/*
 * The function suffered some changes, we should update its params and refresh the filter results
 * */
_variableEditor.prototype.changeFunction=function (tbody, selector){
	var changedRow = selector.up('tbody');

	var functionName =  $(selector.options[selector.selectedIndex]).readAttribute('functionName');

	var increment = changedRow.readAttribute('increment');

	var paramContent = '';
	if($("template_functionAttributes_"+functionName +"")) {
		paramContent = $("template_functionAttributes_"+ functionName +"").innerHTML;
	}
	paramContent = paramContent.replace(/\.:index:\./g, increment);

	var paramContainer = changedRow.select('td.dummy_paramsContainer').first();

	paramContainer.update(paramContent);

	initTooltips(false, paramContainer);

	//////////////////////////////////////////
	if(this.selectedRow) {
		this.selectedRow.removeClassName('selected');
	}
	this.selectedRow = tbody;
	this.selectedRow.addClassName('selected');

	this.refreshFilters(null, null);
}

/*
 * Remove a function from the list
 * */
_variableEditor.prototype.removeFunction=function (tbody, element){
	tbody.remove();

	this.updateFunctionList(tbody);
	this.refreshFilters(null, null);
}

/*
 * Move a function down
 * */
_variableEditor.prototype.moveFunctionDown=function (tbody, element){
	if(tbody.next('tbody.functionAttributesRow')) {
		tbody.next('tbody.functionAttributesRow').insert({after:tbody});
	}

	if(this.selectedRow) {
		this.selectedRow.removeClassName('selected');
	}
	this.selectedRow = tbody;
	this.selectedRow.addClassName('selected');
	this.refreshFilters(null, null);
}

/*
 * Move a function up
 * */
_variableEditor.prototype.moveFunctionUp=function (tbody, element){
	if(tbody.previous('tbody.functionAttributesRow')) {
		tbody.previous('tbody.functionAttributesRow').insert({before:tbody});
	}

	if(this.selectedRow) {
		this.selectedRow.removeClassName('selected');
	}
	this.selectedRow = tbody;
	this.selectedRow.addClassName('selected');
	this.refreshFilters(null, null);
}