<div class="tabbable">
	<ul class="nav nav-tabs">
		<li class="active"><a href="#tab0" data-toggle="tab"><i class="icon-tasks"></i> <?php echo __('admin.informations'); ?></a></li>
		<li><a href="#tab1" data-toggle="tab"><i class="icon-shopping-cart"></i> Articles</a></li>
	</ul>
	<div class="tab-content">
		<div class="tab-pane active" id="tab0">
			<table class="table table-striped">
				<tr <?php if($errors->first('customer_id')) echo 'class="error"'; ?>>
					<td style="width:300px">Client *</td>
					<td>
						<?php echo  Form::select('customer_id', $clients, Input::old('customer_id', ((isset($doc) && $doc->customer_id!='') ? $doc->customer_id : '')), array('style'=>'width:280px;')); ; ?>
						<?php echo  $errors->first('customer_id', '<span class="help-inline">:message</span>') ; ?>
					</td>
				</tr>
				<tr <?php if($errors->first('label')) echo 'class="error"'; ?>>
					<td>Nom du projet</td>
					<td>
						<?php echo  Form::text('label', Input::old('label', (isset($doc) ? $doc->label : NULL)),array('style'=>'width:400px;')) ; ?>
						<?php echo  $errors->first('label', '<span class="help-inline">:message</span>') ; ?>
					</td>
				</tr>
				<?php if($type!='avoir'): ?>
				<tr <?php if($errors->first('date_livraison')) echo 'class="error"'; ?>>
					<td>Date de livraison<?=$type=='devis'?'estimée':''?></td>
					<td>
						<?php echo  Form::text('date_livraison', Input::old('date_livraison', str_replace('0000-00-00','',(isset($doc) ? substr($doc->date_livraison,0,10) : NULL))), array('placeholder' => 'Date de livraison', 'class' => 'datepicker')); ; ?>
						<?php echo  $errors->first('date_livraison', '<span class="help-inline">:message</span>') ; ?>
					</td>
				</tr>
				<?php endif; ?>
				<?php if($type=='avoir' || $type=='facture'): ?>
				<tr <?php if($errors->first('date')) echo 'class="error"'; ?>>
					<td>Date de <?=$type=='avoir'?'l\'avoir:':' facture'?></td>
					<td>
						<?php echo  Form::text('date', Input::old('date', str_replace('0000-00-00','',(isset($doc) ? substr($doc->date,0,10) : NULL))), array('placeholder' => 'Date de facture', 'class' => 'datepicker')); ; ?>
						<?php echo  $errors->first('date', '<span class="help-inline">:message</span>') ; ?>
					</td>
				</tr>
				<?php endif; ?>
				<?php if($type=='facture'): ?>
				<tr <?php if($errors->first('date_limite')) echo 'class="error"'; ?>>
					<td>Date limite de paiement</td>
					<td>
						<?php echo  Form::text('date_limite', Input::old('date_limite', str_replace('0000-00-00','',(isset($doc) ? substr($doc->date_limite,0,10) : NULL))), array('placeholder' => 'Date limite de paiement', 'class' => 'datepicker')); ; ?>
						<?php echo  $errors->first('date_limite', '<span class="help-inline">:message</span>') ; ?>
					</td>
				</tr>
				<?php if($doc->devis_id>=1): ?>
				<tr>
					<td colspan="2"><i class="icon-info-sign"></i> Note : cette facture est liée au devis <a target="_blank" href="<?php echo  URL::to_route('edit_devis', array($doc->devis_id)) ; ?>">#<?php echo $doc->devis_id; ?></a></td>
				</tr>
				<?php endif; ?>
				<?php endif; ?>
				<?php if($doc->id>=1): ?>
				<tr>
					<td colspan="2"><a class="btn btn-small" href="<?php echo  URL::to_route($route.'pdf', array($doc->id)) ; ?>" target="_blank"><i class="icon-file"></i> Imprimer</a></td>
				</tr>
				<?php endif; ?>
			</table>
		</div>
		<div class="tab-pane" id="tab1">
			<style>
			#sortable { list-style-type: none; margin: 0; padding: 0; width: 100%; }
			#sortable li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; }
			</style>
			
			<div>
				<div style="width:77%;font-weight:bold;float:left;">&nbsp;Article</div>
				<div style="width:10%;font-weight:bold;float:left;">Qté</div>
				<div style="width:10%;font-weight:bold;float:left;">Prix HT</div>
				<div style="clear:both;"></div>
			</div>
			
			<ul id="sortable">
				<?php if($doc && count($doc->lignes)>=1): ?>
					<?php foreach($doc->lignes as $l): ?>
					<li class="ui-state-default" style="text-align:center">
						<i class="icon-fullscreen"></i> <?php echo  Form::text('article_label[]', $l->article_label,array('style'=>'width:70%;','class'=>'article_label_input')) ; ?> 
						<?php echo  Form::text('article_qte[]', $l->article_qte,array('style'=>'width:8%;','class'=>'article_qte')) ; ?> 
						<?php echo  Form::text('article_prix[]', $l->article_prix,array('style'=>'width:8%;','class'=>'article_prix')) ; ?>
					</li>
					<?php endforeach; ?>
				<?php else: ?>
					<li class="ui-state-default" style="text-align:center">
						<i class="icon-fullscreen"></i> <?php echo  Form::text('article_label[]', '',array('style'=>'width:70%;','class'=>'article_label_input')) ; ?> 
						<?php echo  Form::text('article_qte[]', '1.00',array('style'=>'width:8%;','class'=>'article_qte')) ; ?> 
						<?php echo  Form::text('article_prix[]', '0.00' ,array('style'=>'width:8%;','class'=>'article_prix')) ; ?>
					</li>
				<?php endif; ?>
			</ul>
			<div style="text-align:center;margin-top:10px;"><button class="btn btn-success" id="add_article"><i class="icon-plus"></i> Ajouter un article</button></div>
			
			<div id="trash" style="background-color : #f1f1f1;font-size:25px;border:1px dashed #CCC;;padding:10px;text-align:center;width:72%;margin-left:auto;margin-right:auto;margin-top:15px;margin-bottom:25px"><i class="icon-trash"></i> <span style="font-size:20px;">Faire glisser l'article ici pour le supprimer</span></div>
			
			<div style="width:75%;margin:10px auto 10px auto;font-size:20px;text-align:center">
				<div style="width:34%;float:left;">
					<div class="well">
					<?php echo  Form::select('tva', array('19.6'=>'TVA 19.60%','0'=>'Exonéré - TVA 0%'),Input::old('tva', (isset($doc) ? $doc->tva : NULL)),array('style'=>'margin-bottom:10px;width:150px','id'=>'select_tva')) ; ?><br />
					<p style="margin-top:15px">Total HT : <span id="display_total_ht">0.00</span> &euro;</p>
					<p style="margin-top:10px">Total TTC : <span id="display_total_ttc">0.00</span> &euro;</p>
					</div>
				</div>
				<div style="float:left;width:2%">&nbsp;</div>
				<div style="width:64%;float:left;">
					<div class="well">
						<?php if($type!='avoir'): ?>
						<?php if($doc && count($doc->acomptes)>=1): ?>
							<?php foreach($doc->acomptes as $a): ?>
							<div class="acomptes_lignes">
								<div class="input-append" style="display:inline;"><?php echo  Form::text('acompte_pourcent[]', '0' ,array('style'=>'margin-top:6px;width:8%;','class'=>'acompte_pourcent','placeholder'=>'%')) ; ?> <span style="margin-top:6px;" class="add-on">%</span></div>
								<?php echo  Form::text('acompte_label[]', $a->label,array('style'=>'width:43%;','class'=>'acompte_label','placeholder'=>'Libellé acompte')) ; ?>
								<div class="input-append" style="display:inline;"><?php echo  Form::text('acompte_montant[]', $a->montant,array('style'=>'margin-top:6px;width:13%;','class'=>'acompte_montant','placeholder'=>'€ TTC')) ; ?> <span style="margin-top:6px;" class="add-on">€</span></div>
								<button class="btn btn-small remove_acompte"><i class="icon-trash"></i></button>
							</div>
							<?php endforeach; ?>
						<?php endif; ?>
						<div style="text-align:center;margin-top:10px;" id="add_acompte_div"><button class="btn btn-success" id="add_acompte"><i class="icon-plus"></i> Ajouter un acompte</button></div>
						<?php endif; ?>
						<div class="acomptes_solde" style="<?php if($type!='avoir'): ?>padding-top:10px<?php endif; ?>">
							<div class="input-append" style="display:inline;"><?php echo  Form::text('solde_pourcent', '100' ,array('style'=>'margin-top:6px;width:9%;','id'=>'solde_pourcent','placeholder'=>'%','disabled')) ; ?> <span style="margin-top:6px;" class="add-on">%</span></div>
							<?php echo  Form::text('solde_label', Input::old('solde_label', (isset($doc) ? $doc->solde_label : 'Avant la mise en ligne')) ,array('style'=>'width:45%;','id'=>'solde_label','placeholder'=>'Solde')) ; ?>
							<div class="input-append" style="display:inline;"><?php echo  Form::text('solde_montant', '0' ,array('style'=>'margin-top:6px;width:15%;','id'=>'solde_montant','placeholder'=>'€ TTC','disabled')) ; ?> <span style="margin-top:6px;" class="add-on">€</span></div>
						</div>
					</div>
				</div>
				<div style="clear:both;"></div>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
