var ajax_url = "index.php?module=EcmPaymentStates&action=javahelper&to_pdf=1";
var winien = [];
var ma = [];
var sum_ma = 0;
var total_winien=0;
var total_ma=0;

$(document).ready(function() {
	$('#number_phone').scombobox({
		fullMatch : false,
		invalidAsValue: true
	// when fullMatch is true
	// then highligh is also true by default
	});
	$('#number_phone').css('width','250px');
	$('.scombobox-display').css('width','250px');
	
});
function showNote(id){
	 window.open('index.php?module=EcmPaymentStates&action=createPDF&to_pdf=1&record2='+id+'&show=yes','_blank');
	 $('.hide_all').hide('slow'); 
}

function showDetails(id) {
	$('.hide_all').hide('slow'); 
	$("#details_"+id).show('slow');
	
	var params = {
			job : 'getDetails',
			id : id,
		};

		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "text",
			success : function(data) {
				console.log(data);
				if (data != '-1')
					$("#details_div_"+id).html(data);
			},
			data : params
		});
}

function sendSMS(){
	$('#loading').show();
	var number=$('#div_send').find('.scombobox-display').val();
	var content=encodeURIComponent($('#div_send').find('#textarea').val());
	var params = {
			job : 'sendSMS',
			number : number,
			content: content,
		};

		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "text",
			async : false,
			success : function(data) {
				console.log(data); 
					if(data=='OK')alert('SMS został wysłany!'); else alert('Wysyłka SMS nie powiodła się :( !');
			},
			data : params
		});
		
		$('#div_send').hide();
		$('#loading').hide();
}

function hideDetails(id) {
	$("#details_"+id).hide('slow');
}

function makeNote() {

	var string='';

	$("input[name='winien[]']:checked").each(function(){
		if($(this).val()!=''){
			console.log($(this).val());
			string+=$(this).val()+',';
		}
	});
	$("#id_list").val(string);
 	$("#submitNote").click();
}
function createSmsFromError(){
	var c=$("input[name='winien[]']:checked");
	if(c.length==0){
		alert("Proszę wybrać transakcje do wysyłki!");
	return false;
	
	}

}
function createSmsText(){
	var string=$('#system_name').val()+". Proszę o uregulowanie zaległej płatności: ";
	var c=$("input[name='winien[]']:checked");
	if(c.length==0){
		
	
	} else {
		$("input[name='winien[]']:checked").each(function(){
			if($(this).val()!=''){
				string=string+$('#trans_name_'+$(this).val()).text();
				string=string+" termin "+$('#trans_date_'+$(this).val()).text();
				string=string+" w kwocie "+$('#winien_val_'+$(this).val()).text();
			}
		});
		string=string+". Wiadomość automatyczna. Prosimy nie odpowiadać.";
		
		$('#div_send').find('#textarea').html(string);
	}
	

}

function sendNote(id){
	

	var params = {
			job : 'sendNote',
			ids : id,
			parent_id: $('#account_id').val(),
		};

		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
					if(data==1)alert('Email został wysłany!');
			},
			data : params
		});

}
function createMonit(typ,email){
	
	  var email_1= $(".scombobox-display").val();
	   var textarea = $("#textarea").val();
	var string='';
	//console.log(email_1);
	if($("input[name='winien[]']:checked").length>0){

	$("input[name='winien[]']:checked").each(function(){
		if($(this).val()!=''){
			console.log($(this).val());
			string+=$(this).val()+',';
		}
	});
	
	if(typ==0){
		$('#loading').show();
	var params = {
			job : 'createMonit',
			email:email_1,
			text:textarea,
			ids : string,
			parent_id: $('#account_id').val(),
		};

		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
					if(data==1){
						alert('Email został wysłany!');
					} else {
						alert('Wysyłka monitu nie powiodła się!');
					}
					$('#div_send').hide('slow');
			},
			data : params
		});
		$('#loading').hide();
	} else {
		 window.open('index.php?module=EcmPaymentStates&action=makeMonit&to_pdf=1&aa='+string+'&show=yes2','_blank');
	}
	} else {
		alert('Wybierz transakcje!');
	}
}

