<!--// $Id$ //-->

{css}

{$default_printpage = ConfigHelper::getConfig('invoices.default_printpage')}
{$default_taxrate = ConfigHelper::getConfig('phpui.default_taxrate')}
{$default_taxlabel = ConfigHelper::getConfig('phpui.default_taxlabel')}
{$notification = ConfigHelper::checkConfig('finances.customer_notify', true)}
{$offline_support = ConfigHelper::checkConfig('ksef.offline_support')}

<FORM name="addbalance" method="POST" id="addbalance-form" action="?m=balanceadd&id={$balancelist.customerid}">
</FORM>

<FORM method="post" name="printcustomerbalance" id="printcustomerbalance" action="?m=print&type=customerbalance"
	target="_blank">
	<input type="hidden" name="customer" value="{$balancelist.customerid}">
</FORM>

{tab_container id="customerbalancebox" label="Customer Account"}

	{if $limit}
		{$content_id="customerbalancepanel"}
	{else}
		{$content_id=null}
	{/if}
	{tab_header content_id=$content_id}
		{tab_header_cell icon="lms-ui-icon-finances"}
			<strong>{trans("Customer Account")}</strong>
			{if $limit}
				{$n=$limit*-1}
			{/if}
			&nbsp;&nbsp;&nbsp;
			{strip}
				<label id="aggregate_document_label">
					<input type="checkbox" name="aggregate_documents" value="1"
							{if $aggregate_documents} checked{/if}>
					{trans("aggregate documents")}
				</label>
			{/strip}

			{if ConfigHelper::checkPrivilege('finances_management')}
				<label>
					<span class="lms-ui-label">
						{trans("from")}
					</span>
					<input type="text" name="from" size="10" maxlength="10" placeholder="{trans("yyyy/mm/dd")}"
						{tip class="lms-ui-date" text="Enter date in 'yyyy/mm/dd' format (empty field means 1970/01/01) or click to choose it from calendar"}
						form="printcustomerbalance">
				</label>
				<label>
					<span class="lms-ui-label">
						{trans("to")}
					</span>
					<input type="text" name="to" size="10" maxlength="10" placeholder="{trans("yyyy/mm/dd")}"
						{tip class="lms-ui-date" text="Enter date in 'yyyy/mm/dd' format (empty field means current date) or click to choose it from calendar"}
						form="printcustomerbalance">
				</label>
				<a href="javascript:document.printcustomerbalance.submit();">{trans("Customer Balance Sheet")}</a>
			{/if}
		{/tab_header_cell}
		{tab_header_cell}
			<a id="newtransferformanchor" rel="external" class="lms-ui-button" {if $customerinfo.deleted} disabled{/if}
				href="?m=customertransferform&id={$balancelist.customerid}&type={LMSTcpdfTransferForm::VALUE_ASSIGNMENTS}">{trans("Transfer form")}</a>
			<select name="newtransferform" onchange="javascript:new_transfer_form_type_changed()" form="addbalance-form"
				{if $customerinfo.deleted} disabled{/if}>
				<option value="{LMSTcpdfTransferForm::VALUE_ASSIGNMENTS}">{trans("<!transferform>assignments")}</option>
				<option value="{LMSTcpdfTransferForm::VALUE_BALANCE}">{trans("<!transferform>balance")}</option>
				<option value="{LMSTcpdfTransferForm::VALUE_CUSTOM}">{trans("<!transferform>custom")}</option>
			</select>
			<input type="text" name="newtransferformcustomvalue" pattern="[0-9]+(\.[0-9]{literal}{1,2}{/literal})?" size="5" style="display: none;" form="addbalance-form">
			{if ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
				<a id="newdocanchor" class="lms-ui-button" {if $customerinfo.deleted} disabled{/if}
					ref="?m=invoicenew&action=init&customerid={$balancelist.customerid}">{trans("New document")}</a>
				<select name="newdocument" onchange="javascript:new_doc_type_changed(this.options[this.selectedIndex].value)" form="addbalance-form"
					{if $customerinfo.deleted} disabled{/if}>
					<option value="?m=invoicenew&action=init&customerid={$balancelist.customerid}">{trans("invoice")}</option>
					<option value="?m=invoicenew&action=init&proforma=1&customerid={$balancelist.customerid}">{trans("pro forma invoice")}</option>
					<option value="?m=receiptadd&type=in&action=init&customerid={$balancelist.customerid}">{trans("cash-in receipt")}</option>
					<option value="?m=receiptadd&type=out&action=init&customerid={$balancelist.customerid}">{trans("cash-out receipt")}</option>
					<option value="?m=noteadd&action=init&customerid={$balancelist.customerid}">{trans("debit note")}</option>
				</select>
			{/if}
			{if  ConfigHelper::checkPrivilege('finances_management')}
				<A href="javascript:show_list()">{trans("Show All")}</A>
				<input type="hidden" value="{$balancelist.customerid}" name="customer">
				<SELECT name="showlist" id="showlistselect" form="addbalance-form">
					{if $limit}<OPTION value="list">{trans("transactions")}</OPTION>{/if}
					<OPTION value="invoice">{trans("invoices")}</OPTION>
					<OPTION value="invoicepro">{trans("pro forma invoices")}</OPTION>
					<OPTION value="note">{trans("debit notes")}</OPTION>
				</SELECT>
			{/if}
		{/tab_header_cell}
	{/tab_header}

	{tab_contents id="customerbalancepanel"}

		{tab_table}

			{$datatables_max_records=intval(ConfigHelper::getConfig('phpui.datatables_max_records', 0, true))}
			<TABLE id="customerbalancebox-datatable" class="lmsbox-inner{if !$datatables_max_records || empty($balancelist.list) || count($balancelist.list) < $datatables_max_records} lms-ui-datatable{else} lms-ui-background-cycle{/if}"
					{if !$datatables_max_records || empty($balancelist.list) || count($balancelist.list) < $datatables_max_records} data-page-length="{$n}"
					data-empty-table-message="{trans("That customer hasn't got any transactions.")}"
					data-display-start="{if empty($balancelist.list)}{$n = $limit}{else}{$n = count($balancelist.list) + $limit}{/if}{if $n < 0}0{else}{$n}{/if}" style="display: none;"{/if} width="100%">
				<COLGROUP>
					<COL style="width: 1%;">
					<COL style="width: 1%;">
					<COL style="width: 1%;">
					<COL style="width: 1%;">
					<COL style="width: 1%;">
					<COL style="width: 1%;">
					<COL style="width: 1%;">
					<COL style="width: 92%;">
					<COL style="width: 1%;">
				</COLGROUP>
				<THEAD>
				<TR>
					<TH>{trans("Date:")}</TH>
					<TH>{trans("User:")}</TH>
					<TH class="text-right" data-searchable="false">{trans("Liability:")}</TH>
					<TH class="text-right" data-searchable="false">{trans("Income:")}</TH>
					<TH class="text-right" data-searchable="false">{trans("Expense:")}</TH>
					<TH class="text-center" data-orderable="false" data-searchable="false">&raquo;</TH>
					<TH class="text-right" data-orderable="false" data-searchable="false">{trans("After:")}</TH>
					<TH data-orderable="false">{trans("Description:")}</TH>
					<TH data-orderable="false" data-searchable="false">&nbsp;</TH>
				</TR>
				</THEAD>
				<TBODY>
				{foreach $balancelist.list as $item}
				{if $datatables_max_records && count($balancelist.list) >= $datatables_max_records}
					{if $limit < 0 && $item@iteration <= count($balancelist.list) + $limit}
					{continue}
					{elseif $limit > 0 && $item@iteration > $limit}
					{continue}
					{/if}
				{/if}
				<TR{if $item.docid} data-published="{$item.published}" data-doctype="{$item.doctype}"
					data-senddate="{if $item.senddate}{$item.senddate|date_format:"Y-m-d H:i"}{else}{$item.senddate}{/if}"
					data-refdocs="{if empty($item.documentreferenced)}0{else}1{/if}"
					data-ksef="{if empty($item.ksefhash)}0{else}1{/if}"
					data-ksef-submit="{if empty($item.ksefsubmit)}0{else}1{/if}"
					class="{if $item.doctype == $smarty.const.DOC_INVOICE_PRO} teal{if $item.referenced} transformed{/if}{/if}
					{if $item.closed && ($item.doctype == $smarty.const.DOC_INVOICE || $item.doctype == $smarty.const.DOC_CNOTE || $item.doctype == $smarty.const.DOC_DNOTE)} blend{/if}"
					{/if}
					{if $item.value > 0 && $item.type} data-moveable="1"{/if}>
					<TD class="nobr" data-order="{$item@index}">{$item.date}</TD>
					<TD class="nobr">{$item.username|truncate:16:"&hellip;":true}</TD>
					<TD class="text-right nobr" data-order="{$item.value}">{if !$item.type}{Utils::formatMoney($item.value*-1, $item.currency)}{else}-{/if}</TD>
					<TD class="text-right nobr{if $item.type && $item.value > 0} green{/if}" data-order="{$item.value}">{if $item.type && $item.value > 0}+{Utils::formatMoney($item.value, $item.currency)}{else}-{/if}</TD>
					<TD class="text-right nobr" data-order="{$item.value}">{if $item.type && $item.value < 0}{Utils::formatMoney($item.value*-1, $item.currency)}{else}-{/if}</TD>
					<TD class="text-center">&raquo;</TD>
					<TD class="text-right nobr{if $item.after < 0} red{/if}">{Utils::formatMoney($item.after)}</TD>
					<TD class="comment"
						{if $item.doctype == $smarty.const.DOC_INVOICE && !empty($item.reference) && $aggregate_documents && !empty($item.documentcomment)} title="{$item.documentcomment}"{/if}
						>{$item.comment|escape}</TD>
					<TD class="text-right nobr">
						{foreach $item.customlinks as $link}
							<A {if isset($link.url)} href="{$link.url}" {/if} rel="external" {if isset($link.onclick)} onclick="{$link.onclick}"{/if}>{if isset($link.icon)}<IMG src="{$link.icon}" alt="{$link.label}" {$link.tip}>{else}{$link.label}{/if}</A>
							{if isset($link.extra)}{$link.extra}{/if}
						{/foreach}
						{if !empty($item.ksefhash)}
							{if !empty($item.ksefstatus) && ($item.ksefstatus < 200 || $item.ksefstatus >= 300)}
								{$class = "lms-ui-error"}
							{else}
								{$class = ""}
							{/if}
							{hint icon="lock" url="?m=invoiceksefinfo&id={$item.docid}" tooltip_class="lms-ui-ksef-qr-code" class=$class}
						{/if}
						{if $item.docid}
							{if $item.doctype == $smarty.const.DOC_INVOICE_PRO}
								{if  ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
									{button type="link" icon="transform" external=true
										href="?m=invoicenew&id={$item.docid}&action=init"
										tip="Convert to invoice"}
								{/if}
							{/if}
							{if ($customerinfo.sendinvoices || $balancelist.sendinvoices) && ($item.doctype == $smarty.const.DOC_INVOICE
								|| $item.doctype == $smarty.const.DOC_CNOTE || $item.doctype == $smarty.const.DOC_INVOICE_PRO
								|| $item.doctype == $smarty.const.DOC_DNOTE)}
								{if empty($item.ksefsubmission) || $item.ksefstatus == 200 || $offline_support && isset($item.ksefstatus) && $item.ksefstatus == 0}
									{textformat assign="tip" wrap=5000}
										{if $item.senddate}{trans("Send invoice again")}<br><strong>{t a=$item.senddate|date_format:"Y-m-d H:i"}(already sent on $a){/t}</strong>{else}{trans("Send invoice")}{/if}
									{/textformat}
									{button type="link" icon="{if $item.senddate}mailsent{else}mail{/if}" class="send-invoice"
										href="?m=invoicesend&id={$item.docid}" tip=$tip}
								{/if}
							{/if}
							{if $item.doctype == $smarty.const.DOC_INVOICE}
								{if !$item.cancelled}
									{if  ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
										{button type="link" icon="clone" href="?m=invoicenew&action=init&id={$item.docid}&clone=1"
											tip="Clone"}
										{button type="link" icon="correction" href="?m=invoicenote&id={$item.docid}&action=init"
											tip="Revise"}
									{/if}
								{/if}
								{if !$item.closed && !$item.cancelled && !$item.archived && !$item.referenced && (!$item.published || ConfigHelper::checkPrivilege('published_document_modification'))}
									{if  ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
										{textformat assign="onclick" wrap=5000}
											{if $item.published}
												confirmDialog($t('Document has been published already! Are you sure you want to edit it despite this?'), this)
													.done(function() {
														window.open($(this).attr('href'));
													});
											{else}
												window.open($(this).attr('href'));
											{/if}
											return false;
										{/textformat}
										{if empty($item.ksefhash) && empty($item.ksefsubmit)
											|| !empty($item.ksefstatus) && ($item.ksefstatus < 200 || $item.ksefstatus >= 300)}
											{button type="link" icon="edit" class="lms-ui-hint-rollover"
												href="?m=invoiceedit&id={$item.docid}&action=edit"
												onclick=$onclick
												data_url="?m=number&id={$item.docid}"
												icon_tip="Invoice"}
										{/if}
									{/if}
								{/if}
								{if !$item.cancelled}
									{if !$item.archived}
										{if ConfigHelper::checkPrivilege('trade_document_archiving')}
											{button type="link" icon="archive" href="?m=invoicearchive&id={$item.docid}" tip="Archive"}
										{/if}
									{else}
										{if ConfigHelper::checkPrivilege('trade_document_unarchiving')}
											{button type="link" icon="restore" href="?m=invoiceunarchive&id={$item.docid}" tip="Unarchive"}
										{/if}
									{/if}
								{/if}
								{if !$item.published || ConfigHelper::checkPrivilege('published_document_modification')}
									{button type="link" icon="view" class="print-invoice lms-ui-hint-rollover"
										href="?m=invoice&id={$item.docid}&dontpublish=1"
										data_url="?m=invoiceinfo&id={$item.docid}" icon_tip="View"}
								{/if}
								{button type="link" icon="print" class="print-invoice lms-ui-hint-rollover"
									href="?m=invoice&id={$item.docid}"
									data_url="?m=invoiceinfo&id={$item.docid}"
									icon_tip="Invoice"}
							{elseif $item.doctype == $smarty.const.DOC_INVOICE_PRO}
								{if !$item.cancelled && !$item.archived && (!$item.published || ConfigHelper::checkPrivilege('published_document_modification'))}
									{if  ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
										{textformat assign="onclick" wrap=5000}
											{if $item.published}
												confirmDialog($t('Document has been published already! Are you sure you want to edit it despite this?'), this)
													.done(function() {
														window.open($(this).attr('href'));
													});
											{else}
												window.open($(this).attr('href'));
											{/if}
											return false;
										{/textformat}
										{if empty($item.ksefhash) && empty($item.ksefsubmit)}
											{button type="link" icon="edit" class="lms-ui-hint-rollover"
												href="?m=invoiceedit&id={$item.docid}&action=edit&proforma=1"
												onclick=$onclick
												data_url="?m=number&id={$item.docid}"
												icon_tip="pro forma invoice"}
										{/if}
									{/if}
								{/if}
								{if !$item.cancelled}
									{if !$item.archived}
										{if ConfigHelper::checkPrivilege('trade_document_archiving')}
											{button type="link" icon="archive" href="?m=invoicearchive&id={$item.docid}" tip="Archive"}
										{/if}
									{else}
										{if ConfigHelper::checkPrivilege('trade_document_unarchiving')}
											{button type="link" icon="restore" href="?m=invoicunearchive&id={$item.docid}" tip="Unarchive"}
										{/if}
									{/if}
								{/if}
								{if !$item.published || ConfigHelper::checkPrivilege('published_document_modification')}
									{button type="link" icon="view" class="print-invoice lms-ui-hint-rollover"
										href="?m=invoice&id={$item.docid}&dontpublish=1"
										data_url="?m=invoiceinfo&id={$item.docid}"
										icon_tip="View"}
								{/if}
								{button type="link" icon="print" class="print-invoice lms-ui-hint-rollover"
									href="?m=invoice&id={$item.docid}"
									data_url="?m=invoiceinfo&id={$item.docid}"
									icon_tip="pro forma invoice"}
							{elseif $item.doctype == $smarty.const.DOC_CNOTE}
								{if !$item.cancelled && !$item.referenced}
									{if ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
										{button type="link" icon="correction" href="?m=invoicenote&id={$item.docid}&action=init"
											tip="Revise"}
									{/if}
								{/if}
								{if !$item.archived && !$item.referenced && (!$item.published || ConfigHelper::checkPrivilege('published_document_modification'))}
									{if  ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
										{if empty($item.ksefhash) && empty($item.ksefsubmit)}
											{textformat assign="onclick" wrap=5000}
												{if $item.published}
													confirmDialog($t('Document has been published already! Are you sure you want to edit it despite this?'), this)
													.done(function() {
													window.open($(this).attr('href'));
													});
												{else}
													window.open($(this).attr('href'));
												{/if}
												return false;
											{/textformat}
											{button type="link" icon="edit" class="lms-ui-hint-rollover"
												href="?m=invoicenoteedit&id={$item.docid}&action=edit"
												onclick=$onclick
												data_url="?m=number&id={$item.docid}"
												icon_tip="Invoice"}
										{/if}
									{/if}
								{/if}
								{if !$item.cancelled}
									{if !$item.archived}
										{if ConfigHelper::checkPrivilege('trade_document_archiving')}
											{button type="link" icon="archive" href="?m=invoicearchive&id={$item.docid}" tip="Archive"}
										{/if}
									{else}
										{if ConfigHelper::checkPrivilege('trade_document_unarchiving')}
											{button type="link" icon="restore" href="?m=invoiceunarchive&id={$item.docid}" tip="Unarchive"}
										{/if}
									{/if}
								{/if}
								{if !$item.published || ConfigHelper::checkPrivilege('published_document_modification')}
									{button type="link" icon="view" class="print-invoice lms-ui-hint-rollover"
										href="?m=invoice&id={$item.docid}&dontpublish=1"
										data_url="?m=number&id={$item.docid}"
										icon_tip="View"}
								{/if}
								{button type="link" icon="print" class="print-invoice lms-ui-hint-rollover"
									href="?m=invoice&id={$item.docid}"
									data_url="?m=number&id={$item.docid}"
									icon_tip="Credit note"}
							{elseif $item.doctype == $smarty.const.DOC_RECEIPT}
								{if  ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
									{button type="link" icon="edit" class="lms-ui-hint-rollover"
										href="?m=receiptedit&id={$item.docid}"
										data_url="?m=number&id={$item.docid}"
										external=true
										icon_tip="Cash receipt"}
									{button type="link" icon="print" class="lms-ui-hint-rollover"
										href="?m=receipt&id={$item.docid}"
										data_url="?m=number&id={$item.docid}"
										external=true
										icon_tip="Cash receipt"}
								{/if}
							{elseif $item.doctype == $smarty.const.DOC_DNOTE}
								{if !$item.cancelled && !$item.archived && (!$item.published || ConfigHelper::checkPrivilege('published_document_modification'))}
									{if  ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
										{textformat assign="onclick" wrap=5000}
											{if $item.published}
												confirmDialog($t('Document has been published already! Are you sure you want to edit it despite this?'), this)
													.done(function() {
														window.open($(this).attr('href'));
													});
											{else}
												window.open($(this).attr('href'));
											{/if}
											return false;
										{/textformat}
										{button type="link" icon="edit" class="lms-ui-hint-rollover"
											href="?m=noteedit&id={$item.docid}&action=edit"
											onclick=$onclick
											data_url="?m=number&id={$item.docid}"
											icon_tip="Invoice"}
									{/if}
								{/if}
								{if !$item.cancelled}
									{if !$item.archived}
										{if ConfigHelper::checkPrivilege('trade_document_archiving')}
											{button type="link" icon="archive" href="?m=notearchive&id={$item.docid}" tip="Archive"}
										{/if}
									{else}
										{if ConfigHelper::checkPrivilege('trade_document_unarchiving')}
											{button type="link" icon="restore" href="?m=noteunarchive&id={$item.docid}" tip="Unarchive"}
										{/if}
									{/if}

								{/if}
								{if !$item.published || ConfigHelper::checkPrivilege('published_document_modification')}
									{button type="link" icon="view" class="lms-ui-hint-rollover"
										href="?m=note&id={$item.docid}&dontpublish=1"
										data_url="?m=number&id={$item.docid}"
										external=true
										icon_tip="View"}
								{/if}
								{button type="link" icon="print" class="lms-ui-hint-rollover"
									href="?m=note&id={$item.docid}"
									data_url="?m=number&id={$item.docid}"
									external=true
									icon_tip="Debit note"}
							{/if}
						{/if}
						{if !empty($item.documentreferenced)}
							{button type="link" icon="more" class="all-attachment-toggle" tip="related documents"}
						{/if}
						<INPUT type="checkbox" form="addbalance-form"
								NAME="marks{if $aggregate_documents}{if $item.doctype == $smarty.const.DOC_INVOICE || $item.doctype == $smarty.const.DOC_INVOICE_PRO || $item.doctype == $smarty.const.DOC_CNOTE}[invoice][{$item.docid}]{elseif $item.doctype == $smarty.const.DOC_RECEIPT}[receipt][{$item.docid}]{elseif $item.doctype == $smarty.const.DOC_DNOTE}[note][{$item.docid}]{else}[{$item.id}]{/if}{else}{if $item.doctype == $smarty.const.DOC_INVOICE_PRO && !ConfigHelper::checkConfig('phpui.proforma_invoice_generates_commitment')}[proforma][{$item.docid}]{/if}[{$item.id}]{/if}"
								value="{$item.id}" class="lms-ui-multi-check">
						{if !empty($item.documentreferenced)}
							<div class="all-attachment-view">
								{foreach $item.refdocs as $docid => $refdoc}
									<div class="document-list">
										{if count($refdoc.attachments) == 1}
											<div class="document-title">
												{$attachment = reset($refdoc.attachments)}
												{$attachmentid = key($refdoc.attachments)}
												{capture assign="attachment_text"}{t a=$_DOCTYPES[$refdoc.type] b=$refdoc.fullnumber c=$refdoc.cdate|date_format:"Y-m-d"}$a no. $b issued on $c{/t}{/capture}
												{documentview
													id="{$docid}-{$attachmentid}"
													type=$attachment.contenttype
													name=$attachment.filename
													url="?m=documentview&id={$docid}&attachmentid={$attachmentid}"
													external=true
												}
												{if $attachment.type == -1}<i class="lms-ui-icon-user" title="<strong>{t a=date("Y/m/d H:i", $attachment.cdate)}Sent by customer at $a{/t}</strong>"></i>{/if}
											</div>
										{else}
											<div class="document-title">
												{t a=$_DOCTYPES[$refdoc.type] b=$refdoc.fullnumber c=$refdoc.cdate|date_format:"Y-m-d"}$a no. $b issued on $c{/t}
											</div>
											<div class="document-attachment-list">
												{foreach $refdoc.attachments as $attachmentid => $attachment}
													<div class="document-attachment">
														{documentview
															id="{$docid}-{$attachmentid}"
															type=$attachment.contenttype
															name=$attachment.filename
															url="?m=documentview&id={$docid}&attachmentid={$attachmentid}"
															external=true
														}
														{if $attachment.type == -1}<i class="lms-ui-icon-user" title="<strong>{t a=date("Y/m/d H:i", $attachment.cdate)}Sent by customer at $a{/t}</strong>"></i>{/if}
													</div>
												{/foreach}
											</div>
										{/if}
									</div>
								{/foreach}
							</div>
						{/if}
					</TD>
				</TR>
				{/foreach}
				</TBODY>
			</TABLE>

		{/tab_table}

		{tab_button_panel}

			{tab_buttons}
				{if ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
					{if ConfigHelper::checkConfig('phpui.delete_link_in_customerbalancebox')}
						{button icon="delete" id="delete-invoices" label="Delete"}
					{/if}
					{button icon="transfer" id="move-balances" label="<!balance>Transfer"}
				{/if}
				{button icon="mail" id="send-invoices" label="Send invoices"}
				{if ConfigHelper::checkPrivilege('trade_document_archiving')}
					{button icon="archive" id="archive-invoices" label="Archive"}&nbsp;
				{/if}
				{if ConfigHelper::checkPrivilege('trade_document_uarchiving')}
					{button icon="restore" id="unarchive-invoices" label="Unarchive"}&nbsp;
				{/if}
				{trans("Print")}:
				{button icon="print" label="invoices" id="print-invoices"}
				{button icon="cash" label="cash receipt" id="print-receipts"}
				{button icon="dnote" label="debit notes" id="print-notes"}
				<label>
					<INPUT type="checkbox" form="addbalance-form" name="which[{$smarty.const.DOC_ENTITY_ORIGINAL}]"
							value="{$smarty.const.DOC_ENTITY_ORIGINAL}"
							{if preg_match('/original/i', $default_printpage)} checked{/if}>
					{$_DOCENTITIES[$smarty.const.DOC_ENTITY_ORIGINAL]}
				</label>
				<label>
					<INPUT type="checkbox" form="addbalance-form" name="which[{$smarty.const.DOC_ENTITY_COPY}]"
							value="{$smarty.const.DOC_ENTITY_COPY}"
							{if preg_match('/copy/i', $default_printpage)} checked{/if}>
					{$_DOCENTITIES[$smarty.const.DOC_ENTITY_COPY]}
				</label>
				<div id="duplicate-box">
					<label>
						<INPUT type="checkbox" form="addbalance-form" name="which[{$smarty.const.DOC_ENTITY_DUPLICATE}]" id="duplicate-checkbox"
								value="{$smarty.const.DOC_ENTITY_DUPLICATE}"
								{if preg_match('/duplicate/i', $default_printpage)} checked{/if}>
						{$_DOCENTITIES[$smarty.const.DOC_ENTITY_DUPLICATE]}
					</label>
					<div id="duplicate-box-date-selector"
							{if !preg_match('/duplicate/i', $default_printpage)} style="display: none;"{/if}>
						<input type="text" form="addbalance-form" name="duplicate-date" class="lms-ui-date lms-ui-date-unix">
					</div>
				</div>
			{/tab_buttons}

			{tab_buttons}
				<label>
					{trans("Check All")}
					<INPUT type="checkbox" class="lms-ui-multi-check-all">
				</label>
			{/tab_buttons}

		{/tab_button_panel}

		{if  ConfigHelper::checkPrivilege('financial_operations') || ConfigHelper::checkPrivilege('finances_management')}
			{tab_button_panel}
				{tab_buttons}
					<div class="addbalance-form-cell">
						<INPUT type="hidden" form="addbalance-form" name="addbalance[customerid]" value="{$balancelist.customerid}">
						<INPUT type="text" form="addbalance-form" name="addbalance[time]" size="15" maxlength="16" {tip class="lms-ui-datetime" text="Enter transaction time in 'yyyy/mm/dd hh:mm' format (empty field means current time). Click to select date from calendar."} {if $time}value="{$time|date_format:"Y/m/d H:i"}"{/if}>
						{$layout.logname|truncate:16:"&hellip;":true}
						<INPUT type="text" size="8" form="addbalance-form" name="addbalance[value]" accesskey="s" {if $value}value="{$value}"{/if} {tip text="Enter transaction value"}>&nbsp;
						{currency_selection selected=Localisation::getDefaultCurrency() elementname="addbalance[currency]" form="addbalance-form"}
						<SELECT SIZE="1" form="addbalance-form" name="addbalance[taxid]" {tip text="Select Tax value"}>
							{foreach $taxeslist as $tax}
								<option value="{$tax.id}"
									{if $taxid && $tax.id == $taxid
										|| (!$taxid && (isset($default_taxlabel) && $tax.label == $default_taxlabel
											|| !isset($default_taxlabel) && $tax.value == $default_taxrate))} selected{/if}
									>{$tax.label}</option>
							{/foreach}
						</SELECT>
					</div>

					<div class="addbalance-form-cell">
						<label>
							<INPUT type="radio" form="addbalance-form" NAME="addbalance[type]" value="0" {tip text="Select type of operation"}>
							{trans("liability")}
						</label>
						<label>
							<INPUT type="radio" form="addbalance-form" NAME="addbalance[type]" value="1" {tip text="Select type of operation"} checked>
							{trans("income/expense")}
						</label>
						<div class="servicetype">
							{icon name="money"}
							<select id="servicetype" name="addbalance[servicetype]" form="addbalance-form" {tip text="Service type"}>
								<option value="">{trans("— none —")}</option>
								{foreach Localisation::arraySort($_SERVICETYPES) as $type => $label}
									<option value="{$type}"{if $servicetype == $type} selected{/if}>{$label}</option>
								{/foreach}
							</select>
						</div>
						{if $sourcelist}
						<div class="isource">
							<i class="lms-ui-icon-isource fa-fw"></i>
							<select form="addbalance-form" name="addbalance[sourceid]" {tip text="Select import source (optional)" trigger="source"}>
								<option value="-1">{trans("<!cash-source>— default —")}</option>
								<option value="0">{trans("— none —")}</option>
								{foreach $sourcelist as $source}
									<option value="{$source.id}"{if $source.id == $sourceid} selected{/if}>{$source.name}</option>
								{/foreach}
							</select>
						</div>
						{/if}
					</div>

					<div class="addbalance-form-cell">
						<input type="text" form="addbalance-form" size="30" name="addbalance[comment]" value="{$comment}" {tip text="Enter short description of transaction"}>
					</div>
				{/tab_buttons}
			{/tab_button_panel}
			{tab_button_panel}
				{tab_buttons}
					{if $customerinfo.balance < 0}
						{button icon="edit" id="clear-account" label="Clear Account"}
					{/if}
				{/tab_buttons}

				{tab_buttons}
					<label>
						<input type="hidden" form="addbalance-form" name="addbalance[notification]" value="0">
						<input type="checkbox" form="addbalance-form" name="addbalance[notification]" value="1"
							{if !empty($notification)} checked{/if}>
						{trans("Notify customer")}
					</label>
					{if $instantpayment}
						{button icon="cash" onclick="javascript:AddBalance(true);" label="Instant payment"}
					{/if}
					{button icon="save" onclick="javascript:AddBalance();" label="Submit"}
				{/tab_buttons}

			{/tab_button_panel}
		{/if}
	{/tab_contents}
{/tab_container}

<form method="POST" id="transfer-balance-form" action="?m=customerbalancetransfer">
</form>

<style>

	#transfer-balance-dialog {
		overflow: visible;
		display: none;
	}

	ol.dialog-box {
		list-style: none;
		padding-left: 0;
		width: 90%;
	}
	ol.dialog-box li {
		padding-bottom: 5px;
	}

	#transfer-balance-dialog-value-field {
		display: flex;
		flex-direction: column;
		width: fit-content;
	}

	#transfer-balance-dialog-value-field > * {
		margin-left: 0;
	}

	#transfer-balance-dialog-value-field > *:not(:first-child) {
		margin-top: 0.5em;
	}

</style>

<div id="transfer-balance-dialog" class="lms-ui-dialog" title="{trans("Financial operation transfer")}">
	<ol class="dialog-box">
		<li>
			<strong>{trans("Customer")}</strong>
			{customerlist
				customers=$customers
				form="transfer-balance-form"
				selectname="customer-select"
				inputname="customerid"
				selecttip=""
				inputtip=""
				required=true
				version=2}
		</li>
		<li id="transfer-balance-dialog-value-field" style="display: none;">
			<strong>{trans("Value")}</strong>
			<span>
				<input type="text" size="8" name="value" pattern="[0-9]+([\.,][0-9]+)?"
					form="transfer-balance-form">
				{currency_selection selected=Localisation::getDefaultCurrency() elementname="currency" form="transfer-balance-form"}
			</span>
		</li>
	</ol>
	<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
		<div class="ui-dialog-buttonset">
			{button type="submit" class="lms-ui-button ui-button ui-corner-all ui-widget" icon="apply"
				id="transfer-balance-apply-button" label="Apply" form="transfer-balance-form"}
			{button class="lms-ui-button ui-button ui-corner-all ui-widget" icon="cancel"
				id="transfer-balance-cancel-button" label="Cancel" form="transfer-balance-form"}
		</div>
	</div>
</div>

<script>

{if !$limit}
	$('#customerbalancepanel').show();
{/if}

	function AddBalance(with_receipt) {
		if (document.forms['addbalance'].elements['addbalance[value]'].value == '') {
			alertDialog($t("Enter transaction value") + '!');
			return;
		}
		if (document.forms['addbalance'].elements['addbalance[comment]'].value == '') {
			alertDialog($t("Enter transaction comment") + '!');
			return;
		}
		if (typeof(with_receipt) == 'boolean' && with_receipt)
			document.addbalance.action += '&receipt=1';
		document.addbalance.submit();
	}

	$('#print-receipts').click(function() {
		if (!$('tr[data-doctype="{$smarty.const.DOC_RECEIPT}"] :checked').length) {
			alertDialog($t('No document of given type has been selected!'), this);
			return;
		}

		var add = "";
		var which = 0;
		$('[form="addbalance-form"][name^="which"]:checked').each(function() {
			which += parseInt($(this).val());
		});
		add += "&which=" + which;

		document.addbalance.action = "?m=receipt&print=cached&cash=1" + add;
		document.addbalance.target = "_blank";
		document.addbalance.submit();
	});

	$('.print-invoice').click(function() {
		var add = "";
		var which = 0;
		$('[form="addbalance-form"][name^="which"]:checked').each(function() {
			which += parseInt($(this).val());
		});
		add += "&which=" + which;
		if (which & {$smarty.const.DOC_ENTITY_DUPLICATE}) {
			var duplicate_date = parseInt($('[name="duplicate-date"]').val());
			if (duplicate_date > 0) {
				add += "&duplicate-date=" + duplicate_date;
			}
		}

		window.open($(this).attr('href') + add);
		return false;
	});

	$('#print-invoices,#print-notes').click(function() {
		var print_invoices = $(this).is('#print-invoices');
		if ((print_invoices && !$('tr[data-doctype="{$smarty.const.DOC_INVOICE}"] :checked').length
			&& !$('tr[data-doctype="{$smarty.const.DOC_CNOTE}"] :checked').length)
			|| (!print_invoices && !$('tr[data-doctype="{$smarty.const.DOC_DNOTE}"] :checked').length)) {
			alertDialog($t('No document of given type has been selected!'), this);
			return;
		}

		function print_doc(type) {
			var add = "";
			var which = 0;
			$('[form="addbalance-form"][name^="which"]:checked').each(function() {
				which += parseInt($(this).val());
			});
			add += "&which=" + which;
			if (which & {$smarty.const.DOC_ENTITY_DUPLICATE}) {
				var duplicate_date = parseInt($('[name="duplicate-date"]').val());
				if (duplicate_date > 0) {
					add += "&duplicate-date=" + duplicate_date;
				}
			}

			document.addbalance.action="?m=" + type + "&print=cached&cash=1" + add;
			document.addbalance.target="_blank";
			document.addbalance.submit();
		}

		print_doc(print_invoices ? 'invoice' : 'note');
	});

	function show_list()
	{
		var type = document.getElementById('showlistselect').value;

		if (type == 'invoice')
			document.addbalance.action = '?m=invoicelist&customer={$balancelist.customerid}';
		else if (type == 'invoicepro')
			document.addbalance.action = '?m=invoicelist&proforma=1&customer={$balancelist.customerid}';
		else if (type == 'note')
			document.addbalance.action = '?m=notelist';
		else {
			window.location.assign('?m=customerbalance&id={$balancelist.customerid}');
			return;
		}

		document.addbalance.target = '';
		document.addbalance.submit();
	}

	function new_doc_type_changed(url) {
		document.getElementById('newdocanchor').href = url;
	}

	function new_transfer_form_type_changed() {
		var type = $('[name="newtransferform"]').val();
		$('#newtransferformanchor').attr('href', '?m=customertransferform&id={$balancelist.customerid}&type=' + type +
			'&value=' + $('[name="newtransferformcustomvalue"]').val());
		if (type == {LMSTcpdfTransferForm::VALUE_CUSTOM}) {
			$('[name="newtransferformcustomvalue"]').show().focus();
		} else {
			$('[name="newtransferformcustomvalue"]').hide();
		}
	}

	$(function() {
		$('[name="newtransferformcustomvalue"]').on('change keypress', function() {
			setTimeout(function() {
				$('#newtransferformanchor').attr('href', '?m=customertransferform&id={$balancelist.customerid}&type=' +
					$('[name="newtransferform"]').val() + '&value=' + $('[name="newtransferformcustomvalue"]').val());
			}, 1);
		});

		// don't allow to trigger click event on title bar
		$('#aggregate_document_label').click(function(e) {
			e.stopPropagation();
		});

		$('[name="aggregate_documents"]:checkbox').click(function() {
			location.href = '?m={$layout.module}&id={$objectid}&aggregate_documents=' +
				($(this).prop('checked') ? '1' : '0');
		});

		$('[name="addbalance[type]"]').change(function() {
			var that = this;
			$('#servicetype').prop('disabled', function() {
				return $(that).val() == '1';
			});
		}).change();
	});

	{if ConfigHelper::checkConfig('phpui.delete_link_in_customerbalancebox')}
	$('#delete-invoices').click(function() {
		if (!$(this).closest('.lms-ui-multi-check').find('input.lms-ui-multi-check:checked').length) {
			return;
		}

		if ($('tr[data-published="1"] :checked').length) {
			{if ConfigHelper::checkPrivilege('published_document_modification')}
			confirmDialog($t("Some documents have been published already! Are you sure you want to delete them despite this?"), this)
				.done(function () {
					confirmDialog($t("Are you sure, you want to delete selected operation(s) and document item(s)?"), this)
						.done(function () {
							if ($('tr[data-refdocs="1"] :checked').length) {
								confirmDialog($t("Are you sure, you want to also remove related documents?"), this)
									.done(function () {
										document.addbalance.action = "?m=balancedel&documents=1";
										document.addbalance.target = "";
										document.addbalance.submit();
									}).fail(function () {
										document.addbalance.action = "?m=balancedel";
										document.addbalance.target = "";
										document.addbalance.submit();
									});
							} else {
								document.addbalance.action = "?m=balancedel";
								document.addbalance.target = "";
								document.addbalance.submit();
							}
						});
				});
			return;
			{else}
			alertDialog($t("Some documents have been published already!"), this);
			return;
			{/if}
		}

		confirmDialog($t("Are you sure, you want to delete selected operation(s) and document item(s)?"), this)
			.done(function() {
				if ($('tr[data-refdocs="1"] :checked').length) {
					confirmDialog($t("Are you sure, you want to also remove related documents?"), this)
						.done(function () {
							document.addbalance.action = "?m=balancedel&documents=1";
							document.addbalance.target = "";
							document.addbalance.submit();
						}).fail(function () {
							document.addbalance.action = "?m=balancedel";
							document.addbalance.target = "";
							document.addbalance.submit();
						});
				} else {
					document.addbalance.action = "?m=balancedel";
					document.addbalance.target = "";
					document.addbalance.submit();
				}
			});
	});
	{/if}

	$('.send-invoice').click(function(e) {
		var senddate = $(this).closest('tr').attr('data-senddate');
		if (parseInt(senddate) === 0) {
			confirmDialog($t('Are you sure, you want to send invoice to customer \'$a\'?', '{$customerinfo.customername|escape:"javascript"|escape:"html"}'), this)
				.done(function() {
					var add = "";
					var which = 0;
					$('[form="addbalance-form"][name^="which"]:checked').each(function() {
						which += parseInt($(this).val());
					});
					add += "&which=" + which;
					if (which & {$smarty.const.DOC_ENTITY_DUPLICATE}) {
						var duplicate_date = parseInt($('[name="duplicate-date"]').val());
						if (duplicate_date > 0) {
							add += "&duplicate-date=" + duplicate_date;
						}
					}
					window.open($(this).attr('href') + add);
				});
		} else {
			confirmDialog($t("Invoice was sent to customer '$a' already on $b. Are you sure, you want to send invoice again?", '{$customerinfo.customername|escape:"javascript"|escape:"html"}', senddate), this)
			.done(function() {
					var add = "";
					var which = 0;
					$('[form="addbalance-form"][name^="which"]:checked').each(function() {
						which += parseInt($(this).val());
					});
					add += "&which=" + which;
					if (which & {$smarty.const.DOC_ENTITY_DUPLICATE}) {
						var duplicate_date = parseInt($('[name="duplicate-date"]').val());
						if (duplicate_date > 0) {
							add += "&duplicate-date=" + duplicate_date;
						}
					}
					window.open($(this).attr('href') + add);
				});
		}
		return false;
	});

	$('#send-invoices').click(function() {
		if (!$('tr[data-doctype="{$smarty.const.DOC_INVOICE}"] :checked').length
				&& !$('tr[data-doctype="{$smarty.const.DOC_CNOTE}"] :checked').length
				&& !$('tr[data-doctype="{$smarty.const.DOC_DNOTE}"] :checked').length) {
			alertDialog($t('No document of given type has been selected!'), this);
			return;
		}

		confirmDialog($t("Are you sure, you want to send invoices to customer?"), this).done(function() {
			var add = "";
			var which = 0;
			$('[form="addbalance-form"][name^="which"]:checked').each(function() {
				which += parseInt($(this).val());
			});
			add += "&which=" + which;
			if (which & {$smarty.const.DOC_ENTITY_DUPLICATE}) {
				var duplicate_date = parseInt($('[name="duplicate-date"]').val());
				if (duplicate_date > 0) {
					add += "&duplicate-date=" + duplicate_date;
				}
			}

			document.addbalance.action="?m=invoicesend&marks=cash" + add;
			document.addbalance.target="_blank";
			document.addbalance.submit();
		});
	});

	$('#archive-invoices').click(function() {
		if (!$('tr[data-doctype="{$smarty.const.DOC_INVOICE}"] :checked').length
				&& !$('tr[data-doctype="{$smarty.const.DOC_CNOTE}"] :checked').length
				&& !$('tr[data-doctype="{$smarty.const.DOC_DNOTE}"] :checked').length) {
			alertDialog($t('No document of given type has been selected!'), this);
			return;
		}

		confirmDialog($t("Are you sure, you want to archive selected documents?"), this).done(function() {
			document.addbalance.action="?m=invoicearchive&marks=cash";
			document.addbalance.target="";
			document.addbalance.submit();
		});
	});

	$('#unarchive-invoices').click(function() {
		if (!$('tr[data-doctype="{$smarty.const.DOC_INVOICE}"] :checked').length
				&& !$('tr[data-doctype="{$smarty.const.DOC_CNOTE}"] :checked').length
				&& !$('tr[data-doctype="{$smarty.const.DOC_DNOTE}"] :checked').length) {
			alertDialog($t('No document of given type has been selected!'), this);
			return;
		}

		confirmDialog($t("Are you sure, you want to unarchive selected documents?"), this).done(function() {
			document.addbalance.action="?m=invoiceunarchive&marks=cash";
			document.addbalance.target="";
			document.addbalance.submit();
		});
	});

	$('#clear-account').click(function() {
		confirmDialog($t("Are you sure, you want to account ALL debts of customer '$a'?", '{$customerinfo.customername|escape:"javascript"|escape:"html"}'), this)
			.done(function() {
				location.href = '?m=customerbalanceok&id={$customerinfo.id}';
			});
	});

	$('#duplicate-checkbox').click(function() {
		$('#duplicate-box-date-selector').toggle($(this).prop('checked'));
	});

	$(function() {
		$('.all-attachment-toggle').click(function() {
			var attachmentView = $(this).siblings('.all-attachment-view');
			attachmentView.toggle();
			$(this).find('i').attr('class', 'lms-ui-icon-' + (attachmentView.is(':visible') ? 'less' : 'more'));
		});""

/*
		$('#customerbalancebox .lms-ui-multi-check,.lms-ui-multi-check-all').change(function() {
			$('#move-balances').prop('disabled', !$('#customerbalancebox .lms-ui-multi-check:checked').closest('[data-moveable]').length);
		});
*/

		var transfer_balance_dialog = new LmsUiDialog('transfer-balance-dialog', {
			position: {
				my: "left bottom",
				at: "top right",
				of: $('#move-balances')
			}
		});
		$('#transfer-balance-cancel-button').click(function() {
			transfer_balance_dialog.handler.dialog("close");
		});

		{if !empty($balancelist.customerid)}
			$('#transfer-balance-form').submit(function() {
				var checkboxes = $('#customerbalancebox [data-moveable] .lms-ui-multi-check:checked');
				var value = parseFloat($('#transfer-balance-dialog-value-field input').val().replace(',', '.'));
				var currency = $('#transfer-balance-dialog-value-field select').val();
				var valueVisible = $('#transfer-balance-dialog-value-field').is(':visible');
				var old_customerid = {$balancelist.customerid};
				var customerid = parseInt($('[name="customerid"][form="transfer-balance-form"]').val());
				if (!valueVisible && !checkboxes.length || valueVisible && (isNaN(value) || !currency.length) || customerid == old_customerid) {
					$('#transfer-balance-apply-button').prop('disabled', false);
					return false;
				}
				var html = '<input type="hidden" name="old-customerid" value="' + old_customerid + '">';
				$.each(checkboxes, function() {
					html += '<input type="hidden" name="marks[]" value="' + $(this).val() + '">';
				});
				$(this).html(html);
			});
		{/if}

		//$('#move-balances').prop('disabled', !$('#customerbalancebox .lms-ui-multi-check:checked').closest('[data-moveable]').length)
		$('#move-balances').click(function() {
			var valueRequired = !$('#customerbalancebox .lms-ui-multi-check:checked').closest('[data-moveable]').length;
			$("#transfer-balance-dialog-value-field").toggle(valueRequired).find('input,select').prop('required', valueRequired);
			transfer_balance_dialog.open();
		});
	});

	new_doc_type_changed($('[name="newdocument"]').val());

</script>