function number_format (number, decimals, dec_point, thousands_sep) {
  // *     example 1: number_format(1234.56);
  // *     returns 1: '1,235'
  // *     example 2: number_format(1234.56, 2, ',', ' ');
  // *     returns 2: '1 234,56'
  // *     example 3: number_format(1234.5678, 2, '.', '');
  // *     returns 3: '1234.57'
  // *     example 4: number_format(67, 2, ',', '.');
  // *     returns 4: '67,00'
  // *     example 5: number_format(1000);
  // *     returns 5: '1,000'
  // *     example 6: number_format(67.311, 2);
  // *     returns 6: '67.31'
  // *     example 7: number_format(1000.55, 1);
  // *     returns 7: '1,000.6'
  // *     example 8: number_format(67000, 5, ',', '.');
  // *     returns 8: '67.000,00000'
  // *     example 9: number_format(0.9, 0);
  // *     returns 9: '1'
  // *    example 10: number_format('1.20', 2);
  // *    returns 10: '1.20'
  // *    example 11: number_format('1.20', 4);
  // *    returns 11: '1.2000'
  // *    example 12: number_format('1.2000', 3);
  // *    returns 12: '1.200'
  // *    example 13: number_format('1 000,50', 2, '.', ' ');
  // *    returns 13: '100 050.00'
  // Strip all characters but numerical ones.
  number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec);
      return '' + Math.round(n * k) / k;
    };
  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}