function compareTotals(id,type){
	console.log(total_ma+' ,'+total_winien);
	if(type==0){
		var val=UnformatNumber($('#w_'+id).html());
	   if(total_ma-val>0){
		   console.log(val);
          	$('#'+id).val(FormatNumber(val));
       } else {
    	   console.log(total_ma);
           if(total_ma>0)$('#'+id).val(FormatNumber(total_ma));else alert('Wykorzystano całą kwotę!');
       } 
       total_ma=total_ma-UnformatNumber($('#w_'+id).html());
	} else {
		var val=UnformatNumber($('#m_'+id).html());
		   if(total_winien-val>0){
			   console.log(val);
	          	$('#'+id).val(FormatNumber(val));
	       } else {
	    	   console.log(total_winien);
	           if(total_winien>0)$('#'+id).val(FormatNumber(total_winien));else alert('Wykorzystano całą kwotę!');
	       } 
		   total_winien=total_winien-UnformatNumber($('#m_'+id).html());
	}
}

function showSettlePanel() {
	$(".settle_panel").css("display", "block");
	//prepare data
	winien.length = 0;
	ma.length = 0;
	$("input[name='winien[]']:checked").each(function(){winien.push($(this).val());});

	$("input[name='ma[]']:checked").each(function(){ma.push($(this).val());});
	total_winien=0;
	total_ma=0;
	var table_winien = 'Strona Winien:<br><table style="width: 100%;">';	
	$.each(winien, function(index, value) {
		var params = {
				job : 'getTransaction',
				id : value,
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
					console.log(data);
					if (data != '-1') {
						var unsettled = (parseFloat(data.value)-parseFloat(Math.abs(data.settled)));

						total_winien+=unsettled;
						table_winien+='<tr>';
						table_winien+='<td align="left">'+data.name+'</td>';
						table_winien+='<td align="right" id="w_'+data.id+'">'+FormatNumber(unsettled)+'</td>';
						if(winien.length>1 && ma.length>0){
						table_winien+='<td align="right">';
						table_winien+='<img src="modules/EcmQuotes/images/insertrow.gif" onclick="compareTotals(\''+data.id+'\',0);calculateSum();"/>'
						table_winien+='<input onclick="calculateSum();" type="text" id="'+data.id+'" value="'+FormatNumber(0)+'"/></td>';
						}
						table_winien+='</tr>';
					}
				},
				data : params
			});
	});	
	table_winien+='</table>';
	
	var table_ma = 'Strona Ma:<br><table style="width: 100%;">';	
	$.each(ma, function(index, value) {
		var params = {
				job : 'getTransaction',
				id : value,
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
					console.log(data);
					if (data != '-1') {
						
						var unsettled = (parseFloat(data.value)-parseFloat(Math.abs(data.settled)));

						total_ma+=unsettled;
						table_ma+='<tr>';
						table_ma+='<td align="left">'+data.name+'</td>';
						table_ma+='<td align="right" id="m_'+data.id+'">'+FormatNumber(unsettled)+'</td>';
						if(ma.length>1 && winien.length>0){
							table_ma+='<td align="right">';
							table_ma+='<img src="modules/EcmQuotes/images/insertrow.gif" onclick="compareTotals(\''+data.id+'\',1);calculateSum();"/>'
							table_ma+='<input onclick="calculateSum();" type="text" id="'+data.id+'" value="'+FormatNumber(0)+'"/></td>';
							}
						table_ma+='</tr>';	
						sum_ma+= unsettled;
					}
				},
				data : params
			});
	});	
	table_ma+='</table>'; 
	var action='$(\'.check\').attr(\'checked\',false);$(\'.settle_panel\').css(\'display\', \'none\');';
	var button = '<input id="accept_btn" type="button" class="button" onclick="console.log(\'go!\');doMatch();" value="Akceptuj"/>'
				 +'<br><input type="button" class="button" onclick="'+action+'" value="Anuluj"/>';
	
	var sum_table = '<table style="width: 100%"><tr><td id="sum_cell" style="text-align: right" colspan="3"></td></tr></table>'
	
	$(".settle_panel_main").html(table_ma+'<br>'+table_winien+sum_table+button);
}

