{extends file=$smarty.const.SMARTY_LAYOUT_MAIN_POPUP}

{block name="template-head" append}
	{$JS->loadGroup('remoteLoad')}
	{$CSS->loadGroup('remoteLoad')}

	{$JS->loadGroup("optionsBox.icons")}
	{$CSS->loadGroup("optionsBox.icons")}

	{$CSS->load("{asset path="_css/index.css"}")}
{/block}

{block name="content"}
	<div id="supplierInvoiceDetails">
		{if !$closePopup}
			<form id="form" class="form" method="post" action="">
				<table class="simpleList w100p">
					<tbody>
						<tr>
							<!-- SUPPLIER FIELDS -->
							<td class="supplierFields">
								{$mvcView->getSupplierDetails()->render()}
							</td>
							<td class="invoiceDetails">
								{$mvcView->getInvoiceDetailsContainer()->render()}
							</td>
						</tr>
					</tbody>
				</table>
				<div id="extraInfo">
					{$mvcView->getPluginExtraFields()->render()}
				</div>


				<div id="invoiceRows">
					{$mvcView->getInvoiceRows()->render()}
				</div>

				{$mvcView->getExtraInfo()->render()}

				<input type="hidden" name="save" id="save" value="1" />
			</form>
		{/if}

		{block name="submitButton"}
			<div class="buttons layout-L">
				{if !$closePopup}
					<button type="button" class="button-popupSubmit" onclick="$('form').submit()">{$_LANG['save']}</button>
				{/if}
			</div>
		{/block}
	</div>
{/block}

