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

$(document).ready(function(){

    
    $.tablesorter.addParser({
		  // use a unique id
		  id: 'saas',
		  is: function(s, table, cell) {
		    // s is the text from the cell
		    // table is the current table (as a DOM element; not jQuery object)
		    // cell is the current table cell (DOM element)
		    // return false if you don't want this parser to be auto detected
		    return false;
		  },
		  format: function(s, table, cell, cellIndex) {
		    // s is the text from the cell
		    // table is the current table (as a DOM element; not jQuery object)
		    // cell is the current table cell (DOM element)
		    // cellIndex is the current cell's column index
		    // format your data for normalization
		    // (i.e. do something to get and/or modify your data, then return it)
		    return s.replace('.', '').replace(',', '.').replace('%', '');
		  },
		  // flag for filter widget (true = ALWAYS search parsed values; false = search cell text)
		  parsed: false,
		  // set the type to either numeric or text (text uses a natural sort function
		  // so it will work for everything, but numeric is faster for numbers
		  type: 'numeric'
	});

	  // call the tablesorter plugin
	  $("table").tablesorter({
		  
	    theme: 'blue',
	    // initialize zebra striping of the table
	    widgets: ['zebra','staticRow'],
	    // change the default striping class names
	    // updated in v2.1 to use widgetOptions.zebra = ["even", "odd"]
	    // widgetZebra: { css: [ "normal-row", "alt-row" ] } still works
	    widgetOptions : {
	      zebra : [ "normal-row", "alt-row" ]
	    }
	  });
	     $('#date_to').on('inputchange', function() {
       
             setTimeout(function() {
            	 if($("#show_after_d").val()=='checked'){
            		 submit();
            	 }
            	
             }, 1000);
         });
}); 

$.event.special.inputchange = {
		setup : function() {
			var self = this, val;
			$.data(this, 'timer', window.setInterval(function() {
				val = self.value;
				if ($.data(self, 'cache') != val) {
					$.data(self, 'cache', val);
					$(self).trigger('inputchange');
				}
			}, 20));
		},
		teardown : function() {
			window.clearInterval($.data(this, 'timer'));
		},
		add : function() {
			$.data(this, 'cache', this.value);
		}
	};

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 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 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){
	
	var string='';
	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){
	var params = {
			job : 'createMonit',
			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!');
			},
			data : params
		});
	} else {
		 window.open('index.php?module=EcmPaymentStates&action=makeMonit&to_pdf=1&aa='+string+'&show=yes2','_blank');
	}
	} else {
		alert('Wybierz transakcje!');
	}
}

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());});

	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) {
					if (data != '-1') {
						var unsettled = (parseFloat(data.value)-parseFloat(data.settled));
						table_winien+='<tr>';
						table_winien+='<td align="left">'+data.name+'</td>';
						table_winien+='<td align="right">'+FormatNumber(unsettled)+'</td>';
						table_winien+='<td align="right">';
						table_winien+='<img src="modules/EcmQuotes/images/insertrow.gif" onclick="$(\'#'+data.id+'\').val(\''+FormatNumber(unsettled)+'\'); calculateSum();"/>'
						table_winien+='<input type="text" id="'+data.id+'" value="'+FormatNumber(0)+'"/ onchange="$(this).val(FormatNumber($(this).val()));calculateSum();" onclick="$(this).select();" ></td>';
						table_winien+='</tr>';
					}
				},
				data : params
			});
	});	
	table_winien+='</table>';
	
	var table_ma = '<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) {
					if (data != '-1') {
						var unsettled = (parseFloat(data.value)-parseFloat(data.settled));
						table_ma+='<tr>';
						table_ma+='<td align="left">'+data.name+'</td>';
						table_ma+='<td align="right" id="'+data.id+'">'+FormatNumber(unsettled)+'</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($("#"+value).html());

	});
	$("#sum_cell").html(FormatNumber(sum));
	
	$("#sum_ma_cell").html(FormatNumber(sum_ma - sum));
	
	/*
	if (toFixed(sum_ma - sum,2) < 0){
		//$("#accept_btn").attr("disabled", "disabled");
	}else
		$("#accept_btn").attr("disabled", "");
		*/
}

function setmax(){
	
}
function doMatch() {
	console.log('kurwa');
	var ma_id = ma[0];
	var winien_id = winien[0];
console.log('co ci kurwa jest nc');
console.log(ma);
console.log(winien);
	
	if(ma.length>1){
		$.each(ma, function(index,value) {
			var params = {
					job : 'createRelation',
					id : winien_id,
					value : UnformatNumber($("#"+value).html()),
					payment : value,
				};

				$.ajax({
					type : "POST",
					url : ajax_url,
					dataType : "json",
					async : false,
					success : function(data) {
							console.log(data);
					},
					data : params
				});
		});	
	} else {

		$.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 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($('#show_settled').val()=='on' || $('#show_settled').val()=='checked' ){
		$('#show_settled').val('');
		console.log('kurwa chowam');
	} else {
		$('#show_settled').val('on');
		console.log('kurwa wlaczam');
	}
	$("#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 sendPost2(){

	if($('#show_after_p').val()=='on' || $('#show_after_p').val()=='checked' ){
		$('#show_after_p').val('');
	} else {
		$('#show_after_p').val('on');
	}
	$("#submit").click();

	   
}

function submit(){
	$("#submit").click();
}
function sendPost3(){

	if($('#show_after_t').val()=='on' || $('#show_after_t').val()=='checked' ){
		console.log('odznaczam');
		$('#show_after_t').val('');
	} else {
		$('#show_after_t').val('on');
		console.log('zaznaczam');
	}
	$("#submit").click();

	   
}

function sendPost4(){

	if($('#show_after_d').val()=='on' || $('#show_after_d').val()=='checked' ){
		console.log('odznaczam');
		$('#show_after_d').val('');
	} else {
		$('#show_after_d').val('on');
		console.log('zaznaczam');
	}
	$("#submit").click();

	   
}
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&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) {
	// make string..
	number = number + '';
	// remove 1000 sep
	number = number.replace('.', '');
	// change ',' to '.'
	number = number.replace(',', '.');
	
	number = toFixed(number,2);

	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;
}