function calculateSum() {
	var sum = 0;
	$.each(winien, function(index, value) {
		sum+=UnformatNumber($("#"+value).val());
	});
	var sum_ma=0;
	$.each(ma, function(index, value) {

		sum_ma+=UnformatNumber($("#m_"+value).html());

	});
	//console.log(sum+' '+sum_ma+' '+toFixed(sum_ma - sum,2));
	$("#sum_cell").html(FormatNumber(sum));
	
	$("#sum_ma_cell").html(FormatNumber(sum_ma - sum));
	
	
	if (toFixed(sum_ma - sum,2) < 0)
		$("#accept_btn").attr("disabled", true);
	else
		$("#accept_btn").attr("disabled", false);
}

function doMatch() {
	var ma_id = ma[0];
	var winien_id = winien[0];


	if(ma.length>1 && winien.length==1){
		$.each(ma, function(index,value) {
			var params = {
					job : 'createRelation',
					id : winien_id,
					value : UnformatNumber($("#"+value).val()),
					payment : value,
				};

				$.ajax({
					type : "POST",
					url : ajax_url,
					dataType : "json",
					async : false,
					success : function(data) {
							console.log(data);
					},
					data : params
				});
		});	
	} 
	if(ma.length>1 && winien.length==0 && ma.length<3 ){
		console.log(UnformatNumber($("#"+ma[0]).html())+UnformatNumber($("#"+ma[1]).html()));
		if(UnformatNumber($("#m_"+ma[0]).html())+UnformatNumber($("#m_"+ma[1]).html())==0){
			
		var params = {
				job : 'createRelationMany',
				id : ma.toString(','),
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
						console.log(data);
				},
				data : params
			});
		} else {
			alert('Brak możliwości rozliczenia!');
			return false;
		}
	} 
	if(ma.length>1 && winien.length>1 ){

		
			
		var params = {
				job : 'createRelationMany',
				id : ma.toString(',')+','+winien.toString(','),
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
						console.log(data);
				},
				data : params
			});
		
	} 
	if(ma.length>1 && winien.length==0 && ma.length>2 ){
		console.log(UnformatNumber($("#"+ma[0]).html())+UnformatNumber($("#"+ma[1]).html()));
		var params = {
				job : 'createRelationMany',
				id : ma.toString(','),
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
						console.log(data);
				},
				data : params
			});
	} 
	if(winien.length>1 && ma.length==0 && winien.length>2 ){
		console.log(UnformatNumber($("#w_"+winien[0]).html()))
		console.log(UnformatNumber($("#w_"+winien[1]).html()));
		
			
		var params = {
				job : 'createRelationMany',
				id : winien.toString(','),
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
						console.log(data);
				},
				data : params
			});
	
	}  
	if(winien.length>1 && ma.length==0 && winien.length<3 ){
		

			
		console.log(UnformatNumber($("#"+ma[0]).html())+UnformatNumber($("#"+ma[1]).html()));
		var params = {
				job : 'createRelationMany',
				id : winien.toString(','),
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
						console.log(data);
				},
				data : params
			});
		
	} 
	if(winien.length==1 && ma.length==1){
	
		var ma_w= UnformatNumber($("#ma_val_"+ma[0]).html());
		if(isNaN(ma_w)){
			ma_w=UnformatNumber($("#ma_val_"+ma[0]).children('b').children('span').html());
			
		} else {
			
		}
		var w_w= UnformatNumber($("#winien_val_"+winien[0]).html());
		if(isNaN(w_w)){
			w_w=UnformatNumber($("#winien_val_"+winien[0]).children('b').children('span').html());
			
		} else {
			
		}
		if(w_w!=ma_w){
			if(parseFloat(w_w)<0 && 0<parseFloat(ma_w)){
				alert('Brak możliwości rozliczenia!');
				return false;
			}
			if(parseFloat(w_w)>0 && 0>parseFloat(ma_w)){
				alert('Brak możliwości rozliczenia!');
				return false;
			}
			if(w_w>ma_w){
				total=ma_w;
			
			} else {
				total=w_w;
				
			}
		} else {
			total=w_w;
			
		}

		
		$.each(winien, function(index,value) {
			var params = {
					job : 'createRelation',
					id : value,
					value : total,
					payment : ma_id,
				};
	
				$.ajax({
					type : "POST",
					url : ajax_url,
					dataType : "json",
					async : false,
					success : function(data) {
							console.log(data);
					},
					data : params
				});
		});	
	}
	if(winien.length>1 && ma.length==1){
		
		$.each(winien, function(index,value) {
			var params = {
					job : 'createRelation',
					id : value,
					value : UnformatNumber($("#"+value).val()),
					payment : ma_id,
				};
	
				$.ajax({
					type : "POST",
					url : ajax_url,
					dataType : "json",
					async : false,
					success : function(data) {
							console.log(data);
					},
					data : params
				});
		});	
	}
	window.location.reload();
}
function createTransactionWinien(id){
	ma.length = 0;
	$("input[name='ma[]']:checked").each(function(){ma.push($(this).val());});
	var timpp='';
	if(ma.length>0){
		var tmp= new Object();
		tmp.id='';
		tmp.amount='';
		$.each(ma, function(index,value) {
			tmp.id+=value+'|';
			timpp= UnformatNumber($("#ma_val_"+value).html());
			if(isNaN(timpp)){
				timpp=UnformatNumber($("#ma_val_"+value).children('b').children('span').html());
				tmp.amount+=timpp+'|';
			} else {
				tmp.amount+=timpp+'|';
			}
			
			
		
		});	
		
		window.location.href='index.php?module=EcmTransactions&action=EditView&parent_id='+id+'&type=0&fromAccountPaymentStates=1&toRelId='+tmp.id+'&toRelVal='+tmp.amount;
		
	} else {
		window.location.href='index.php?module=EcmTransactions&action=EditView&parent_id='+id+'&type=0&fromAccountPaymentStates=1';
	}

}