{block name="js" append}
	<script type="text/javascript">
		MVC.servicesFieldsSettings = {$servicesFieldsSettings|json_encode};
		MVC.supplierInvoicesVats = {$supplierInvoicesVats|json_encode};
		MVC.invoiceIsBalanced = {$invoiceIsBalanced|json_encode};
		MVC.basePrices = {$basePrices|json_encode};

		MVC.supplierInvoice = {};

		MVC.supplierInvoice.tableInvoiceRows = null;

		if ($('invoiceRows')) {
			MVC.supplierInvoice.tableInvoiceRows = $('invoiceRows').down('table.clonesContainer.matrix');
		}
		MVC.supplierInvoice.currencyDecimals = {$currencyDecimals|json_encode};

		MVC.loadRemoteSupplierDetails = function(idSupplier, parent) {
			if (idSupplier) {
				new Ajax.Request(MVC.appUrl('RemoteData/JsonEntityDetails', 'supplier'), {
					parameters: { id : idSupplier },
					onSuccess : function(transport){
						var json = transport.responseJSON;
						if (json) {
							MVC.refreshSupplierDetails(json, parent);
						}
					}
				});
			}
			else {
				MVC.refreshSupplierDetails({}, parent);
			}
		}

		MVC.updateInvoiceDueDate = function()
		{

			// get supplier id
			var idSupplier = FormField.getValue('form_Supplier', 'App/Form/Input/Autocomplete_Supplier', 'supplierData[idSupplier]', 'supplierData_idSupplier_');

			// get invoice date
			if ($('invoiceData_date_')) {
				var invoiceDate = FormField.getValue('form_Invoice', 'Engine/Form/Input/Date', 'invoiceData[date]', 'invoiceData_date_');
			}
			else {
				var invoiceDate = $F('oldInvoiceDate');
			}

			// update invoice date from supplier
			new Ajax.Request(MVC.appUrl('Invoices/SupplierInvoices/Management', 'getDueDateFromSupplier'), {
				parameters: { idSupplier : idSupplier, 'invoiceDate': invoiceDate },
				onSuccess : function(transport){
					var json = transport.responseJSON;
					if (json) {
						MVC.refreshInvoiceDueDate(json);
					}
				}
			});
		}

		MVC.refreshInvoiceDueDate = function(json)
		{
			FormField.setValue(null, 'Engine/Form/Input/Date', null, $('invoiceData_dueDate_'), json.dueDate);
		}

		MVC.refreshSupplierDetails = function(json, parent)  {
			// update company
			var inputCompany = parent.down('span#company');
			inputCompany.update((json.company?json.company:''));

			// update regno
			var inputRegNo = parent.down('span#regNo');
			inputRegNo.update((json.regNo?json.regNo:''));

			// update fiscal code
			var inputFiscalCode = parent.down('span#fiscalCode');
			inputFiscalCode.update((json.fiscalCode?json.fiscalCode:''));

			var selectBankAccounts = parent.down('select#supplierData_bankAccount_');

			if (!json.bankAccounts) {
				json.bankAccounts = [];
			}

			json.bankAccounts.unshift({
				'value' : '',
				'label': '-',
				'defaultAccount': 0
			});

			selectBankAccounts.populateSelectorValues(json.bankAccounts);



			if ({$idBankAccount}) {
				selectBankAccounts.setSelectorValue({$idBankAccount});
			}
			else {
				for (var i = 0; i < json.bankAccounts.length; i++) {
					if (json.bankAccounts[i]['defaultAccount'] == '1') {
						selectBankAccounts.setSelectorValue(json.bankAccounts[i]['value']);
					}
				}
			}
		}

		MVC.showSupplierAutocompleteButtons = function(container) {
			container.down('var.supplierInfo').show();

			if (container.down('a.supplierUpdate')) {
				container.down('a.supplierUpdate').show();
			}

			if (container.down('a.showSupplierSuggestions')) {
				container.down('a.showSupplierSuggestions').hide();
			}
		}

		MVC.hideSupplierAutocompleteButtons = function(container) {
			container.down('var.supplierInfo').hide();

			if (container.down('a.supplierUpdate')) {
				container.down('a.supplierUpdate').hide();
			}

			if (container.down('a.showSupplierSuggestions')) {
				container.down('a.showSupplierSuggestions').show();
			}
		}

		/* This function is used to validate uniqueness of number */
		MVC.gatherCallback = function()
		{
			if ($('invoiceData_date_')) {
				var invoiceDate = FormField.getValue('form_Invoice', 'Engine/Form/Input/Date', 'invoiceData[date]', 'invoiceData_date_');
			}
			else {
				var invoiceDate = $F('oldInvoiceDate');
			}

			var params = {
				'idSupplier': 	FormField.getValue('form_Supplier', 'App/Form/Input/Autocomplete_Supplier', 'supplierData[idSupplier]', 'supplierData_idSupplier_'),
				'invoiceDate':	invoiceDate,
				'idInvoice': 	"{$idInvoice}"
			};
			return params;

		}

		MVC.revalidateElement = function(element)
		{
			_inputValidator.triggerRegisteredValidatorsForContainer(element.up('td.inputElement'));
		}


		MVC.toggleServiceDataInput = function(serviceCode, tbody) {
			// get selector for vatQuota
			var fldVatQuota = tbody.down("td.vatValue select::regex(name, ^invoiceRows\\[[0-9]+\\]\\[vatQuota\\]$)");
			var idInvoiceRow =  $F(tbody.down('input[type="hidden"].idInvoiceRow'));

			// toggle vat quota
			MVC.toggleVatQuotaSelect(fldVatQuota, MVC.supplierInvoicesVats[serviceCode]);

			// populate vat quota
			MVC.populateVatQuotaSelect(fldVatQuota, MVC.supplierInvoicesVats[serviceCode]);

			if (!tbody.hasClassName('disabled')) {
				// setup validators
				MVC.setServiceFieldsValidators(serviceCode, tbody);

			}
		}


		MVC.setServiceFieldsValidators = function(serviceCode, tbody) {

			var serviceFieldsSetup = (MVC.servicesFieldsSettings[serviceCode] ? MVC.servicesFieldsSettings[serviceCode] : MVC.servicesFieldsSettings["_undefined_"]);

			for (var fieldName in serviceFieldsSetup) {

				if (serviceFieldsSetup.hasOwnProperty(fieldName)) {
					var fld = tbody.down(
						"td.serviceData select::regex(name, ^invoiceRows\\[[0-9]+\\]\\[%s\\]$)".sprintf(fieldName)
						+ ",td.serviceData input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[%s\\]$)".sprintf(fieldName)
						+ ",td.serviceData input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[%s\\]\\[id\\]$)".sprintf(fieldName)	// autocomplete
						+ ",td.serviceData textarea::regex(name, ^invoiceRows\\[[0-9]+\\]\\[%s\\]$)".sprintf(fieldName));

					if (!fld) {
						alert("Cannot extract field for column '" + fieldName + "'");
						throw "Cannot extract field for column '" + fieldName + "'";
					}

					MVC.setServiceDataInputOptions(fld, serviceFieldsSetup[fieldName]);
				}

			}

		}


		MVC.setServiceDataInputOptions = function(element, options) {
			// field is visible
			if (options['isVisible']) {
				element.up('div.input').removeClassName('invisible');
			}

			// field is invisible
			else {
				element.up('div.input').addClassName('invisible');
			}

			if (options['isMandatory']) {
				element.up('div.input').addClassName('mandatory');
				_inputValidator.createOnLoad(element, 'blank', { "mandatory":true});
			}
			else {
				element.up('div.input').removeClassName('mandatory');

				_inputValidator.destroy(function(validator, index){
					var velements = validator.element;
					for(var i = 0; i < velements.length; i++) {
						var el = velements[i];
						if (element == el) {
							return true;
						}
					}

					return false;
				}.bind(null));
			}
		}

		/* Toggle vat quota select input */
		MVC.toggleVatQuotaSelect = function(fld, options)
		{
			if (options) {
				fld.up('div.input').removeClassName('invisible');
				fld.select('option').invoke('remove');
			}
			else {
				fld.up('div.input').addClassName('invisible');
			}
		}

		/* Populate vat quota select input */
		MVC.populateVatQuotaSelect = function(fld, options)
		{
			if (options) {
				// loop through options
				for (var property in options['list']) {
					var selected = false;

					if (options['default'] === property) {
						selected = true;
					}

					var option = new Element('option', { 'value': property, 'selected': selected});
					option.update(property);
		    		fld.insert({ 'bottom': option});
				}
			}
		}

		MVC.supplierInvoice.validateInvoiceRowsPrices = function(tbody) {

			// collect input value
			var quantityValue = 	$F(tbody.down('td.quantity > input.input-text'));
			var unitPriceValue = 	$F(tbody.down('td.unitPrice > input.input-text'));
			var baseValue = 		$F(tbody.down('td.baseValue > input.input-text'));
			var vatValue = 			$F(tbody.down('td.vatValue  input.input-text'));
			var total = 			$F(tbody.down('td.total > input.input-text'));

			if (parseFloat(quantityValue) <= 0) {
				tbody.down('td.quantity > input.input-text').value = 1;
			}
			else {
				tbody.down('td.quantity > input.input-text').value = Number(quantityValue) || 1;
			}

			tbody.down('td.unitPrice > input.input-text').value = Number(unitPriceValue) || 0;
			tbody.down('td.baseValue > input.input-text').value = Number(baseValue) || 0;
			tbody.down('td.vatValue  input.input-text').value = Number(vatValue) || 0;
			tbody.down('td.total > input.input-text').value = Number(total) || 0;

		}

		MVC.supplierInvoice.getValue = function(element, defaultValue) {
			if (element == null) {
				return defaultValue;
			}

			return ($(element)?$F(element):defaultValue);
		}

		MVC.supplierInvoice.recalculateInvoiceRowPrices = function(tbody, component)
		{
			var tdDescription = 	tbody.down("td.description");
			var tdQuantity	 = 		tbody.down("td.quantity");
			var tdUnitPrice	 = 		tbody.down("td.unitPrice");
			var tdPrice		 = 		tbody.down("td.baseValue");
			var tdVAT		 = 		tbody.down("td.vatValue");
			var tdTotalPrice = 		tbody.down("td.total");

			// get input element
			var quantityElm =  	(tdQuantity ? tdQuantity.down("input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[quantity\\]$)") : null);
			var unitPriceElm =  (tdUnitPrice ? tdUnitPrice.down("input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[unitPrice\\]$)") : null);
			var serviceCodeElm =tdDescription.down("select::regex(name, ^invoiceRows\\[[0-9]+\\]\\[service\\]$)");
			var basePriceElm =  tdPrice.down("input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[baseValue\\]$)");
			var vatPercentElm = tdVAT.down("select::regex(name, ^invoiceRows\\[[0-9]+\\]\\[vatQuota\\]$)");
			var vatPriceElm =  	tdVAT.down("input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[vat\\]$)");
			var totalPriceElm = tdTotalPrice.down("input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[total\\]$)");

			var serviceCode = MVC.supplierInvoice.getValue(serviceCodeElm, '');

			// set data attributes, these could be set from the rendered template, but it's too hard to do now, so this will have to do
			tdDescription.setAttribute('data-component', 'serviceCode');
			tdQuantity.setAttribute('data-component', 'quantity');
			tdUnitPrice.setAttribute('data-component', 'unitPrice');
			tdPrice.setAttribute('data-component', 'basePrice');
			tdVAT.setAttribute('data-component', 'VATPrice');
			tdTotalPrice.setAttribute('data-component', 'totalPrice');

			var history = [];	// history of manually changed components. It could be saved in the DOM tree, ad used when recalculating the components. For now it will only contain the last changed element
			history.push(component);
			var componentValues = this.recalculateComponents(component, history, quantityElm, unitPriceElm, basePriceElm, vatPriceElm, totalPriceElm, vatPercentElm, MVC.supplierInvoicesVats[serviceCode]);

			// set input values
			this.setInputValue(quantityElm, 	componentValues['quantity'], 1);
			this.setInputValue(unitPriceElm, 	componentValues['unitPrice'], 0);
			this.setInputValue(basePriceElm, 	componentValues['basePrice'], 0);
			this.setInputValue(vatPriceElm, 	componentValues['VATPrice'], 0);
			this.setInputValue(totalPriceElm, 	componentValues['totalPrice'], 0);

			// recalculate totals
			MVC.supplierInvoice.calculateTotalInvoice();
		}

		MVC.supplierInvoice.recalculateComponents = function(componentElm, historyArr, quantityElm, unitPriceElm, basePriceElm, vatPriceElm, totalPriceElm, vatPercentElm, vatPercents) {
			// console.info('recalculateComponents');	// DEBUG: enable this

			// the complete list of components handled by this function
			let allComponents = [vatPriceElm, basePriceElm, totalPriceElm, unitPriceElm, quantityElm, ];		// the order here represents the priority in which the components will be calculated

			// the list of components that should not be touched, because one way or another they are viewed as constant components
			let constantComponents = historyArr;

			// extend the list of components that should not be touched
			var changedComponentName = componentElm.up('td[data-component]').getAttribute('data-component');

			// determine if totalPriceElm should be constant
			if (![basePriceElm, totalPriceElm, unitPriceElm].includes(componentElm)
				&& Number($F(totalPriceElm))) {
				constantComponents.push(totalPriceElm);
			}

			// determine if VATPriceElm should be constant
			if (Number($F(quantityElm))) {
				constantComponents.push(quantityElm);
			}

			// determine if VATPriceElm should be constant
			if (![vatPercentElm, vatPriceElm, basePriceElm, totalPriceElm, unitPriceElm].includes(componentElm)
				&& allComponents.includes(componentElm) 	// check if we changed a field that is not part of the price list (service code, description, etc)
				&& Number($F(vatPriceElm)) && vatPercents['list'][$F(vatPercentElm)]) {
				constantComponents.push(vatPriceElm);
			}

			// determine if vatPercentElm should be constant
			if (componentElm!=vatPercentElm) {
				constantComponents.push(vatPercentElm);
			}

			// the list of components that should be calculated
			let dynamicComponents = allComponents.filter(component => !constantComponents.includes(component));

			// console.info('allComponents', allComponents);			// DEBUG: enable this
			// console.info('fixedComponents', constantComponents);	// DEBUG: enable this
			// console.info('dynamicComponents', dynamicComponents);	// DEBUG: enable this

			let invoiceCurrency = $F($$("select[name='invoiceData[currency]']").first());

			var componentValues = {
				quantity: 	((constantComponents.includes(quantityElm))? 	Number($F(quantityElm)) : null),
				unitPrice: 	((constantComponents.includes(unitPriceElm))? 	Number($F(unitPriceElm)) : null),
				basePrice: 	((constantComponents.includes(basePriceElm))? 	Number($F(basePriceElm)) : null),
				VATPrice: 	((constantComponents.includes(vatPriceElm))? 	Number($F(vatPriceElm)) : null),
				totalPrice: ((constantComponents.includes(totalPriceElm))? 	Number($F(totalPriceElm)) : null),
				vatPercent: ((constantComponents.includes(vatPercentElm))? 	Number(vatPercents['list'][$F(vatPercentElm)]) : null),
			};

			// console.info('componentValues', componentValues);	// DEBUG: enable this

			// this is a list of calculators (local functions), defined per component
			let componentCalculators = {
				quantity: [	// the order of each calculator represents the priority in which the component will be calculated, until we get some result

					// each calculator is defined as: (quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => calculatedValue
					// it will only do the calculation if the input elements are defined, otherwise it will return null
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(basePrice && unitPrice)
							?(basePrice/unitPrice)
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return 1;	// assume that the quantity is 1, if no other way to calculate it exists
					},
				],
				unitPrice: [
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(basePrice && quantity)
							?(basePrice/quantity)
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(basePrice)
							?(basePrice)
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(totalPrice && VATPrice)
							?(totalPrice - VATPrice)
							:null
						);
					},
				],
				basePrice: [
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(totalPrice && VATPrice)
							?(totalPrice - VATPrice)
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(unitPrice && quantity)
							?(unitPrice*quantity)
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(totalPrice)
							?(totalPrice * 100/(100 + vatPercent))
							:null
						);
					},
				],
				VATPrice: [
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(totalPrice && basePrice)
							?(totalPrice - basePrice)
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(basePrice)
							?((basePrice * vatPercent) / 100)
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(totalPrice)
							?(totalPrice - round((totalPrice * 100/(100 + vatPercent)), MVC.supplierInvoice.currencyDecimals[(invoiceCurrency?invoiceCurrency:'__max__')]))
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(quantity && unitPrice)
							?(quantity * unitPrice * vatPercent) / 100
							:null
						);
					},
				],
				totalPrice: [
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(basePrice && VATPrice)
							?(basePrice + VATPrice)
							:null
						);
					},
					(quantity, unitPrice, basePrice, VATPrice, totalPrice, vatPercent) => {
						return (
							(basePrice)
							?(basePrice)
							:null
						);
					},
				],
			};


			// calculate dynamic components, using the previously defined calculators
			for (var i=0; i < dynamicComponents.length; i++) {
				var componentName = dynamicComponents[i].up('td[data-component]').getAttribute('data-component');

				// console.info('calculate', componentName);	// DEBUG: enable this

				var calculator = componentCalculators[componentName];

				for (var ci=0; ci<calculator.length; ci++) {
					var componentCalc = calculator[ci];

					if (componentValues[componentName]==null) {
						let value = componentCalc(
							componentValues['quantity'],
							componentValues['unitPrice'],
							componentValues['basePrice'],
							componentValues['VATPrice'],
							componentValues['totalPrice'],
							componentValues['vatPercent']
						);

						if (value!==null) {
							componentValues[componentName]  = round(value, MVC.supplierInvoice.currencyDecimals[(invoiceCurrency?invoiceCurrency:'__max__')]);
							// console.info(componentName, '=', componentValues[componentName], ' (calculator: ', ci, ')');	// DEBUG: enable this
						}
					}
				}
			}

			// console.info('componentValues', componentValues);	// DEBUG: enable this

			return componentValues;
		}

		MVC.supplierInvoice.setInputValue = function(elm, value, defaultValue) {
			if (Number($F(elm)) != value) {
				elm.setValue(value??0);
				FormField.highlightChangedElement(elm);
			}
		}


		/********************** CALCULATE TOTAL INVOICE ************************/
		MVC.supplierInvoice.calculateTotalInvoice = function() {
			var tdBaseValueList = MVC.supplierInvoice.tableInvoiceRows.select('td.baseValue');
			var tdVatValueList = MVC.supplierInvoice.tableInvoiceRows.select('td.vatValue');

			var totalBaseValue = MVC.basePrices['totalBaseValue'];
			for (var i=0; i < tdBaseValueList.length; i++) {
				var baseValueInput = tdBaseValueList[i].down("input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[baseValue\\]$)");
				if (!isNaN(parseFloat($F(baseValueInput)))) {
					totalBaseValue += parseFloat($F(baseValueInput));
				}
			}

			var totalVatValue = MVC.basePrices['totalVatValue'];
			for (var i=0; i < tdVatValueList.length; i++) {
				var vatInput = tdVatValueList[i].down("input::regex(name, ^invoiceRows\\[[0-9]+\\]\\[vat\\]$)");
				if (!isNaN(parseFloat($F(vatInput)))){
					totalVatValue += parseFloat($F(vatInput));
				}
			}

			var tbodyFooter = MVC.supplierInvoice.tableInvoiceRows.down('tbody.footer');

			let currency = $F($$("select[name='invoiceData[currency]']").first());

			// update total price
			tbodyFooter.down('td.totalPrice').down("input::regex(name, ^totalPrice$)").value = 	round(totalBaseValue, MVC.supplierInvoice.currencyDecimals[(currency?currency:'__max__')]);

			// update total vat
			tbodyFooter.down('td.totalVat').down("input::regex(name, ^totalVat$)").value = 		round(totalVatValue, MVC.supplierInvoice.currencyDecimals[(currency?currency:'__max__')]);

			// update total invoices
			tbodyFooter.down('td.totalInvoice').down("input::regex(name, ^total$)").value = 	round(totalBaseValue + totalVatValue, MVC.supplierInvoice.currencyDecimals[(currency?currency:'__max__')]);
		}

		MVC.pageRefresh = function(module, action, windowName, execOutput) {
			if (module == 'Partners/Suppliers') {
				if (windowName == 'supplierInsert') {
					$('supplierData_idSupplier_').value = execOutput['id'];
					$('supplierData_idSupplier__title_').value = execOutput['name'];
					$('supplierData_idSupplier_').value = execOutput['id'];

					MVC.loadRemoteSupplierDetails(execOutput['id'], $('form_Supplier'));
				}

				if (windowName == 'supplierUpdate') {
					MVC.loadRemoteSupplierDetails(execOutput['id'], $('form_Supplier'));
				}
			}
		};

		if (MVC.supplierInvoice.tableInvoiceRows) {
			MVC.supplierInvoice.tableInvoiceRows.observe('matrix:initialize', function(evt) {
				MVC.supplierInvoice.tableInvoiceRows.select(">tbody.clone").each(function(clone) {

					if (!clone.hasClassName('disabled')) {
						MVC.setServiceFieldsValidators(
							$F(clone.down("td.inputElement select::regex(name, ^invoiceRows\\[[0-9]+\\]\\[%s\\]$)".sprintf('service'))),
							clone
						);
					}
				});
			});

			MVC.supplierInvoice.tableInvoiceRows.observe('matrix:makeClone', function(evt) {
				MVC.toggleServiceDataInput(
					'',
					evt['memo']['clone']
				);
			});

			MVC.supplierInvoice.tableInvoiceRows.observe('matrix:removeClone', function(evt) {
				MVC.supplierInvoice.calculateTotalInvoice();
			});

		}

		MVC.scheduleOnLoad(function() {

			if ($('supplierData_idSupplier_') && $F('supplierData_idSupplier_')) {
				MVC.loadRemoteSupplierDetails($F('supplierData_idSupplier_'), $('form_Supplier'));

				if ($('supplierData_idSupplier_').up('fieldset#form_Supplier').down('div.elementOperationsButtons')) {
					MVC.showSupplierAutocompleteButtons($('supplierData_idSupplier_').up('fieldset#form_Supplier').down('div.elementOperationsButtons'));
				}
			}

			if (MVC.supplierInvoice.tableInvoiceRows) {
				MVC.supplierInvoice.calculateTotalInvoice();
			}

			if ($('supplierData_idSupplier_')) {
				$('supplierData_idSupplier_').observe('SupplierSuggestions:select', function(event, element){
					var params = {};
					params.value = event.memo.suppId;
					params.displayValue = event.memo.suppAlias;

					FormField.setValue($('supplierData_idSupplier_'), 'Engine/Form/Input/Autocomplete', null, 'supplierData_idSupplier_', params);
					RemoteHtmlViewHandler.close();
					MVC.loadRemoteSupplierDetails(params.value, $('form_Supplier'));
					MVC.showSupplierAutocompleteButtons($('form_Supplier'));
				});
			}

			$$('select.shouldBeInvisible').each(function(el){
				el.up('div.input').addClassName('invisible');
				el.removeClassName('shouldBeInvisible');
			});

			if (!MVC.invoiceIsBalanced && $$('select[name="invoiceData\[currency\]"]').length) {
				$$('select[name="invoiceData\[currency\]"]')[0].disabled = false;
			}

			{block name="onClosePopup"}
				{if $closePopup}
					setTimeout('window.close();', 1000);
					if (window.parent.opener && window.parent.opener.MVC) {
						MVC.notifyParent('document:pageRefresh', {
							'module': MVC.CURRENT_MODULE,
							'action': MVC.CURRENT_ACTION,
							'windowName': window.name,
							'execOutput': {$execOutput|json_encode}
						});
					}
				{/if}
			{/block}
		});

	</script>
{/block}


