//It restrict the non-numbers

	var specialKeys = new Array();
	
	specialKeys.push(8,44,46); //Backspace
	
	function IsNumeric(e) {
		var keyCode = e.which ? e.which : e.keyCode;
		//console.log( keyCode );
		var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
		return ret;
	}

$(document).ready(function() {
	
	
	//autocomplete script
	$(document).on('focus','#itemsearch',function(){
		
		$('#itemsearchresults').html('');
		
		
		$(this).autocomplete({
			source: function( request, response ) {
				$.ajax({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    url : '/panel/ajax-getstockitem',
					dataType: "json",
					method: 'post',
					data: {
					   term: request.term,
					   type: 'prodinvoice'
					},
					 success: function( data ) {
						 response( $.map( data, function( item ) {
							var code = item.split("|");
							return {
								label: code[1],
								value: code[1],
								data : item
							}
						}));
					}
				});
			},
			autoFocus: true,	      	
			minLength: 0,
			select: function( event, ui ) {
				
				var names = ui.item.data.split("|");

                var siid = $.trim(names[0]);


				var curItems = $('.iitem').length;


				var lastIndex = (curItems) ? $('.iitem:last').data('index')+1 : 0;



				$.ajax({
					type : 'POST',
					headers: {
						'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
					},
					url: '/panel/ajax-getnewstockitems',
					dataType: 'html',
					data: {siid: siid, index: lastIndex},
					beforeSend: function() {

					},
					success: function(data) {

						//$('#prodsearchresults').html(data);
						$('table#invtable').append(data);
                        $('#acqnt').val(1);
                        $('#acprice').val('');
						$('table#invtable .tot').number( true, 2 );
						getTotal();
						$('#closeapm').click();
						//$('table#invtable td:last .tot').number( true, 2 );

					}, // success
					error: function(statusCode, errorThrown) {
						if (statusCode.status == 0) {
							alert("Nije uspostavljena veza sa internetom\npokušajte da se ponovo povežete\nkako bi mogli da nastavite sa radom");
						} // if no connection
					} // error

				}); // ajax

				
				

				
			}		      	
		});
	});
	
	
		
	
	function getTotal() {
		
		var priceTotal = 0;
		
		$('input.price').each( function() {
			
			var val =  parseFloat($(this).val());
			var qnty =  parseFloat($(this).parent().parent().find('input.qnt').val());
			priceTotal = priceTotal+(val*qnty);
			
			
		});
		priceTotal = priceTotal.toFixed(2);
		
		
		$('input#subTotal').val(priceTotal);
		
	}
	
	function pricechange(e) {

		var qntyf    = e.parent().parent().find('input.qnt');
		var totf     = e.parent().parent().find('input.tot');
		var price    = parseFloat(e.val());
		var quantity = parseFloat(qntyf.val());
		
		if(quantity == '' || quantity < 1) { qntyf.val(1); }
		
		var total = jQuery.trim((price*quantity).toFixed(2));
		totf.val(total);
		
	
	}
	
	function qntyChange(e) {
		
		var pricef   = e.parent().parent().find('input.price');
		var totf     = e.parent().parent().find('input.tot');
		var price    = jQuery.trim(pricef.val());
		var quantity = e.val();
		
		if(price == '') {
			
			return false;
			
		} else {
			
			var total = jQuery.trim((price*quantity).toFixed(2));
		    totf.val(total);
		    getTotal();			
			
		}		
		
	}
	
	$(document).on('keyup change','input.price',function(){
        $(this).val($(this).val().replace(/,/g,"."));
		pricechange($(this));
		getTotal();
		
	});	
	
	$(document).on('keyup change', 'input.qnt', function(){		
		qntyChange($(this));
		getTotal();
	});	
	
	// cekiranje svih checkboxes
	$(document).on('change','#check_all',function(){
		$('input[class=case]:checkbox').not(":disabled").prop("checked", $(this).is(':checked'));
	});

	//brisanje oznacenih stavki
	$(document).on('click', '.delete',  function() {

        $('.case:checkbox:checked').each(function () {
			if($(this).closest('tr').next('tr').hasClass('errorrow')){$(this).closest('tr').next('tr').remove();}
            $(this).closest('tr').remove();
        });


		//$('.case:checkbox:checked').parents("tr.iitem").remove();


		$('#check_all').prop("checked", false); 
		getTotal();
	});	
	
	$(document).on('click' , '.fixp' , function(event){
        if(confirm('Da li ste sigurni da zelite da promenite oznaku za fiksnu cenu ?\nUkoliko je već odobravan ukidan popust\nIznos moze biti netačan')) {
			return true;
		} else {
			event.stopPropagation();
			return false;
		}
	
	});

	
	function changePrices(rate){
		
		$("tr.iitem").each(function() {
			
			var pricefield = $(this).find('input.price');
			var fixmark    = $(this).find('.fixp');
			
			var cprice = parseFloat(pricefield.val());
			
			
			if( (cprice != '') && (!fixmark.is(':checked')) ){
				
				var newprice = (cprice*rate).toFixed(2);
				pricefield.val(newprice).trigger('change');
			
			}
            
        });
		
		getTotal();
		
	}

	
	$('#insrtbutt').on('click', function(){
		
		if(!confirm('Da li zelite da snimite ovaj dokument ?')){
			return false;
		}
		
	});
	
	$('.tot, #subTotal').number( true, 2 );
	

	
    
}); // dr