function createTransactionMa(id){
	winien.length = 0;
	$("input[name='winien[]']:checked").each(function(){winien.push($(this).val());});
	var timpp='';
	if(winien.length>0){
		var tmp= new Object();
		tmp.id='';
		tmp.amount='';
		$.each(winien, function(index,value) {
			tmp.id+=value+'|';
			timpp= UnformatNumber($("#winien_val_"+value).html());
			if(isNaN(timpp)){
				timpp=UnformatNumber($("#winien_val_"+value).children('b').children('span').html());
				tmp.amount+=timpp+'|';
			} else {
				tmp.amount+=timpp+'|';
			}
			
			
		
		});	
		
		window.location.href='index.php?module=EcmTransactions&action=EditView&parent_id='+id+'&type=1&fromAccountPaymentStates=1&toRelId='+tmp.id+'&toRelVal='+tmp.amount;
		
	} else {
		window.location.href='index.php?module=EcmTransactions&action=EditView&parent_id='+id+'&type=1&fromAccountPaymentStates=1';
	}

}

function FormatNumber(number, precision) {
	var precision = precision || 2;
	
	// make string..
	number = number + '';
	number = number.replace(',', '.');
	// round
	number = toFixed(number, precision);
	// add 1000 sep
	var tmp = number.split(".");
	var c = '';
	for (var i = tmp[0].length; i != -1; i--) {
		c += tmp[0].charAt(i);
		if ((tmp[0].length - i) == 0 || i == 0)
			continue;
		if ((tmp[0].length - i) % 3 == 0)
			c += '.';
	}
	// reverse c
	c = c.split("").reverse().join("");

	return c + ',' + tmp[1];
}
 

function sendPost(){

	if($('#switch_show').val()=='1'){
		$('#switch_show').val('0');
		
	} else {
		$('#switch_show').val('1');
		
	}
	$('#toPDF').val('0');
	$('#to_pdf').val('0');
	$('#searchForm').attr("target", "");
	$("#submit").click();

	   
}

function submitForm(){

	$("#submit").click();

	   
}

