
var ComboXMLClients = Class.create();
Object.extend(ComboXMLClients.prototype, CocoInPlaceComboEditorXML.prototype);
Object.extend(ComboXMLClients.prototype, {
	initialize: function(element, selected_oid, id_comercial)
	{
		url_xml = '../php_helpers/xml_exporters/get_xml_select_items.php?option=llista_clients';
		if (id_comercial != null)
		{ // filtrem per comercial
			url_xml += '&id_comercial=' + id_comercial;
		}
		this.comboXMLinitialize(element, selected_oid, null, '', '', url_xml)
	}
});

var CompraRapidaController = Class.create();
CompraRapidaController.prototype = 
{
	initialize: function()
	{
		this.arr_inputs = Array();
	},
	
	createCompraRapida: function(a_elements_div, a_total_div, options)
	{
		this.divInputs = $(a_elements_div);
		this.divInputs.innerHTML = "";		
		this.divTotal = $(a_total_div);
		this.divTotal.innerHTML = "";
		this.numCells = 7;
		this.options = options || {};
		
		this.options.headers 			= this.options.headers || ["Referencia", "Producto", "Info", "Precio", "Cant.", "Subtotal", ""]
    this.options.cells_width 	= this.options.cells_width || [100, 325, 80, 100, 80, 80, 20];
		this.options.headerClass	= this.options.headerClass || "";
		this.options.headerBgColor = this.options.headerBgColor || "";
		
		this.lastImput = null;
		this.arr_inputs = Array();
		this.create_headers();		
		this.appendInput();
	},
	
	create_headers: function()
	{
		this.tableInputs = document.createElement("table");
		this.tableInputsBody = document.createElement("tbody");
		this.tableInputs.bgColor = this.options.headerBgColor;
		this.tableInputs.cellPadding = 0;
		this.tableInputs.border = 0;
		this.tableInputs.cellSpacing = 0;
		// files		
		var row = document.createElement("tr");
		if (this.options.headerClass != "")
			Element.addClassName(row, this.options.headerClass);
		
		var cells = Array(this.numCells);
		for (var i=0; i<this.numCells; i++)
		{
			cells[i] = document.createElement("td");
			cells[i].width = this.options.cells_width[i];
			cells[i].innerHTML = this.options.headers[i];
			row.appendChild(cells[i]);
		}
		this.tableInputsBody.appendChild(row);
		this.tableInputs.appendChild(this.tableInputsBody);
		
		this.divHeaders = document.createElement("div")
		this.divHeaders.appendChild(this.tableInputs);
		this.divInputs.appendChild(this.divHeaders);
	},
	
	reset: function()
	{
		for (var i=this.arr_inputs.length-1; i>=0; i--)
		{
			this.tableInputsBody.removeChild(this.arr_inputs[i].row);
			delete this.arr_inputs[i];
		}
		this.arr_inputs = Array();
		this.appendInput();		
	},
	
	removeInput: function(a_input)
	{
		if (a_input == this.lastInput)
			return;
		
		this.tableInputsBody.removeChild(a_input.row);
		var new_arr = Array();
		var pos = 0;
		for (var i=0; i<this.arr_inputs.length; i++)
		{
			if (this.arr_inputs[i] != a_input)
			{
				new_arr[pos] = this.arr_inputs[i];
				pos++;
			}
		}
		this.arr_inputs = new_arr;
		delete a_input;	
		this.updateTotal();	
	},
	
	createInput: function(a_divItem)
	{
		return new InputCompraRapida(a_divItem, this, this.options);
	},
	
	appendInput: function( )
	{
		//var divItem = document.createElement("div")
		var input = this.createInput(this.tableInputsBody);
		this.arr_inputs[this.arr_inputs.length] = input;

		//this.divInputs.appendChild(divItem);
		this.lastInput = input;		
		this.updateTotal();
	},
	
	inputSelected: function(a_input)
	{
		if (a_input == this.lastInput)
			this.appendInput();
		a_input.autoc_input_ref.disabled = true;	
		a_input.text_qt.disabled = false;
		Element.show(a_input.input_del);
		a_input.text_qt.value = "1";
		a_input.text_qt.focus();
		a_input.text_qt.select();
	},
	
	updateTotal: function()
	{
		var total = 0;
		for (var i=0; i<this.arr_inputs.length; i++)
			total += this.arr_inputs[i].subtotal;
		
		this.divTotal.innerHTML = total.toFixed(2);		
	},
	
	hasArticles: function()
	{
		for (var i=0; i<this.arr_inputs.length; i++)
		{
			if (this.arr_inputs[i].has_article)
			 return true;
		}	
		return false;	
  },
	
	toXML: function()
	{
		var xml = "<comprarapida>";
		for (var i=0; i<this.arr_inputs.length; i++)
		{
			if (this.arr_inputs[i].has_article)
				xml += this.arr_inputs[i].toXML();
		}
		xml += "</comprarapida>";
		return xml;
	},
	
	toStr: function()
	{
		var str = "";
		for (var i=0; i<this.arr_inputs.length; i++)
		{			
			if (this.arr_inputs[i].has_article && this.arr_inputs[i].quantitat > 0 )
			{
				if (i>0)
					str += "||";
				str += this.arr_inputs[i].toStr();			
			}
		}
		return str;
	}
	
	
};

