

<?php $__env->startSection('title'); ?>
@parent
Операции :: Бюджет для "<?php echo $workProject->name; ?>"
<?php $__env->stopSection(); ?>

<?php $__env->startSection('breadcrumbs'); ?>
	<?php echo Breadcrumbs::render('budget.operations', $workProject); ?>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('modals'); ?>
	<?php echo $__env->make('budget/operations/modal', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('css'); ?>
	<link rel="stylesheet" href="<?php echo asset('css/bootstrap-validator.min.css'); ?>">
<?php $__env->stopSection(); ?>

<?php $__env->startSection('js'); ?>
	<script src="<?php echo asset('js/plugin/x-editable/x-editable.min.js'); ?>"></script>
	<script src="<?php echo asset('js/plugin/bootstrapvalidator/bootstrapValidator.min.js'); ?>"></script>
	<script src="<?php echo asset('js/kmk-support.js'); ?>"></script>
	<script src="<?php echo asset('js/budget.js'); ?>"></script>
	<script>
		function initEditable() {
			$('.editable-date').editable({
				url: '/budget/operations/update',
				mode: 'inline',
        combodate: {
                maxYear: new Date().getFullYear()
           }
			});      
			$('.editable-comment').editable({
				url: '/budget/operations/update',
				emptytext: 'Нет',
				mode: 'inline'
			});
			$('.editable-select-type').editable({
				url: '/budget/operations/update',
				mode: 'inline',
				source: [
					{ value: <?php echo BudgetOperation::TYPE_INCOMING; ?>, text: 'Приход' },
					{ value: <?php echo BudgetOperation::TYPE_OUTCOMING; ?>, text: 'Расход' },
					{ value: <?php echo BudgetOperation::TYPE_EXCHANGE; ?>, text: 'Перевод' },
					{ value: <?php echo BudgetOperation::TYPE_OPENING_BALANCE; ?>, text: 'Остатки на начало месяца' },
					{ value: <?php echo BudgetOperation::TYPE_OPENING_DEBT_IN; ?>, text: 'Мы должны на начало месяца' },
					{ value: <?php echo BudgetOperation::TYPE_OPENING_DEBT_OUT; ?>, text: 'Долг нам на начало месяца' }
				]
			});
			$('.editable-select-account').editable({
				url: '/budget/operations/update',
				mode: 'inline',
        emptytext: 'Выберите счет',
				source: [
					<?php foreach($accounts as $key=>$value): ?>
					{ value: <?php echo $key; ?>, text: "<?php echo str_replace('"', '\"', $value); ?>" },
					<?php endforeach; ?>
				]
			});
			$('.editable-select-partner').editable({
				url: '/budget/operations/update',
				mode: 'inline',
				source: [
					<?php foreach($partners as $key=>$value): ?>
					{ value: <?php echo $key; ?>, text: "<?php echo str_replace('"', '\"', $value); ?>" },
					<?php endforeach; ?>
				]
			});
			$('.editable-select-cost').editable({
				url: '/budget/operations/update',
				emptytext: 'Нет',
				mode: 'inline',
				source: [
					<?php foreach($groups as $group): ?>
					{ text: "<?php echo $group->name; ?>", children: [
            <?php if( isset($costsArr[$group->id]) ): ?>
              <?php foreach($costsArr[$group->id] as $costToSelect): ?>
                { value: <?php echo $costToSelect->id; ?>, text: "<?php echo $costToSelect->name; ?>" },
              <?php endforeach; ?>
            <?php endif; ?>
            ]
					},
				  <?php endforeach; ?>
		    ]
			});
			$('.editable-select-amount').editable({
				url: '/budget/operations/update',
				mode: 'inline'
			}).on('hidden', function(e, reason) {
				if(reason === 'save') {
					$(this).html(humanizeNumber($(this).html()));
				}
			});

			$('.editable').on('save', function(e, params) {
				if (params.response.status == 'success') {
					if (params.response.operation) {
						$('#budgetOperation'+params.response.id).replaceWith(params.response.operation);
						$('#budgetOperation'+params.response.id + ' a.to-humanize').each(function() {
							$(this).html(humanizeNumber($(this).html()));
						});
						initEditable();
						initDeleteRestore();
					}
				}
			});
		}

		//удаление/восстановление операции
		function initDeleteRestore() {
			$('.budget-operations-restore, .budget-operations-delete, .budget-operations-noincome, .budget-operations-transit').unbind('click').on('click', function(){
				var l = Ladda.create(this);
				l.start();
				var btn = this;
						$.post(
								$(this).data('action'),
								{
									'operationId': $(this).data('id'),
									'child_deleted_id': $(this).closest('td').data('child-deleted-id')
								},
								function(data) {
									if (data.status === 'success') {
										$('#budgetOperation'+data.id).replaceWith(data.operation);
										$('#budgetOperation'+data.id + ' a.to-humanize').each(function() {
											$(this).html(humanizeNumber($(this).html()));
										});
										if(data.child_deleted_id != null){
										  $('.budget-operation-delete').data('child-deleted-id', data.child_deleted_id);
										}
										initEditable();
										initDeleteRestore();
									}
								},
								'json'
								).always(function() { l.stop(); });
				return false;
			});
			//---------------------------------------------------------------------------------------//
			function getDualOperations(){
				var container = $('#budgetDebtOperationsContainer'),
						operationId,
						debtForm = $('#debtForm').serialize(),
						current = $('#debtForm'),
						debProjectName;
						
		        debtForm += '&debet-project-id='+$('#debtModal').find('#debt_partner_id').find('[value='+$('#debt_partner_id').val()+']').data('debet-project-id');
						$.post(
								'<?php echo action('BudgetController@getDualOperationDebt'); ?>',
								debtForm,
								function(data) {
									if (data.status == 'success') {
										container.html(data.operation);
										
										current.find('#debt_partner_id').removeClass('hide'); // переключение вида отображения долгового контрагента
										current.find('.debt-partner-block .debt-partner-name').html(debProjectName).addClass('hide'); //
										
										if (data.operation == '') {
										  current.find('#dualOperationBlock').addClass('hide');
											if(current.find('#isdebt').prop('checked')){
												current.find('#createDualOperationBlock').removeClass('hide');
											}
										}else{
											current.find('#dualOperationBlock').removeClass('hide');
											container.removeClass('hide');
											if(data.isCheckedOperation){
											  current.find('#createDualOperationBlock').addClass('hide');
											  current.find('.budgetOperationsTable').removeClass('hide');
												current.find('#dualOperationAdd').prop('checked', true);
												
												current.find('#debt_partner_id').addClass('hide');
												debProjectName = current.find('#debt_partner_id').find('[value='+$('#debt_partner_id').val()+']').html();
												current.find('.debt-partner-block .debt-partner-name').html(debProjectName).removeClass('hide');
												
											}else{
												if(current.find('#isdebt').prop('checked')){
											    current.find('#createDualOperationBlock').removeClass('hide');
											  }
				              }
										}
										debPartnersAccounts();
										setDualAccount( current.find('#debt_partner_id').find('[value='+$('#debt_partner_id').val()+']').data('debet-project-id') , current.find('#operationAccount').data('account-name'));
									}
								},
								'json'
								);
			}
   //-----------------------------------------------------------------------------------------------------------//
			$('.budget-operations-debt').on('click', function(){
				var l = Ladda.create(this);
				l.start();
				var btn = this,
				    createDualOperationBlock = $('#createDualOperationBlock');
						$.post(
								'<?php echo action('BudgetController@getOperationDebt'); ?>',
								{
									'operationId': $(this).data('id')
								},
								function(data) {
									if (data.status === 'success') {
										$('#debt_operation_id').val(data.operation.id);
										if (data.operation.isdebt) {
											$('#isdebt').prop('checked', true);
											$('#debt_partner_id').val(data.operation.debt_partner_id);
											$('#debt_comment').val(data.operation.debt_comment);
										}
										else {
											$('#isdebt').prop('checked', false);
											$('#debt_partner_id').val(0);
											$('#debt_comment').val('');
										}
										$('#operationAccount').data('account-name', data.accountName);
										$('#operationAccount').html(data.accountNameView);
										// список связанных операций
										getDualOperations();
										checkDualDebetPartner();
										createDualOperationBlock.addClass('hide');
										createDualOperationBlock.find('#dualOperationCreate').prop('checked', false);
										createDualOperationBlock.find('.accounts').addClass('hide');
										$('#debtModal').modal('show');
									}
								},
								'json'
								).always(function() { l.stop(); });
				return false;
			});
			
			$('#debtForm').on('change','#debt_partner_id', function(){
				if( $('#debtForm').find('#isdebt').prop('checked') ){
				  getDualOperations();
				}else{
				  $('#budgetDebtOperationsContainer').empty();
					$('#createDualOperationBlock').addClass('hide');
				}
				checkDualDebetPartner();
			});
			$('#debtForm').on('change','#isdebt', function(){
				if( $(this).prop('checked') ){
				  getDualOperations();
				}else{
				  $('#budgetDebtOperationsContainer').empty();
					$('#createDualOperationBlock').addClass('hide');
					$('#debtForm').find('#dualOperationAdd').prop('checked', false)
				}
			});
			// подсветка выбранной зеркальной операции
			$('#budgetDebtOperationsContainer').on('click','.check-deb-operation', function(){
				var current = $(this),
				    container = $('#budgetDebtOperationsContainer');
				if( current.prop('checked') ){
					container.find('tr').removeClass('info');
					container.find('.check-deb-operation').prop('checked', false);
					current.closest('tr').addClass('info');
					current.prop('checked', true);
					$('#debtForm').find('#dualOperationAdd').prop('checked', true)
				}else {
					current.closest('tr').removeClass('info');
					$('#debtForm').find('#dualOperationAdd').prop('checked', false)
				}
			});

			$('#budgetOperationsContainer tr')
							.mouseover(function(){
								$(this).find('button.budget-operations-restore, button.budget-operations-delete, .budget-operations-debt, .budget-operations-noincome, .budget-operations-transit, .budget-operations-salary').stop().fadeIn('normal');
							})
							.mouseout(function(){
								$(this).find('button.budget-operations-restore, button.budget-operations-delete, .budget-operations-debt, .budget-operations-noincome, .budget-operations-transit, .budget-operations-salary').stop().fadeOut('fast');
							})
		}

		function reload () {
			var params = kmkGiveGetParams(location.search);
			params['startDate'] = $('#startDate').val();
			params['endDate'] = $('#endDate').val();
			kmkSetBrowserAddressParams(kmkObjectToGetString(params, false));
			location.reload();
		}

											// -- окно управления долговой операцией -- //
		// показ списка счетов для зеркальной операции в окне управления долговой операцией
		function debPartnersAccounts(){
			$('#debtForm').find('#debPartnerAccounts').find('.deb-partners-accounts').addClass('hide');
			var current = $('#debt_partner_id'),
					sourceList = current.closest('#debtForm').find('#debPartnerAccounts'),
					selectedProjectId = current.find('[value='+current.val()+']').data('debet-project-id');

      if(selectedProjectId == 0){
				$('#createDualOperationBlock').addClass('hide');
				$('#createDualOperationBlock').find('#dualOperationCreate').prop('checked', false);
			}else{
				sourceList.find('.project_id-'+selectedProjectId).removeClass('hide');
				var del = sourceList.find('.project_id-'+selectedProjectId);
				del.detach();
				sourceList.prepend(del);
			}
		}
		// устанавливает счет для зеркальной операции в окне управления долговой операцией
		function setDualAccount(projectId, accName){
			var sourceList = $('#debPartnerAccounts'),
					account = sourceList.find('.project_id-'+projectId+'.account-name-'+accName);

			if(accName && account.val()){
			account.attr('selected','selected');
			sourceList.val(account.val());
			}else{
				sourceList.find('.default').attr('selected','selected');
				sourceList.val('0');
			}
		}
		// проверяет создан ли у выбранного долгового агента текущий проект в качестве долгового агента
		// выводит ошибки, если нет
		function checkDualDebetPartner(){
			var current = $('#debt_partner_id'),
					dualDebtPartnerId = current.find('[value='+current.val()+']').data('dual-debt-partner-id'),
					debtProjectId = current.find('[value='+current.val()+']').data('debet-project-id');

			if( current.val() == null || (dualDebtPartnerId > 0 && debtProjectId > 0) || (dualDebtPartnerId == 0 && debtProjectId == 0) ){
				$('#dualDebtPartnerId').val(dualDebtPartnerId);
				$('#creation-error').addClass('hide');
			}else if( dualDebtPartnerId == 0 && debtProjectId > 0 ){
				$('#dualDebtPartnerId').val(0);
				$('#creation-error').removeClass('hide');
				$('#budgetDebtOperationsContainer').addClass('hide');
			}
		}

		$(document).ready(function() {
		  debPartnersAccounts(); // показ списка счетов для зеркальной операции в окне управления долговой операцией
			//checkDualDebetPartner();

			var startDate = $('#startDate')
				.datepicker({
					onClose: function( selectedDate ) {
						$("#endDate").datepicker( "option", "minDate", selectedDate );
						reload();
					}
				});
			var endDate = $('#endDate')
				.datepicker({
					onClose: function( selectedDate ) {
						$( "#startDate" ).datepicker( "option", "maxDate", selectedDate );
						reload();
					}
				});

      var today = new Date();
			$("#todayDate").data('date', today.getDate()+'.'+(parseInt(today.getMonth())+1)+'.'+today.getFullYear());
			today.setDate(today.getDate()-1);
			$("#yeasterdayDate").data('date', today.getDate()+'.'+(parseInt(today.getMonth())+1)+'.'+today.getFullYear());

			$('.btn-set-date').unbind('click').on('click', function(){
				$('#startDate').val($(this).data('date'));
				$('#endDate').val($(this).data('date'));
				reload();
				return false;
			});

			$('#debtForm').submit(function(){
				var l = Ladda.create($('#debtFormSbmtBtn').get()[0]);
				l.start();
				var btn = this;
						
				$.post(
								$(this).attr('action'),
								$('#debtForm').serialize(),
								function(data) {
									if (data.status === 'success') {
										$('#budgetOperation'+data.id).replaceWith(data.operation);
										$('#budgetOperation'+data.id).find('.budget-operation-delete').addClass('olo');
										$('#budgetOperation'+data.id + ' a.to-humanize').each(function() {
											$(this).html(humanizeNumber($(this).html()));
										});
										if(data.child_deleted_id != null){
										  $('#budgetOperation'+data.id).find('.budget-operation-delete').data('child-deleted-id', data.child_deleted_id);
										}
										initEditable();
										initDeleteRestore();
										$('#debtModal').modal('hide');
									}
								},
								'json'
								).always(function() { l.stop(); });
				return false;
			});

			<?php if(User::find(Auth::user()->id)->hasRole(Role::ROLE_BUDGET)): ?>
			initEditable();
			initDeleteRestore();
			<?php endif; ?>

			$('a.to-humanize').each(function() {
				$(this).html(humanizeNumber($(this).html()));
			});

			$('#debtForm').on('change','#showDualOperationCreate', function(){
				var current = $('#debtForm');
				if( $(this).find('#dualOperationCreate').prop('checked') ){
				  current.find('.accounts').removeClass('hide');
					current.find('#dualOperationAdd').prop('checked', false)// если хотят создать новую, то снять галочку с блока выбора из списка операций и с самой выбранной операции
					current.find('.budgetOperationsTable').addClass('hide');// и спрятать блок выбора операций
		    }else{
					current.find('.accounts').addClass('hide');
				}
			});
			$('#debtForm').on('change','#dualOperationAdd', function(){
				var current = $('#debtForm');
				if( $(this).prop('checked') ){
				  current.find('.accounts').addClass('hide');
					current.find('#dualOperationCreate').prop('checked', false)
					current.find('.budgetOperationsTable').removeClass('hide');
		    }else{
					current.find('.budgetOperationsTable').addClass('hide');
					$('#budgetDebtOperationsContainer').find('.info').removeClass('info');
					current.find('.check-deb-operation').prop('checked', false);
				}
			});
		});
	</script>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="row">
  <div class="col-md-12">
		<div class="panel panel-default">
			<?php echo $__env->make('budget/menu', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
			<div class="panel-body">
				<div id="operationsFiltr" class="btn-group btn-group-sm pull-left" style="margin-right:10px">
					<button class="btn btn-default <?php if(!$input['type']): ?> active <?php endif; ?>" data-filter-name="type" data-filter-value="">Все</button>
					<button class="btn btn-default <?php if($input['type'] == BudgetOperation::TYPE_INCOMING): ?> active <?php endif; ?>" data-filter-name="type" data-filter-value="<?php echo BudgetOperation::TYPE_INCOMING; ?>">Приход</button>
					<button class="btn btn-default <?php if($input['type'] == BudgetOperation::TYPE_OUTCOMING): ?> active <?php endif; ?>" data-filter-name="type" data-filter-value="<?php echo BudgetOperation::TYPE_OUTCOMING; ?>">Расход</button>
					<button class="btn btn-default <?php if($input['type'] == BudgetOperation::TYPE_EXCHANGE): ?> active <?php endif; ?>" data-filter-name="type" data-filter-value="<?php echo BudgetOperation::TYPE_EXCHANGE; ?>">Перевод</button>

				</div>
				<div class="form-group form-inline pull-right">
					<b>Сумма:</b> <input id="operation-search-fld" name="operation-search-fld" class="form-control input"/>
				</div>
				<form class="form-inline" role="form">
					<div class="form-group">
						<input id="startDate" name="startDate" class="form-control input-sm" value="<?php echo $startDate; ?>"/>
					</div>
					<div class="form-group">
						<input id="endDate" name="endDate" class="form-control input-sm" value="<?php echo $endDate; ?>"/>
					</div>
					<div class="form-group">
						<button id="yeasterdayDate" class="btn btn-default btn-set-date" data-date="">Вчера</button>
						<button id="todayDate" class="btn btn-default btn-set-date">Сегодня</button>
					</div>
					<br/><br/>
					<div class="form-group">
						<label for="accountSelect" class="control-label">Счет</label>
						<?php echo Form::select('accountSelect', $accountsToSelect, null, array('class' => 'form-control input-sm', 'id' => 'accountSelect')); ?>

					</div>
					<div class="form-group">
						<label for="costSelect" class="control-label">Статья расходов</label>
						<select class="form-control input-sm" name="costSelect" id="costSelect">
							  <option value="0">Все</option>
							<?php foreach($groups as $group): ?>
							<optgroup label="<?php echo $group->name; ?>">
                <?php if( isset($costsArr[$group->id]) ): ?>
							    <?php foreach($costsArr[$group->id] as $costToSelect): ?>
                  <option value="<?php echo $costToSelect->id; ?>"><?php echo $costToSelect->name; ?></option>
								  <?php endforeach; ?>
                <?php endif; ?>
						  </optgroup>
							<?php endforeach; ?>
						</select>
					</div>
					&nbsp;&nbsp;&nbsp;<label class="checkbox-inline"><input id="noUploaded" type="checkbox"/> только ручные операции</label>
					&nbsp;&nbsp;&nbsp;<label class="checkbox-inline"><input id="noCostId" type="checkbox"/> расходы без категории</label>
				</form>
				<br/>
				<dl class="dl-horizontal">
					<dt>Приход за период</dt>
					<dd><span class="to-humanize"><?php echo $budgetOperationsIn; ?></span> <i class="fa fa-rub"></i></dd>
					<dt>Расход за период</dt>
					<dd><span class="to-humanize"><?php echo $budgetOperationsOut; ?></span> <i class="fa fa-rub"></i></dd>
				</dl>
				<div class="table-responsive budgetOperationsTable">
					<table class="table table-condensed table-hover">
						<thead>
							<tr>
								<th></th>
								<th>Дата</th>
								<th>Тип</th>
								<th>Счет</th>
								<th>Информация</th>
								<th class="text-right">Сумма</th>
								<th>Комментарий</th>
							</tr>
						</thead>
						<tbody id="budgetOperationsContainer">
							<?php 
								$projectsName = Project::getProjectsNameList();
							?>
							<?php foreach($budgetOperations as $budgetOperation): ?>
							<?php echo $__env->make('budget/operations/operation', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
							<?php endforeach; ?>
						</tbody>
					</table>
				</div>
				<dl id="operationsSum" class="dl-horizontal hide">
					<dt>Итого всего</dt>
					<dd><span id="operationsSumAll" class="to-humanize"></span> <i class="fa fa-rub"></i></dd>
					<dt id="operationsSumNoIncomeText">Итого является расходом</dt>
					<dd><span id="operationsSumNoIncome" class="to-humanize"></span> <i class="fa fa-rub"></i></dd>
					<dt id="operationsSumIncomeText">Итого не является расходом</dt>
					<dd><span id="operationsSumIncome" class="to-humanize"></span> <i class="fa fa-rub"></i></dd>
				</dl>
				<?php if(User::find(Auth::user()->id)->hasRole(Role::ROLE_BUDGET)): ?>
				<?php echo $__env->make('budget/operations/btns', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
				<?php endif; ?>
				<div class="clearfix"></div>
				<br/>

				<?php if(User::find(Auth::user()->id)->hasRole(Role::ROLE_BUDGET)): ?>
				<div class="well well-sm hide">
					<div class="col-sm-offset-3">
						<h4>Добавить операцию</h4>
					</div>
					<?php echo Form::open(array('action' => array('BudgetController@createOperation'), 'id' => 'budgetNewOperationForm', 'class' => 'form-horizontal')); ?>

					<div class="form-group">
						<label for="budgetNewOperationDate" class="col-sm-3 control-label">Дата</label>
						<div class="col-sm-4">
							<?php echo Form::text('budgetNewOperationDate', date('d.m.Y'), array('class' => 'form-control', 'id' => 'budgetNewOperationDate')); ?>

						</div>
					</div>
					<div class="form-group">
						<label for="budgetNewOperationType" class="col-sm-3 control-label">Тип операции</label>
						<div class="col-sm-4">
							<?php echo Form::select('budgetNewOperationType', array(
										BudgetOperation::TYPE_INCOMING => 'Приход',
										BudgetOperation::TYPE_OUTCOMING => 'Расход',
										BudgetOperation::TYPE_EXCHANGE => 'Перевод',
										BudgetOperation::TYPE_OPENING_BALANCE => 'Остатки на начало месяца',
										BudgetOperation::TYPE_OPENING_DEBT_IN => 'Мы должны на начало месяца',
										BudgetOperation::TYPE_OPENING_DEBT_OUT => 'Долг нам на начало месяца'
									), null, array('class' => 'form-control', 'id' => 'budgetNewOperationType')); ?>

						</div>
					</div>
					<div class="form-group">
						<div class="col-sm-4 col-sm-offset-3">
							<label class="checkbox-inline">
								<?php echo Form::checkbox('budgetNewOperationIsDebt', 1, null, array('id' => 'budgetNewOperationIsDebt')); ?> Долговая операция
							</label>
						</div>
					</div>
					<div class="form-group">
						<label for="budgetNewOperationAccountOut" class="col-sm-3 control-label">Счет списания в данном проекте</label>
						<div class="col-sm-4">
                            <select class="form-control" id="budgetNewOperationAccountOut" name="budgetNewOperationAccountOut">
							<?php foreach($accounts as $key => $value): ?>
                              <?php echo '<option value="'.$key.'" data-account-name="'.$accountsList[$key].'">'.$value.'</option>'; ?>

                            <?php endforeach; ?>
                            </select>
                            <p class="text-td-small acc-name-view-1"></p>
						</div>
					</div>
					<div class="form-group">
						<label for="budgetNewOperationAccountIn" class="col-sm-3 control-label">Счет зачисления в данном проекте</label>
						<div class="col-sm-4">
                            <select class="form-control" id="budgetNewOperationAccountIn" name="budgetNewOperationAccountIn">
							<?php foreach($accounts as $key => $value): ?>
                              <?php echo '<option value="'.$key.'" data-account-name="'.$accountsList[$key].'">'.$value.'</option>'; ?>

                            <?php endforeach; ?>
                            </select>
                            <p class="text-td-small acc-name-view-2"></p>
						</div>
					</div>
					<div class="form-group">
						<label for="budgetNewOperationDebtPartnerId" class="col-sm-3 control-label">Долговой контрагент: </label>
						<div class="col-sm-4">
							<select class="form-control" id="budgetNewOperationDebtPartnerId" name="budgetNewOperationDebtPartnerId">
                               <?php foreach($debtPartners as $key => $value): ?>
                                  <?php echo '<option value="'.$key.'" data-debet-project-id="'.$value[1].'" data-dual-debt-partner-id="'.(isset($dualDebtPartners[$value[1].'_'.$workProject->id])? $dualDebtPartners[$value[1].'_'.$workProject->id] : '0' ).'">'.$value[0].'</option>'; ?>

                               <?php endforeach; ?> 
                            </select>
                        <p id="creation-info-error" class="text-danger hide"><b>Невозможно создать зеркальную долговую операцию:</b> к выбранному долговому контрагенту не привязан текущий проект в качестве долгового партнера. </p>
						</div>
					</div>
                    <input id="dualDebtPartnerId" name="dualDebtPartnerId" val="" hidden>
                    <?php  
                      $debPartnersId = BudgetDebtPartner::whereProjectId($workProject->id)->where('debet_project_id', '>', '0')->lists('debet_project_id'); // массив долговых проектов у текущего проекта
                      $debPartnersAccounts =  array('<option class="default" selected="selected" value="0">-Выберите счет-</option>'); 
                      foreach (BudgetAccount::whereIn('project_id', $debPartnersId?$debPartnersId:['0'=>'0'])->orderBy('project_id')->get() as $account) {
                        $debPartnersAccounts[$account->id] = '<option class="deb-partners-accounts project_id-'.$account->project_id.' account-name-'.$accountsList[$account->id].' hide" data-account-name="'.$accountsList[$account->id].'" value="'.$account->id.'">'.$account->name.'</option>';
                      }
                    ?>
                    <div class="form-group hide" id="debPartnersAccountsBlock">
                      <label for="debPartnersAccounts" class="col-sm-3 control-label">Счет для <span id="dualOperationType" class="text-bold"></span> <br>в проекте "<span id="dualProjectName" class="text-bold"></span>"</label>
						<div class="col-sm-4">
							<select class="form-control" id="debPartnersAccounts" name="debPartnerAccountId">
                               <?php foreach($debPartnersAccounts as $acc): ?>
                                  <?php echo $acc; ?>

                               <?php endforeach; ?> 
                            </select>
                            <p id="debPartnerAccountIdError" class="text-danger"></p>
                            <span class="acc-name-view-dual"></span>
                            <p id="creation-info-ok" class="text-td-small">Автоматически будет создана вторая - зеркальная долговая операция с данным счетом</p>
						</div>
					</div>
					<div class="form-group">
						<label for="budgetNewOperationPartner" class="col-sm-3 control-label">Контрагент</label>
						<div class="col-sm-4">
							<?php echo Form::select('budgetNewOperationPartner', $partners, null, array('class' => 'form-control', 'id' => 'budgetNewOperationPartner')); ?>

              <p id="budgetNewOperationPartnerError" class="text-danger"></p>
						</div>
					</div>
					<div class="form-group">
						<label for="budgetNewOperationCost" class="col-sm-3 control-label">Статья расходов</label>
						<div class="col-sm-4">
						  <select class="form-control" name="budgetNewOperationCost" id="budgetNewOperationCost">
  							<?php foreach($groups as $group): ?>
                  <optgroup label="<?php echo $group->name; ?>">
                    <?php if( isset($costsArr[$group->id]) ): ?>
                      <?php foreach($costsArr[$group->id] as $costToSelect): ?>
                      <option value="<?php echo $costToSelect->id; ?>"><?php echo $costToSelect->name; ?></option>
                      <?php endforeach; ?>
                    <?php endif; ?>
                  </optgroup>
							  <?php endforeach; ?>
	  					</select>
						</div>
					</div>
					<div class="form-group">
						<label for="budgetNewOperationAmount" class="col-sm-3 control-label">Сумма</label>
						<div class="col-sm-4">
							<?php echo Form::text('budgetNewOperationAmount', 0, array('class' => 'form-control', 'id' => 'budgetNewOperationAmount')); ?>

						</div>
					</div>
					<div class="form-group">
						<label for="budgetNewOperationComment" class="col-sm-3 control-label">Комментарий</label>
						<div class="col-sm-4">
							<?php echo Form::text('budgetNewOperationComment', null, array('class' => 'form-control', 'id' => 'budgetNewOperationComment')); ?>

						</div>
					</div>
					<div class="form-group">
						<div class="col-sm-4 col-sm-offset-3">
							<?php echo Form::hidden('budgetNewOperationId', ''); ?>

							<?php echo Form::hidden('budgetNewOperationProjectId', $workProject->id); ?>

							<button id="budgetNewOperationSbmtBtn" type="submit" class="btn btn-primary ladda-button" data-style="zoom-out" data-modal-id="paymentReciveConfirmModal"><span class="ladda-label">Сохранить операцию</span></button>
							<?php echo Form::button('Отмена', array('class' => 'btn btn-default', 'id' => 'budgetNewOperationCancel')); ?>

						</div>
					</div>
					<?php echo Form::close(); ?>

				</div>
				<?php endif; ?>
			</div>
		</div>
	</div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.default', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>