function sendPost2(){

	if($('#switch_show').val()=='2'){
		$('#switch_show').val('0');
		
	} else {
		$('#switch_show').val('2');
		
	}
	$('#toPDF').val('0');
	$('#to_pdf').val('0');
	$('#searchForm').attr("target", "");
	$("#submit").click();


	   
}
function sendPost3(){

	if($('#switch_show').val()=='3'){
		$('#switch_show').val('0');
		
	} else {
		$('#switch_show').val('3');
		
	}
	$('#toPDF').val('0');
	$('#to_pdf').val('0');
	$('#searchForm').attr("target", "");
	$("#submit").click();

}
	

function sendPost4(){

	if($('#switch_show').val()=='4'){
		$('#switch_show').val('0');
		
	} else {
		$('#switch_show').val('4');
		
	}
	$('#searchForm').attr("target", "");
	$('#toPDF').val('0');
	$('#to_pdf').val('0');
	$("#submit").click();

	   
}
function sendPDF(){

	$('#toPDF').val('1');
	$('#to_pdf').val('1');
	$('#searchForm').attr("target", "_blank");
	$("#submit").click();

	   
}
function sendPost5(){

	if($('#switch_show').val()=='5'){
		$('#switch_show').val('0');
		
	} else {
		$('#switch_show').val('5');
		
	}
	$('#toPDF').val('0');
	$('#searchForm').attr("target", "");
	$('#to_pdf').val('0');
	$("#submit").click();

	   
}
function showActions(id){
	if($('#div_options_'+id).css('display') == 'none'){
		$('.hide_all').hide('slow'); 
		$('#div_options_'+id).show('slow'); 
		} else { 
			$('#div_options_'+id).hide('slow'); 
			}
}
function showOptions(id){
	if($('#div_options_search_'+id).css('display') == 'none'){
		$('.hide_all').hide('slow'); 
		$('#div_options_search_'+id).show('slow'); 
		} else { 
			$('#div_options_search_'+id).hide('slow'); 
			}
}
   

function editTransaction(id){
	
	var r = confirm('Czy na pewno chcesz edytować ten record');
	if (r == true) {
		window.location.href='index.php?module=EcmTransactions&action=EditView&record='+id+'&return_action=AccountPaymentStates&fromAccountPaymentStates=1&return_module=EcmPaymentStates&return_id='+$('#account_id').val();
	} 
}

function deleteTransaction(id){
	var r = confirm('Czy na pewno chcesz usunąć ten rekord?');
	if (r == true) {
		$(".loading_panel").css("display", "block");

		var params = {
				module : 'EcmTransactions',
				action: 'Delete',
				record : id,
			};
			$.ajax({
				type : "POST",
				url : 'index.php?',
				dataType : "json",
				async : false,
				success : function(data) {
					$("#submit").click();
				},
			     error: function (xhr, ajaxOptions, thrownError) {
			 
			         $("#submit").click();
			       },
				data : params
			});	
	} 
}
function deleteRelation(id){
	var r = confirm('Czy na pewno chcesz usunąć powiązanie?');
	if (r == true) {
		$(".loading_panel").css("display", "block");

		var params = {
				module : 'EcmTransactions',
				action: 'RemoveRelations',
				record : id,
			};
			$.ajax({
				type : "POST",
				url : 'index.php?',
				dataType : "json",
				async : false,
				success : function(data) {
					$("#submit").click();
				},
			     error: function (xhr, ajaxOptions, thrownError) {
			 
			         $("#submit").click();
			       },
				data : params
			});	
	} 
}
function UnformatNumber(number) {
    if (!number)
        number = 0;
    // make string..
    number = number + '';
    // remove 1000 sep
    while (number.indexOf('.') != -1) 
        number = number.replace('.', '');
    // change ',' to '.'
    number = number.replace(',', '.');
    return parseFloat(number);
}


function toFixed(value, precision) {
	var precision = precision || 0, neg = value < 0, power = Math.pow(10,
			precision), value = Math.round(value * power), integral = String((neg ? Math.ceil
			: Math.floor)(value / power)), fraction = String((neg ? -value
			: value)
			% power), padding = new Array(Math.max(precision - fraction.length,
			0) + 1).join('0');

	return precision ? integral + '.' + padding + fraction : integral;
}