function article_autocomplete(){
	$('.article_label_input').autocomplete({
	    source: function( request, response ) {
	    	$.post("<?php echo URL::to_route('article_ajax_search'); ?>", request, response);
		},
		change: function(){
		    update_total();
	    },
	    minLength: 2,
	    select: function (event, ui) {
	    	if(parseFloat(ui.item.prix)>0){
		    	$(this).parent().find('.article_prix').val(parseFloat(ui.item.prix));
		    	update_total();
		    	update_acomptes_montants();
	    	}
	    }
	});
	$(".remove_acompte").on('click',function(e){
		e.preventDefault();
		if(window.confirm('Supprimer cet acompte ?')){
			$(this).parent().remove();
			update_acomptes_montants();
			return false;
		}
		return false;
	});
	$(".article_qte, .article_prix, .acompte_montant").on('keyup',function(){
		var old_val = $(this).val();
		var cur_attr = $(this).val().replace(',','.');
		if(old_val != cur_attr){
			$(this).val(cur_attr);	
		}
	});
	$(".article_qte, .article_prix, .acompte_montant, .acompte_pourcent").on('change',function(){
		var cur_attr = parseFloat($(this).val().replace(',','.'));
		if(!cur_attr || cur_attr == 'NaN' || cur_attr == 'undefined' || cur_attr == null ){
			cur_attr = 0;
		}
		else{
			$(this).val(cur_attr.toFixed(2));	
		}
	});
	
	$("input,select").on('change',function(){
		update_total();
		if($(this).hasClass('article_prix') || $(this).hasClass('article_qte') || $(this).attr('id')=='select_tva'){
			update_acomptes_montants();
		}
	});
	
	// Acomptes
	$(".acompte_montant").on('change',function(){
		update_acomptes_pourcents();
	});
	$(".acompte_pourcent").on('change',function(){
		update_acomptes_montants();
	});
	update_acomptes_pourcents();
}
function update_acomptes_pourcents(){
	var total_ttc = get_total_ttc();
	var current_montant = 0;
	$(".acompte_pourcent").each(function(i,val){
		var cur_val = $(this).parent().parent().find('.acompte_montant').val();
		if(cur_val != 'NaN' && cur_val != 'undefined' && cur_val != null ){
			var acompte_montant = parseFloat(cur_val);
			if(acompte_montant>0){
				var acompte_pourcent = Math.round((acompte_montant / total_ttc * 100)*100)/100;
			}
			else{
				var acompte_pourcent = 0;
			}
			$(this).val(acompte_pourcent.toFixed(2));
			current_montant += acompte_montant;
		}
	});
	var solde = total_ttc - current_montant;
	if(solde>0 && total_ttc >0){
		var solde_pourcent = Math.round((solde / total_ttc * 100)*100)/100;
	}
	else{
		var solde_pourcent = 0;
	}
	$("#solde_pourcent").val(solde_pourcent.toFixed(2));
	$("#solde_montant").val(solde.toFixed(2));
}
function update_acomptes_montants(){
	var total_ttc = get_total_ttc();
	var current_montant = 0;
	$(".acompte_montant").each(function(i,val){
		var cur_val = $(this).parent().parent().find('.acompte_pourcent').val();
		if(cur_val != 'NaN' && cur_val != 'undefined' && cur_val != null ){
			var acompte_pourcent = parseFloat(cur_val);
			var acompte_montant = Math.round((total_ttc * acompte_pourcent / 100)*100)/100;
			$(this).val(acompte_montant.toFixed(2));
			current_montant += acompte_montant;
		}
	});
	var solde = total_ttc - current_montant;
	var solde_pourcent = Math.round((solde / total_ttc * 100)*100)/100;
	$("#solde_pourcent").val(solde_pourcent.toFixed(2));
	$("#solde_montant").val(solde.toFixed(2));
}
function get_total_ht(){
	var total_ht = 0;
	$(".article_prix").each(function(i,val){
		var qte = parseFloat($(this).parent().find('.article_qte').val());
		var prix = parseFloat($(this).val());
		if(!qte || qte == 'NaN' || qte == 'undefined' || qte == null || !prix || prix == 'NaN' || prix == 'undefined' || prix == null){
			total_ht += 0;
		}
		else{
			total_ht += parseFloat(prix*qte);
		}
	});
	return total_ht;
}
function get_total_ttc(){
	var total_ht = get_total_ht();
	var tva = parseFloat($('#select_tva').val()); 
	return total_ht + total_ht*tva/100;
}
function update_total(){
	var total_ht = get_total_ht();
	var total_ttc = get_total_ttc();
	$("#display_total_ht").html(number_format(total_ht, 2, '.', ' '));
	$("#display_total_ttc").html(number_format(total_ttc, 2, '.', ' '));
}
$('.datepicker').datepicker({
	dateFormat: 'yy-mm-d'
});
$(function() {
	$('#myTab a:first').tab('show');
	
	$( "#sortable" ).sortable({
      placeholder: "ui-state-highlight"
    });
    $('#trash').droppable({
		drop : function ( event , img ) {
			var $element = img.draggable;
			if(window.confirm('Supprimer cet article ?')){
				$element.detach();
			}
			else{
				return false;
			}
		}
	});
    
    $("#add_article").on('click',function(e){
    	e.preventDefault();
	    $("#sortable").append('<li class="ui-state-default" style="text-align:center"><i class="icon-fullscreen"></i> <?php echo  Form::text('article_label[]', null ,array('style'=>'width:70%;','class'=>'article_label_input')) ; ?> <?php echo  Form::text('article_qte[]', '1.00' ,array('style'=>'width:8%;','class'=>'article_qte')) ; ?> <?php echo  Form::text('article_prix[]', '0.00' ,array('style'=>'width:8%;','class'=>'article_prix')) ; ?></li>');
	    article_autocomplete();
	    return false;
    });
    $("#add_acompte").on('click',function(e){
    	e.preventDefault();
		//$("#add_acompte_div").before('<div class="acomptes_lignes"><?php echo  Form::text('acompte_pourcent[]', null ,array('style'=>'width:8%;','class'=>'acompte_pourcent','placeholder'=>'%')) ; ?> <?php echo  Form::text('acompte_label[]', null ,array('style'=>'width:48%;','class'=>'acompte_label','placeholder'=>'Libellé acompte')) ; ?> <?php echo  Form::text('acompte_montant[]', '0.00',array('style'=>'width:16%;','class'=>'acompte_montant','placeholder'=>'€ TTC')) ; ?> <button class="btn btn-small remove_acompte"><i class="icon-trash"></i></button></div>');
		$("#add_acompte_div").before('<div class="acomptes_lignes"><div class="input-append" style="display:inline;"><?php echo  Form::text('acompte_pourcent[]', '0' ,array('style'=>'margin-top:6px;width:8%;','class'=>'acompte_pourcent','placeholder'=>'%')) ; ?> <span style="margin-top:6px;" class="add-on">%</span></div> <?php echo  Form::text('acompte_label[]', '', array('style'=>'width:43%;','class'=>'acompte_label','placeholder'=>'Libellé acompte')) ; ?> <div class="input-append" style="display:inline;"><?php echo  Form::text('acompte_montant[]', '0.00',array('style'=>'margin-top:6px;width:13%;','class'=>'acompte_montant','placeholder'=>'€ TTC')) ; ?> <span style="margin-top:6px;" class="add-on">€</span></div> <button class="btn btn-small remove_acompte"><i class="icon-trash"></i></button></div>');
	    article_autocomplete();
	    return false;
    });
							
    article_autocomplete();
    update_total();
});
</script>