var InputCompraRapida = Class.create();
InputCompraRapida.prototype = 
{
	initialize: function(a_table, a_controller, options)
	{
		this.baseInitialize(a_table, a_controller, options);
	},
	
	baseInitialize: function(a_table, a_controller, options)
	{
		this.table = $(a_table);
		this.row = null;
		this.controller = a_controller;
		this.initAttributes();
		
		this.options = options || {};
		
		
		this.options.htmlNovetat 	= this.options.htmlNovetat || "Novedad";
		this.options.textBoxClass = this.options.textBoxClass || "none";
		this.options.htmlInputDelImageSrc = 	this.options.htmlInputDelImageSrc || '';	

		this.create_element();
		this.bind_events();
		
		
		// inicialitzem l'autocompleter de l'element
		var ops = {
			paramName:'input', 
			select:'selectme', 
			indicator: this.loading, 			
			owner: this,
			onComplete: this.onComplete.bind(this),
			afterUpdateElement: function(a_text_field, a_list_item)
			{
				this.owner.on_select_ref(a_text_field, a_list_item);
			}
		}
		
		//this.autoc_obj = new Ajax.Autocompleter(this.autoc_input_ref,this.autoc_update,'../../php_helpers/autocompletion/autocompleter_articles.php', ops ); 
		this.autoc_obj = new CocoAjaxAutocompleter(this.autoc_input_ref,this.autoc_update,'../../php_helpers/autocompletion/autocompleter_articles.php', ops ); 
						
	},
	
	onComplete: function(request)
	{
		this.baseOnComplete(request);
	},
	
	baseOnComplete: function(request)
	{		
	    this.autoc_obj.updateChoices(request.responseText);
	},
	
	initAttributes: function()
	{
		this.baseInitAttributes();
	},
	
	baseInitAttributes: function()
	{		
		this.preu_unitari  = 0;
		this.quantitat = 0;
		this.subtotal = 0;
		this.has_article = false;
		this.is_novetat = false;
		this.numCells = this.controller.numCells;
	},	
	
	create_element:function()
	{
		// taula de continguts
		/*
		var table = document.createElement("table");
		table.bgColor = "#FCFCFC";
		table.cellPadding = 0;
		table.border = 0;
		table.cellSpacing = 0;
		*/
		// files		
		//this.row = document.createElement("tr");		
		this.row = this.table.insertRow(1);
		// cel·les i continguts
		
		var cells = Array(this.numCells);
		var totalWidth = 0;
		for (var i=0; i<this.numCells; i++)
		{
			cells[i] = document.createElement("td");
			cells[i].width = this.options.cells_width[i];
			cells[i].height = 25;
			this.row.appendChild(cells[i]);
			
			totalWidth += cells[i].width;
		}
		//this.table.appendChild(this.row);
		
	
		
		// autocompleter
		this.divRef = document.createElement("div");	
		this.autoc_input_ref = document.createElement("input");
		this.autoc_input_ref.type = "text";
		this.autoc_input_ref.size = 14;
		Element.addClassName(this.autoc_input_ref, this.options.textBoxClass);
		this.divRef.appendChild(this.autoc_input_ref);
		this.divRef.align = "center";
		
		// text info
		this.autoc_descrip = document.createElement("div");
		this.autoc_descrip.style.padding = 5;
		this.autoc_descrip.innerHTML = " ";
		
		// div Info
		this.divInfo = document.createElement("div");
		this.divInfo.align = "center";		
		this.divInfo.textContent = " ";
		
		// div Preu		
		this.divPreu = document.createElement("div");
		this.divPreu.align = "right";
		this.divPreu.style.padding = 5;
		this.divPreu.innerHTML = "0.00";
				
		// div quantitat
		this.divQt = document.createElement("div");
		this.divQt.align = "center";
		this.text_qt = document.createElement("input");
		this.text_qt.type = "text";
		this.text_qt.value = "1";
		this.text_qt.size = 3;
		Element.addClassName(this.text_qt, this.options.textBoxClass);
		this.text_qt.disabled = true;
		this.divQt.appendChild(this.text_qt);
		
		// subtotal
		this.divSubtotal = document.createElement("div");
		this.divSubtotal.innerHTML = "0.00";
		this.divSubtotal.align = "right";
		this.divSubtotal.style.padding = 5;
		
		// opcions
		this.divOpcions = document.createElement("div");
		this.input_del = document.createElement("input");
		if (this.options.htmlInputDelImageSrc == "")
		{
			this.input_del.type = "button";
			this.input_del.value = "-";
			Element.addClassName(this.input_del, this.options.textBoxClass);
	  }
		else
		{
			this.input_del.type = "image";
			this.input_del.src = this.options.htmlInputDelImageSrc;
		}		
		this.input_del.style.display = "none";
		this.divOpcions.appendChild(this.input_del);
		this.divOpcions.align = "center";
		
		// fill cells
		cells[0].appendChild(this.divRef);
		cells[1].appendChild(this.autoc_descrip);
		cells[2].appendChild(this.divInfo);
		cells[3].appendChild(this.divPreu);		
		cells[4].appendChild(this.divQt);		
		cells[5].appendChild(this.divSubtotal);
		cells[6].appendChild(this.divOpcions);
		
		
		//this.element.appendChild(table);
		
		// loading div
		//var row2 = document.createElement("tr");
		var row2 = this.table.insertRow(2);
		var cell2 = document.createElement("td");
		cell2.colSpan = this.numCells;
		cell2.width = totalWidth;
		
		
		this.loading = document.createElement("div");
		this.loading.textContent = "Loading..."
		this.loading.style.display = "none";
		
		
		// div autocompleter list
		this.autoc_update = document.createElement("div");		
		Element.addClassName(this.autoc_update, "autocomplete");
		this.autoc_update.style.position = "relative";		
		this.table.appendChild(this.autoc_update);
		
		cell2.appendChild(this.loading);
		cell2.appendChild(this.autoc_update);
		row2.appendChild(cell2);
		//this.table.appendChild(row2);								
	},
	
	bind_events: function()
	{
		Event.observe(this.text_qt, 'change', this.on_quantity_changed.bindAsEventListener(this), false);
		Event.observe(this.text_qt, 'keypress', this.on_keypress_quantity.bindAsEventListener(this), false);
		Event.observe(this.input_del, 'click', this.on_input_del_clicked.bindAsEventListener(this), false);
		//Event.observe(this.autoc_input_ref, 'keyup', this.on_keyup_ref.bindAsEventListener(this));
	},
	
	on_keyup_ref: function(event)
	{
		switch(event.keyCode)
		{
			case Event.KEY_UP:
			case Event.KEY_DOWN:
				Element.scrollTo(this.autoc_obj.getEntry(this.autoc_obj.index));
				return;
		}
	},
	
	on_select_ref: function(a_text_field, a_list_item)
	{ // estem en el marc del Autocompleter
		var product_name = a_list_item.id;			
		this.autoc_descrip.innerHTML = product_name;
		
		var inputs = a_list_item.getElementsByTagName('input');
		this.process_input_hiddens(inputs);				
		
		this.controller.inputSelected(this);
		
		// update field
		this.update_info();		
		this.update_subtotal();
	},
	
	process_input_hiddens: function(inputs)
	{
		this.base_process_input_hiddens(inputs);
	},
	
	base_process_input_hiddens: function(inputs)
	{
		
		this.oid = inputs[0].value;
		this.divPreu.innerHTML  = Number(inputs[1].value).toFixed(2);
		this.is_novetat = inputs[2].value == "1";
	},
	
	
	
	update_info: function()
	{
		this.baseUpdate_info();		
	},
	
	baseUpdate_info: function()
	{
		if (this.is_novetat)
			this.divInfo.innerHTML = this.options.htmlNovetat;
		else
			this.divInfo.innerHTML = " ";
	},
	
	update_subtotal: function()
	{
		this.preu_unitari  = Number(this.divPreu.innerHTML);
		this.quantitat = Number(this.text_qt.value);
		this.subtotal = this.preu_unitari * this.quantitat;
		this.divSubtotal.innerHTML = this.subtotal.toFixed(2);
		this.has_article = true;
		this.controller.updateTotal();		
	},
	
	on_keypress_quantity: function(ev)
	{
		switch (ev.keyCode)
		{
		case Event.KEY_RETURN:
		case Event.KEY_TAB:
			this.controller.arr_inputs[this.controller.arr_inputs.length-1].autoc_input_ref.focus();
			return false;
		}
		
		keycode = ev.keyCode;
		if (keycode == 0) { // mozilla
			keycode = ev.which;
		}
		
		if (keycode >= 33)
		{
			if  (keycode >= 96 && keycode <= 105)
				return true;
			key = String.fromCharCode(keycode).toLowerCase();
			if (key < "0" || key > "9")
				return false;
		}
		
	},
	
	on_quantity_changed: function(event)
	{
		this.update_subtotal();
		//this.controller.arr_inputs[this.controller.arr_inputs.length-1].autoc_input_ref.focus();		
	},
	
	on_input_del_clicked: function(event)
	{
		this.controller.removeInput(this);
	},
	
	toXML: function()
	{
		var xml = "<article>";
		xml += "<oid>" + this.oid + "</oid>";
		xml += "<referencia>" + this.autoc_input_ref.value + "</referencia>";
		xml += "<quantitat>" + this.quantitat + "</quantitat>";
		xml += "</article>"
		return xml;
	},
	
	toStr: function()
	{
		var str = this.oid + "|" + this.autoc_input_ref.value + "|" + this.quantitat;
		return str;
	}
	
	
	
};