
var ajax_url = "index.php?module=EcmAgreements&action=javahelper&to_pdf=1";
var itemsTable = 'itemsTable';
var items = new Array();
var displayArray = new Array();
var searchedProducts = new Array();


function FillTable(data, allReadOnly) {
	html = '';
	var pozycja=1;
	var color;
	// loop throw data rows

	$
			.each(
					data,
					function(row_index, row) {
						html += '<tr>';
						if(row.product_item=="false"){
							color='#D4D9DB';
						} else {
							color='#ffffff';
						}
						// and insert columns
	
						
						$
								.each(
										columns,
										function(col_index, column) {
											// row must have code and name
											if (!row.payment_date)
												return; // return in each =
											// continue in php for
											// loop
											// special types
											if (column.name == 'number') {
												html += '<td style="background-color:'+color+';"><input class="inputs" style="text-align: center;background-color:'+color+';" type="text" id="number_'
														+ row_index
														+ '" name="number_'
														+ row_index
														+ '" readonly value="';
														html+=+ row_index+1;  
														html+='"/></td>';
											} else if (column.name == 'payment_date') {
												html += '<td style="background-color:'+color+';"><textarea style="width: 100%; height: 100%;background-color:'+color+';" id="payment_date_'
														+ row_index
														+ '" name="name_'
														+ row_index + '"';
												if (allReadOnly)
													html += ' readonly';
												html += '>' + row.payment_date
														+ '</textarea></td>';
											} else if (column.name == 'options') {
												if (allReadOnly)
													html += '<td  style="background-color:'+color+';"></tr>';
												else {
													html += '<td  style="background-color:'+color+';">';
													// move up
													html += '<a onClick="moveUpRow('
															+ row_index
															+ ')" target="_blank"><img style="cursor:pointer;" src="modules/EcmAgreements/images/moverowup.gif"/></a>';
													html += '&nbsp;';
													// move down
													html += '<a onClick="moveDownRow('
															+ row_index
															+ ')" target="_blank"><img style="cursor:pointer;" src="modules/EcmAgreements/images/moverowdown.gif"/></a>';
													html += '<br>';
													// delete row
													html += '<a onClick="deleteRow('
															+ row_index
															+ ')" target="_blank"><img style="cursor:pointer;" src="modules/EcmAgreements/images/deleterow.gif"/></a>';
													html += '</td>';
												}
											}
											// other types
											else {
												html += '<td  style="background-color:'+color+';">';
												$
														.each(
																column.content,
																function(
																		cell_index,
																		cell) {
																	var cellname = column.name
																			+ cell.name;
																	if (cellname == 'product_link') {
																		html += '<a href="index.php?module=EcmProducts&action=DetailView&record='
																				+ row.product_id
																				+ '" target="_blank">'
																				+ row.product_code
																				+ '</a>';
																	} else if (cellname == 'price_start_div'
																			&& !allReadOnly) {
																		html += '<br><img style="cursor: pointer;" src="modules/EcmAgreements/images/search.gif" onClick="if ($(\'#price_start_div_'
																				+ row_index
																				+ '\').css(\'display\')==\'none\') getPricesInfo('
																				+ row_index
																				+ '); else $(\'#price_start_div_'
																				+ row_index
																				+ '\').hide(\'slow\')"/>';
																		html += '<div id="'
																				+ cellname
																				+ '_'
																				+ row_index
																				+ '" style="display:none;float:right;text-align:right;border: 1px #cccccc solid;padding:3px;"></div>';
																	} else {
																		if (cell.label
																				&& cell.label != '')
																			html += '<p>'
																					+ cell.label
																					+ '</p>';
																		html += '<input class="inputs" type="'
																				+ cell.type
																				+ '" name="'
																				+ cellname
																				+ '_'
																				+ row_index
																				+ '" id="'
																				+ cellname
																				+ '_'
																				+ row_index
																				+ '"';
																		if (cell.readonly
																				|| allReadOnly)
																			html += ' readonly ';
																		if (column.align)
																			html += ' style="text-align: '
																					+ column.align
																					+ ';background-color:'+color+';"';
																		if (cell.onChange
																				|| cell.isNumber)
																			html += ' onChange="$(this).val(FormatNumber($(this).val()));'
																					+ cell.onChange
																					+ '" onClick="$(this).select();"';
																		else if (cell.onChange
																				|| !cell.isNumber)
																			html += ' onChange="'
																					+ cell.onChange
																					+ '" ';
																		if (row[cellname]
																				&& cell.isNumber)
																			html += ' value="'
																					+ FormatNumber(row[cellname])
																					+ '" ';
																		else if (row[cellname])
																			html += ' value="'
																					+ row[cellname]
																					+ '" ';
																		else {
																			if (cell.isNumber)
																				html += ' value="0,00" ';
																			else
																				html += ' value="" ';
																		}
																		html += '>';
																	}
																});
												html += '</td>';
											}

										});
						html += '</tr>';

					});

	$('#' + itemsTable + '_T > tbody').html(html);
	if (!allReadOnly) {
		// calculate totals
		var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
		//for (var index = 0; index != count; index++)
			//calculateRow(index);
	} else
		DrawDetailSummary();
}

function calculatePaymentDate(pid) {
	var date = $("#register_date").val();
	var d = date.split(".");
	
	date = d.join(".");
	var params = {
			job : 'calculatePaymentDate',
			pid: pid,
			date : date,
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
				$('#payment_date').val(data);
			},
			data : params
		});	
}

function getNBPCurrencyExchange(c_id) {

	var date = $("#register_date").val();
	var d = date.split(".");
	d[0]-=1;
	date = d.join(".");
	var params = {
			job : 'getNBPCurrencyExchange',
			c_id : c_id,
			date : date,
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
				if(data!=false){
				$("#currency_value_nbp").val(data);
				} else {$("#currency_value_nbp").val(0);}
			},
			data : params
		});	
}
function getPayer(id){
	var account_id=$("#address_id :selected").val();
	var params = {
			job : 'getAddress',
			account_id : account_id,
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
				if (data != '-1') {
				
							$("#parent_payer_address_name").val(data[0].description);
							$("#parent_payer_address_street").val(data[0].street);
							$("#parent_payer_address_postalcode").val(data[0].postalcode);
							$("#parent_payer_address_city").val(data[0].city);
							$("#parent_payer_address_country").val(data[0].country);
							
						
				}
				//$(".loading_panel").css("display", "none");
			},
			data : params
		});
}
function getAddress(id){
	var account_id=$("#address_id :selected").val();
	var params = {
			job : 'getAddress',
			account_id : account_id,
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
				if (data != '-1') {
				
							$("#parent_shipping_address_name").val(data[0].description);
							$("#parent_shipping_address_street").val(data[0].street);
							$("#parent_shipping_address_postalcode").val(data[0].postalcode);
							$("#parent_shipping_address_city").val(data[0].city);
							$("#parent_shipping_address_country").val(data[0].country);
							
						
				}
				//$(".loading_panel").css("display", "none");
			},
			data : params
		});
}
function setAddressSend(result){
	var p = new Object();
	p.street=result.street;
	alert(p.street);
}
function getAddresses(account_id) {
	
	//show loading

	var params = {
			job : 'getAddresses',
			account_id : account_id,
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
				$('#addresses').append(data);
				$(".loading_panel").css("display", "none");
			},
			data : params
		});
}

function getPayers(account_id) {
	
	//show loading

	var params = {
			job : 'getPayers',
			account_id : account_id,
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
				$('#payer').append(data);
				$(".loading_panel").css("display", "none");
			},
			data : params
		});
}

function calculateTotal(){

	var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
	
	total_odsteki=0;
	total_prowizja=0;
	total_suma=0;
	total_principal_value=0;
	for (var index = 0; index != count; index++) {
		total_odsteki+=UnformatNumber($("#interest_rate_"+index).val());
		total_prowizja+=UnformatNumber($("#rate_of_commission_"+index).val());
		total_suma+=UnformatNumber($("#total_"+index).val());
		total_principal_value+=UnformatNumber($("#principal_value_"+index).val());
	
	}
	DrawSummary();
	$("#t_interest_rate").val(FormatNumber(total_odsteki));
	$("#t_total").val(FormatNumber(total_suma));
	$("#t_rate_of_commission").val(FormatNumber(total_prowizja));
	$("#t_principal_value").val(FormatNumber(total_principal_value));
	
	$("#total_total").val(total_suma);
	$("#total_interest_rate").val(UnformatNumber($("#t_interest_rate").val()));
	$("#total_rate_of_commission").val(UnformatNumber($("#t_rate_of_commission").val()));
	$("#total_principal_value").val(UnformatNumber($("#t_principal_value").val()));
	

	
}
//klasa liczenie rat 
//
///
// 
function raty(){
	this.ilosc_rat=UnformatNumber($("#number_of_installments").val());
	this.rata_kapitalowa=UnformatNumber($("#principal_value").val());
	this.prowizja=UnformatNumber($("#rate_of_commission").val());
	this.odsetki=UnformatNumber($("#interest_rate").val());
	this.kwota=UnformatNumber($("#amount").val());
	this.data_kredytu=$("#date_of_the_loan").val();
	this.ostatnia_rata=$("#date_end").val();
	this.data_raty=1;
	this.i=1;
	this.sumaKwota=this.kwota;
	this.total_odsteki=0;
	this.total_prowizja=0;
	this.total_suma=0;
	this.total_principal_value=0;
	this.pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
	this.raty=new Array();
}

raty.prototype.wczytajLiczPozycje = function (numer){
	var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row

	for (var index = 0; index != count; index++) {
		var tmp= new Object();
		
		if(index==numer){ // operacje na modyfikowanym rekordzie
			var dt = new Date(this.data_kredytu.replace(this.pattern,'$3-$2-$1'));
			var LdOtM = new Date(dt.getFullYear(), dt.getMonth()+1, 0);
			tmp=items[index];
			tmp.principal_value=UnformatNumber($("#principal_value_"+index).val());
		
			if(numer==0){
			if(LdOtM.getDate()==dt.getDate() && dt.getFullYear()==LdOtM.getFullYear() && LdOtM.getMonth()==dt.getMonth()){	
				tmp=this.pierwszaRataInnyMiesiac(dt.getFullYear(), dt.getMonth(),tmp.principal_value);
			} else {
				tmp=this.pierwszaRata(dt.getFullYear(), dt.getMonth(),dt.getDate(),tmp.principal_value);
			}
			}
			if(numer>0){
				if(count == numer){
					tmp=this.ostatniaRata(dt.getFullYear(), dt.getMonth(),tmp.principal_value);
			
				} else {
					tmp=this.kolejnaRata(dt.getFullYear(), dt.getMonth(),tmp.principal_value);
				}
			}
		} else {
			
			tmp=items[index];
			if(index==0){
				
				var dt = new Date(this.data_kredytu.replace(this.pattern,'$3-$2-$1'));
				var LdOtM = new Date(dt.getFullYear(), dt.getMonth()+1, 0);
				if(LdOtM.getDate()==dt.getDate() && dt.getFullYear()==LdOtM.getFullYear() && LdOtM.getMonth()==dt.getMonth()){	
					tmp=this.pierwszaRataInnyMiesiac(dt.getFullYear(), dt.getMonth(),tmp.principal_value);
				} else {
					tmp=this.pierwszaRata(dt.getFullYear(), dt.getMonth(),dt.getDate(),tmp.principal_value);
				}
			} 
			var dt = new Date(this.data_raty.replace(this.pattern,'$3-$2-$1'));
			var LdOtM = new Date(dt.getFullYear(), dt.getMonth()+1, 0);
			
		
			if(index>0){
			
				if((count-1) == index){
				
					tmp=this.ostatniaRataLicz(dt.getFullYear(), dt.getMonth());
				} else {
			
					tmp=this.kolejnaRata(dt.getFullYear(), dt.getMonth(),tmp.principal_value);
				}
			} 
		}
		this.total_odsteki+=tmp.interest_rate;
		this.total_prowizja+=tmp.rate_of_commission;
		this.total_suma+=tmp.total;
		this.total_principal_value+=tmp.principal_value;
		this.raty.push(tmp);
	}
	DrawSummary();
	$("#t_interest_rate").val(FormatNumber(this.total_odsteki));
	$("#t_total").val(FormatNumber(this.total_suma));
	$("#t_rate_of_commission").val(FormatNumber(this.total_prowizja));
	$("#t_principal_value").val(FormatNumber(this.total_principal_value));
	
	$("#total_total").val(this.total_suma);
	$("#total_interest_rate").val(UnformatNumber($("#t_interest_rate").val()));
	$("#total_rate_of_commission").val(UnformatNumber($("#t_rate_of_commission").val()));
	$("#total_principal_value").val(UnformatNumber($("#t_principal_value").val()));
	return this.raty;
}

raty.prototype.pierwszaRataInnyMiesiac = function (rok,miesiac,rata){
	var rata_tmp = rata!='brak' ? rata : this.rata_kapitalowa;
 
	var tmp = new Object();
	LdOtM = new Date(rok, miesiac+2, 0);
	this.data_raty = tmp.payment_date= formattedDate(LdOtM);
	
    tmp.interest_rate=(((LdOtM.getDate()/LdOtM.getDate())*this.odsetki*this.sumaKwota)/100);
    tmp.rate_of_commission=(((LdOtM.getDate()/LdOtM.getDate())*this.prowizja*this.sumaKwota)/100);
    tmp.principal_value=rata_tmp;
    tmp.total=tmp.rate_of_commission+tmp.interest_rate+tmp.principal_value;
    tmp.saldo=this.sumaKwota-tmp.principal_value;
    this.sumaKwota=this.sumaKwota-tmp.principal_value;
    return tmp;
}

raty.prototype.pierwszaRata = function(rok,miesiac,dzien,rata){
	
	var rata_tmp = rata!='brak' ? rata : this.rata_kapitalowa;
	
	var tmp = new Object();
	LdOtM = new Date(rok, miesiac+1, 0);
	this.data_raty = tmp.payment_date=formattedDate(LdOtM);
	left_day=LdOtM.getDate()-dzien;

    tmp.interest_rate=(((left_day/LdOtM.getDate())*this.odsetki*this.sumaKwota)/100);
    tmp.rate_of_commission=(((left_day/LdOtM.getDate())*this.prowizja*this.sumaKwota)/100);
    tmp.principal_value=rata_tmp;
    tmp.total=tmp.rate_of_commission+tmp.interest_rate+tmp.principal_value;
    tmp.saldo=this.sumaKwota-tmp.principal_value;
    this.sumaKwota=this.sumaKwota-tmp.principal_value;

    return tmp;
}

raty.prototype.ostatniaRataLicz = function(rok,miesiac){
	var tmp = new Object();
//	var rata_tmp = rata!='brak' ? rata : this.rata_kapitalowa;
	
	
	var dt = new Date(this.ostatnia_rata.replace(this.pattern,'$3-$2-$1'));
	var LdOtM = new Date(dt.getFullYear(), dt.getMonth()+1, 0);
	this.data_raty = tmp.payment_date=formattedDate(dt);
	left_day=dt.getDate();

	  tmp.interest_rate=(((left_day/30)*this.odsetki*this.sumaKwota)/100);
	    tmp.rate_of_commission=(((left_day/30)*this.prowizja*this.sumaKwota)/100);
	    tmp.principal_value=this.sumaKwota;
	    tmp.total=tmp.rate_of_commission+tmp.interest_rate+tmp.principal_value;
	    tmp.saldo=this.sumaKwota-this.sumaKwota;
	    this.sumaKwota=this.sumaKwota-this.sumaKwota;
    return tmp;
}

raty.prototype.ostatniaRata = function(rok,miesiac,rata){
	var tmp = new Object();
	var rata_tmp = rata!='brak' ? rata : this.rata_kapitalowa;
	
	
	var dt = new Date(this.ostatnia_rata.replace(this.pattern,'$3-$2-$1'));
	var LdOtM = new Date(dt.getFullYear(), dt.getMonth()+1, 0);
	this.data_raty = tmp.payment_date=formattedDate(dt);
	left_day=dt.getDate();
	
	  tmp.interest_rate=(((left_day/LdOtM.getDate())*this.odsetki*this.sumaKwota)/100);
	    tmp.rate_of_commission=(((left_day/LdOtM.getDate())*this.prowizja*this.sumaKwota)/100);
	    tmp.principal_value=this.sumaKwota;
	    tmp.total=tmp.rate_of_commission+tmp.interest_rate+tmp.principal_value;
	    tmp.saldo=this.sumaKwota-this.sumaKwota;
	    this.sumaKwota=this.sumaKwota-this.sumaKwota;
    
 
    return tmp;
}

raty.prototype.kolejnaRata = function(rok,miesiac,rata){
	var tmp = new Object();
	var rata_tmp = rata!='brak' ? rata : this.rata_kapitalowa;

	LdOtM = new Date(rok, miesiac+2, 0);
	this.data_raty = tmp.payment_date= formattedDate(LdOtM);
	
    tmp.interest_rate=(((LdOtM.getDate()/LdOtM.getDate())*this.odsetki*this.sumaKwota)/100);
    tmp.rate_of_commission=(((LdOtM.getDate()/LdOtM.getDate())*this.prowizja*this.sumaKwota)/100);
    tmp.principal_value=rata_tmp;
    tmp.total=tmp.rate_of_commission+tmp.interest_rate+tmp.principal_value;
    tmp.saldo=this.sumaKwota-tmp.principal_value;
    this.sumaKwota=this.sumaKwota-tmp.principal_value;
    return tmp;
}

raty.prototype.pierwszaOstatniaRata = function(rok,miesiac,dzien,rata){
	
	var rata_tmp = rata!='brak' ? rata : this.rata_kapitalowa;
	
	var tmp = new Object();
	LdOtM = new Date(rok, miesiac+1, 0);
	this.data_raty = tmp.payment_date=formattedDate(LdOtM);
	left_day=LdOtM.getDate()-dzien;
	

    tmp.interest_rate=(((left_day/30)*this.odsetki*this.sumaKwota)/100);
    tmp.rate_of_commission=(((left_day/30)*this.prowizja*this.sumaKwota)/100);
    tmp.principal_value=rata_tmp;
    //tmp.total=tmp.rate_of_commission+tmp.interest_rate+tmp.principal_value;


	var dt = new Date(this.ostatnia_rata.replace(this.pattern,'$3-$2-$1'));
	var LdOtM = new Date(dt.getFullYear(), dt.getMonth()+1, 0);
	this.data_raty = tmp.payment_date=formattedDate(dt);
	left_day=dt.getDate();

	  tmp.interest_rate+=(((left_day/30)*this.odsetki*this.sumaKwota)/100);
	    tmp.rate_of_commission+=(((left_day/30)*this.prowizja*this.sumaKwota)/100);
	   //tmp.principal_value+=rata_tmp;
	    tmp.total=tmp.rate_of_commission+tmp.interest_rate+tmp.principal_value;
	  // tmp.saldo+=this.sumaKwota-tmp.principal_value;
	    //this.sumaKwota=this.sumaKwota-tmp.principal_value;
    
    return tmp;
}

raty.prototype.generujPozycje = function (){
	var tmp = new Object();

	if(this.data_raty==1){ // licze pierwszy termin
		var dt = new Date(this.data_kredytu.replace(this.pattern,'$3-$2-$1'));
		var LdOtM = new Date(dt.getFullYear(), dt.getMonth()+1, 0);
		
		if(this.i==this.ilosc_rat){
			tmp=this.pierwszaOstatniaRata(dt.getFullYear(), dt.getMonth(),dt.getDate(),'brak');
		} else {
			// pierwsza rata w nastepnym miesiacu
			if(LdOtM.getDate()==dt.getDate() && dt.getFullYear()==LdOtM.getFullYear() && LdOtM.getMonth()==dt.getMonth()){	
				tmp=this.pierwszaRataInnyMiesiac(dt.getFullYear(), dt.getMonth(),'brak');
			} else {
				tmp=this.pierwszaRata(dt.getFullYear(), dt.getMonth(),dt.getDate(),'brak');
			}
		}
		
	} else { // reszta
		// ostatnia rata
		var dt = new Date(this.data_raty.replace(this.pattern,'$3-$2-$1'));
		if(this.ilosc_rat==this.i && (this.sumaKwota-this.rata_kapitalowa)>0){
			tmp=this.ostatniaRata(dt.getFullYear(), dt.getMonth(),'brak');
	
		} else {
			tmp=this.kolejnaRata(dt.getFullYear(), dt.getMonth(),'brak');
		}
	}
	return tmp;
	 
}

raty.prototype.sprawdz = function(){
	var error=true;
	for(this.i=1; this.i<this.ilosc_rat+1;this.i++){ 
		if(UnformatNumber($("#total_"+(this.i-1)).val())<0.01){
			$("#total_"+(this.i-1)).css("color", "red");
			$("#number_"+(this.i-1)).css("color", "red");
			$("#payment_date_"+(this.i-1)).css("color", "red");
			$("#interest_rate_"+(this.i-1)).css("color", "red");
			$("#rate_of_commission_"+(this.i-1)).css("color", "red");
			$("#principal_value_"+(this.i-1)).css("color", "red");
			$("#saldo_"+(this.i-1)).css("color", "red");
			error= false;
		} else {
			$("#total_"+(this.i-1)).css("color", "black");
			$("#number_"+(this.i-1)).css("color", "black");
			$("#payment_date_"+(this.i-1)).css("color", "black");
			$("#interest_rate_"+(this.i-1)).css("color", "black");
			$("#rate_of_commission_"+(this.i-1)).css("color", "black");
			$("#principal_value_"+(this.i-1)).css("color", "black");
			$("#saldo_"+(this.i-1)).css("color", "black");
		}
	}
	return error;
}

raty.prototype.generujRaty = function() {
	
	if(Math.ceil(this.kwota/this.rata_kapitalowa)<this.ilosc_rat){
		alert('Podano za dużą wartość raty kapitałowej');
		return false;
	}
	
	for(this.i=1; this.i<this.ilosc_rat+1;this.i++){ 
		var tmp= this.generujPozycje();
			this.total_odsteki+=tmp.interest_rate;
			this.total_prowizja+=tmp.rate_of_commission;
			this.total_suma+=tmp.total;
			this.total_principal_value+=tmp.principal_value;
		this.raty.push(tmp); 

	}
	DrawSummary();
	$("#t_interest_rate").val(FormatNumber(this.total_odsteki));
	$("#t_total").val(FormatNumber(this.total_suma));
	$("#t_rate_of_commission").val(FormatNumber(this.total_prowizja));
	$("#t_principal_value").val(FormatNumber(this.total_principal_value));
	
	$("#total_total").val(this.total_suma);
	$("#total_interest_rate").val(UnformatNumber($("#t_interest_rate").val()));
	$("#total_rate_of_commission").val(UnformatNumber($("#t_rate_of_commission").val()));
	$("#total_principal_value").val(UnformatNumber($("#t_principal_value").val()));
	return this.raty;
};


// klasa liczenie rat end

function ObliczPozycje(index){

	var Tabelka = new raty();
	items=Tabelka.wczytajLiczPozycje(index);
	FillTable(items);
	Tabelka.sprawdz();
}

function ObliczRaty(){
	
	var Tabelka = new raty();
	items=Tabelka.generujRaty();
	FillTable(items);
	/*
	
	while(items.length > 0) {
	    items.pop();
	} // fastest
	var ilosc_rat=UnformatNumber($("#number_of_installments").val());
	var rata_kapitalowa=UnformatNumber($("#principal_value").val());
	var prowizja=UnformatNumber($("#rate_of_commission").val());
	var odsetki=UnformatNumber($("#interest_rate").val());
	var kwota=UnformatNumber($("#amount").val());
	var data_kredytu=$("#date_of_the_loan").val();
	var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
	var dt = new Date(data_kredytu.replace(pattern,'$3-$2-$1'));
	var i;
	  var now = dt.getDate();
	  var year = dt.getFullYear();
	var monarr = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	// check for leap year
	if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) monarr[1] = "29";

	// display day left
	
	var help_salto=kwota;
	var total_odsteki=0;
	var total_prowizja=0;
	var total_suma=0;
	var total_principal_value=0;
	for (i = 0; i < ilosc_rat; i++) {
		var ar=new Object();
	    ar.number=i+1; 
	    ar.payment_date=formattedDate(new Date(dt.getFullYear(), dt.getMonth()+1+i, 0));
	    ar.nextdata=new Date(dt.getFullYear(), dt.getMonth()+1+i, 0);
	    var month = ar.nextdata.getMonth();
	    if(now==1)now=0;
	    if(i==0){
	    	help_saldo=kwota;
	    	ar.saldo=kwota-rata_kapitalowa; 
	    	ar.principal_value=parseFloat(rata_kapitalowa);
	        ar.dni_zostalo=monarr[month]-now;
	    }else{ 
	    	 ar.dni_zostalo=monarr[month];
	    
	    		help_salto=items[i-1].saldo;
	    		ar.principal_value=parseFloat(rata_kapitalowa);
		    	
		    	ar.saldo=help_salto-rata_kapitalowa;
		
	    }
	   
	    console.log(ar.dni_zostalo+' '+monarr[month]+ ' '+odsetki+' '+help_salto);
	    ar.interest_rate=(((ar.dni_zostalo/monarr[month])*odsetki*help_salto)/100);
	    ar.rate_of_commission=(((ar.dni_zostalo/monarr[month])*prowizja*help_salto)/100);
	    
	    if(i==ilosc_rat-1){
	    	ar.principal_value=(kwota-(kwota-help_salto));
	    	
	    	help_salto=help_salto-ar.principal_value;
	    	ar.saldo=help_salto;
	    } 
	    ar.total=ar.interest_rate+ar.rate_of_commission+ar.principal_value;
	    total_odsteki+=ar.interest_rate;
	    total_prowizja+=ar.rate_of_commission;
	    total_suma+=ar.total;
	    total_principal_value+=ar.principal_value;
	    items.push( ar );
	}
	
	FillTable(items);
	DrawSummary();
	$("#t_interest_rate").val(FormatNumber(total_odsteki));
	$("#t_total").val(FormatNumber(total_suma));
	$("#t_rate_of_commission").val(FormatNumber(total_prowizja));
	$("#t_principal_value").val(FormatNumber(total_principal_value));
	
	$("#total_total").val(total_suma);
	$("#total_interest_rate").val(UnformatNumber($("#t_interest_rate").val()));
	$("#total_rate_of_commission").val(UnformatNumber($("#t_rate_of_commission").val()));
	$("#total_principal_value").val(UnformatNumber($("#t_principal_value").val()));
	*/
}

function calculateInstallment(){
	while(items.length > 0) {
	    items.pop();
	} // fastest
	var number_of_installments=UnformatNumber($("#number_of_installments").val());
	var principal_value=UnformatNumber($("#principal_value").val());
	var rate_of_commission=UnformatNumber($("#rate_of_commission").val());
	var interest_rate=UnformatNumber($("#interest_rate").val());
	var amount=UnformatNumber($("#amount").val());
	var date_of_the_loan=$("#date_of_the_loan").val();
	var pattern_to_date = /(\d{2})\.(\d{2})\.(\d{4})/;
	var i;
	
	var dt = new Date(date_of_the_loan.replace(pattern_to_date,'$3-$2-$1'));
	var now = dt.getDate();
	var balance=principal_value;
	var year = dt.getFullYear();
	var monarr = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) monarr[1] = "29";

	for (i = 0; i < number_of_installments || principal_value<=0; i++) {
	    items[i].number=i+1;
	    /*ar.payment_date=formattedDate(new Date(dt.getFullYear(), dt.getMonth()+1+i, 0));
	    ar.nextdata=new Date(dt.getFullYear(), dt.getMonth()+1+i, 0);
	    var month = ar.nextdata.getMonth();
	    if(now==1)now=0;
	    if(i==0){
	    	ar.saldo=kwota-rata_kapitalowa; 
	    	ar.principal_value=parseFloat(rata_kapitalowa);
	        ar.dni_zostalo=monarr[month]-now;
	    }else{ 
	    	 ar.dni_zostalo=monarr[month];
	    
	    		balance=items[i-1].saldo;
	    		ar.principal_value=parseFloat(rata_kapitalowa);
		    	
		    	ar.saldo=balance-rata_kapitalowa;
		
	    }
	    console.log('row '+index+' saldo '+balance);
	    ar.interest_rate=(((ar.dni_zostalo/monarr[month])*odsetki*balance)/100);
	    ar.rate_of_commission=(((ar.dni_zostalo/monarr[month])*prowizja*balance)/100);
	    
	    if(i==ilosc_rat-1){
	    	ar.principal_value=(kwota-(kwota-balance));
	    	
	    	balance=balance-ar.principal_value;
	    	ar.saldo=balance;
	    } 
	    ar.total=ar.interest_rate+ar.rate_of_commission+ar.principal_value;
	    total_odsteki+=ar.interest_rate;
	    total_prowizja+=ar.rate_of_commission;
	    total_suma+=ar.total;
	    total_principal_value+=ar.principal_value;
	    */
	}
	console.log(items);
	FillTable(items);
	DrawSummary();
	$("#t_interest_rate").val(FormatNumber(total_odsteki));
	$("#t_total").val(FormatNumber(total_suma));
	$("#t_rate_of_commission").val(FormatNumber(total_prowizja));
	$("#t_principal_value").val(FormatNumber(total_principal_value));
	
	$("#total_total").val(total_suma);
	$("#total_interest_rate").val(UnformatNumber($("#t_interest_rate").val()));
	$("#total_rate_of_commission").val(UnformatNumber($("#t_rate_of_commission").val()));
	$("#total_principal_value").val(UnformatNumber($("#t_principal_value").val()));
}
function calculateRow(index) {
	if (index == -1) 
		return;

	// liczone według najlepszych zasad księgowości
	var interest_rate = UnformatNumber($('#interest_rate_' + index).val());
	var rofc = UnformatNumber($('#rate_of_commission_' + index).val());
	var principal_value = UnformatNumber($('#principal_value_' + index).val());

	
	items[index].rate_of_commission = toFixed(rate_of_commission, 2);
	items[index].interest_rate = toFixed(interest_rate, 2);
	items[index].total = toFixed(interest_rate+rofc+principal_value, 2);
	
	$("#total_"+index).val(FormatNumber(items[index].total));
	calculateTotal();
}
/*
function calculateTotal() {
	var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
	var vats = new Array();
	var all_subtotal = 0;
	var all_total = 0;
	var sum_vats = 0;
	var sum_discounts = 0;

	for (var index = 0; index != count; index++) {
		subtotal = UnformatNumber($('#total_netto_' + index).val());
		product_item = $('#product_item_' + index).val();
		if(product_item=='true')continue;
	
		all_subtotal += subtotal;
		if (!$("#no_tax").is(":checked")) {
			// font color to black
			$("#ecmvat_name_" + index).css("color", "black");
			if (!($('#ecmvat_id_' + index).val() in vats)) {
				vats[$('#ecmvat_id_' + index).val()] = new Object();
				vats[$('#ecmvat_id_' + index).val()].value_name = $(
						'#ecmvat_name_' + index).val(); // ex. 23
				vats[$('#ecmvat_id_' + index).val()].value = subtotal
						* ($('#ecmvat_value_' + index).val() / 100);
			} else
				vats[$('#ecmvat_id_' + index).val()].value += subtotal
						* ($('#ecmvat_value_' + index).val() / 100);
			sum_vats += subtotal * ($('#ecmvat_value_' + index).val() / 100);
		} else {
			// set color to red
			$("#ecmvat_name_" + index).css("color", "red");
		}

		if (UnformatNumber($('#discount_' + index).val()) > 0)
			sum_discounts += (UnformatNumber($('#price_start_' + index).val()) * UnformatNumber($(
					'#quantity_' + index).val()))
					* (UnformatNumber($('#discount_' + index).val()) / 100);
	}
	all_total = all_subtotal + sum_vats;

	DrawSummary();
	$('#total_vat').val(sum_vats);
	$("#t_netto").val(FormatNumber(all_subtotal));
	$("#t_brutto").val(FormatNumber(all_total));
	$('#to_paid').text(FormatNumber(all_total));
	var paid=$('#paid_val').val();
	var prepaid=$('#prepaid').val();
	$('#left').text(FormatNumber(all_total-paid-prepaid));
	$("#disc").val(FormatNumber(sum_discounts));
	console.log(vats);
	// add vats
	var html = '';
	var vats_summary = '';
	for ( var x in vats) {
		html += '<td class="positionsLabel">' + vats[x].value_name + '</td>';
		html += '<td class="positionsField"><input type="text" readonly="readonly" style="border:0px;font-weight:900;width:100%;text-align:right;" name="vat" id="vat" value="'
				+ FormatNumber(vats[x].value) + '"></td>';
		$('#result_table > tbody > tr:eq(1)').after(html);
		vats_summary += vats[x].value_name + ':' + toFixed(vats[x].value, 2)
				+ ',';
	}

	$("#vats_summary").val(vats_summary);
}
*/
function deleteRow(index) {
	items.splice(index, 1);
	FillTable(items);
}

function moveUpRow(index) {
	if (index == 0)
		return; // Can't go upper.. :(
	var new_index = index - 1;
	var old_index = index;
	if (new_index >= items.length) {
		var k = new_index - items.length;
		while ((k--) + 1) {
			items.push(undefined);
		}
	}
	items.splice(new_index, 0, items.splice(old_index, 1)[0]);
	FillTable(items);
}

function moveDownRow(index) {
	if (index == items.length - 1)
		return; // Can't go lower.. :(
	var new_index = index + 1;
	var old_index = index;
	if (new_index >= items.length) {
		var k = new_index - items.length;
		while ((k--) + 1) {
			items.push(undefined);
		}
	}
	items.splice(new_index, 0, items.splice(old_index, 1)[0]);
	FillTable(items);
}

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

	return parseFloat(number);
}

// round with precision
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;
}

// draw table
function DrawHeaders() {
	var html = '<link rel="stylesheet" type="text/css" href="modules/EcmAgreements/MyTable.css" />';
	html += '<div style="width:100%;border: 1px solid rgb(48,192,255);background-color:white;height: auto;overflow:auto;" id="'
			+ itemsTable + 'DIV">';
	html += '<table class="positions" style="width:100%;" id="' + itemsTable
			+ '_T">';
	html += '<thead id="head">';
	html += '<tr id="tr">';
	// draw columns headers
	$.each(columns, function(index, column) {
		html += '<td width="' + column.width + '%">' + column.label + '</td>';
	});
	html += '</tr></thead><tbody></tbody></table>';
	html += '</div><br>';
	// totals table
	html += '<table width="100%"" cellpadding="0" cellspacing="0" border="0">';
	html += '<tr>';
	html += '<td width="55%" class="dataLabel" valign="top">';
	html += '&nbsp;';
	html += '</td>                                                                               <!--color:#b3b9cf;-->';
	html += '<td width="40%" class="dataField" style="text-align: left;">';
	html += '<br>';
	html += '<table  id="result_table" cellpadding="0" cellspacing="0" style="width:100%; height:100%; border: 1px solid rgb(48,192,255);">';
	html += '</table>';
	html += '</td>';
	html += '<td width="5%" class="dataField" style="text-align: left;">&nbsp;</td>';
	html += '</tr>';
	html += '</table>';
	// sort? why not!
	/*
	 * html += 'Sortowanie:&nbsp;'; html += '<select id="sort_field"
	 * onChange="sortTable();"'; html += '<option value=""></option>'; html += '<option
	 * value="name">Nazwa</option>'; html += '<option value="code">Kod</option>';
	 * html += '<option value="category">Kategoria</option>'; html += '<option
	 * value="category">Kategoria</option>'; html += '<option
	 * value="price">Cena po<br>upuście</option>'; html += '<option
	 * value="total">Wartość</option>'; html += '</select>';
	 */
	$('#' + itemsTable).html(html);
}

function DrawSummary() {
	$("#result_table").html('');
	html = '';
	html += '<tr id="total_tr"> ';
	html += '<td class="positionsLabel" style="border-top:0px;">Suma rat i odsetek</td>';
	html += '<td class="positionsField" style="border-top:0px;"><input type="text" style="border:0px;font-weight:900;width:100%;text-align:right;" readonly="readonly" name="t_total" id="t_total" value=\'\'></td>';
	html += '</tr>';
	html += '<tr id="interest_rate_tr"> ';
	html += '<td class="positionsLabel">Suma odsetek</td>';
	html += '<td class="positionsField"><input type="text" readonly="readonly" style="border:0px;font-weight:900;width:100%;text-align:right;" name="t_interest_rate" id="t_interest_rate" value=\'\'></td>';
	html += '</tr>';
	html += '<tr id="rate_of_commission_tr"> ';
	html += '<td class="positionsLabel">Suma prowizji</td>';
	html += '<td class="positionsField"><input type="text" readonly="readonly" style="border:0px;font-weight:900;width:100%;text-align:right;" name="t_rate_of_commission" id="t_rate_of_commission" value=\'\'></td>';
	html += '</tr>';
	html += '<tr id="principal_value_tr"> ';
	html += '<td class="positionsLabel">Suma rat kapitałowych</td>';
	html += '<td class="positionsField"><input type="text" readonly="readonly" style="border:0px;font-weight:900;width:100%;text-align:right;" name="t_principal_value" id="t_principal_value" value=\'\'></td>';
	html += '</tr>';
	$("#result_table").html(html);
}
function searchProducts() {
	var searchKey = $('#searchProductsInput').val();
	if (searchKey.length < 2 && searchKey != '%') {
		return;
	}
	$("#searchResultDiv").html(
			'<img src="modules/EcmAgreements/images/loading.gif"/>');
	setTimeout(function() {
		if (searchKey == $('#searchProductsInput').val()) {
			var params = {
				job : 'searchProducts',
				searchKey : searchKey,
				searchCategory : $("#productSearchCategory :selected").val(),
				searchStock : $("#productSearchStock :selected").val(),
				searchSort : $("#productSearchSort :selected").val(),
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				success : function(data) {
					if (data != '-1')
						if (data.length == 0)
							$('#searchResultDiv').html(
									'MOD.LBL_SEARCH_NO_RESULT');
						else
							createSearchResult(data);
				},
				data : params
			});
		}
	}, 1000);
}

function createSearchResult(data) {
	var html = '<table style="text-align: center;" cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">';
	html += '<theader><tr>';
	html += '<th  style="width: 15pt; margin: auto auto;">&nbsp</th>';
	html += '<th style="width: 100pt; text-align: center;">Kod</th>';
	html += '<th style="width: 300pt; text-align: center;">Nazwa</th>';
	if ($("#productSearchStock :selected").val() != '1')
		html += '<th  style="width: 30pt; text-align: center;">Stan</th>';
	html += '<th  style="width: 15pt; margin: auto auto;">&nbsp</th>';

	html += '</tr></thead>';
	var counter;
	$
			.each(
					data,
					function(index, value) {
						if(counter%2==0){
							html += '<tr style="height: 15pt;" class="oddListRowS1">';
						} else {
							html += '<tr style="height: 15pt;" class="evenListRowS1">';
						}
						html += '<td style=""><input id="prod_'
								+ value.id + '" type="checkbox"/></td>';
						html += '<td style="" onClick="$(\'#prod_'
								+ value.id
								+ '\').prop(\'checked\', true);">'
								+ value.code + '</td>';
						html += '<td style="" onClick="unsetAllCheckboxes(); $(\'#prod_'
								+ value.id
								+ '\').prop(\'checked\', true); return addProducts();">'
								+ value.name + '</td>';
						if ($("#productSearchStock :selected").val() != '1')
							html += '<td style="">'
									+ value.stock_state + '</td>';
						html += '<td style="">';
						html += '<img style="cursor: pointer;" src="modules/EcmSales/images/search.gif" onClick="if ($(\'#search_info_div_'
								+ value.id
								+ '\').css(\'display\')==\'none\') getSearchInfo(\''
								+ value.id
								+ '\',\''
								+ value.code
								+ '\'); else $(\'#search_info_div_'
								+ value.id
								+ '\').hide(\'slow\')"/>';
						html += '<div id="'
								+ 'search_info_div_'
								+ value.id
								+ '" style="display:none;float:right;text-align:right;border: 1px #cccccc solid;padding:3px;"></div>';
						html += '</td>';
						html += '</tr>';
						searchedProducts.push(value.id);
						counter++;
					});
	// add button
	html += '</table><br>';
	html += 'Cena:&nbsp<input type="text" id="searchInputPrice" value=""/>&nbspIlość:&nbsp<input type="text" id="searchInputQty" value=""/>';
	html += '<br><br><input type="button" value="Dodaj wiele" onClick="return addProducts();"/>';
	$('#searchResultDiv').html(html);
}

function unsetAllCheckboxes() {
	$("#searchResultDiv input[type=checkbox]").each(function() {
		$(this).prop("checked", false);
	});
}

function addProducts() {
	$(".loading_panel").css("display", "block");
	var products = new Array();
	$.each(searchedProducts, function(index, value) {
		if ($('#prod_' + value).is(':checked'))
			products[value] = true;
	});
	var pricebook = $("#pricebook_id :selected").val();
	for ( var key in products) {
		var params = {
			job : 'getProduct',
			id : key,
			pricebook : pricebook,
			account_id : $("#parent_id").val(),
			language : $("#ecmlanguage").val(),
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
				if (data != '-1') {
					var p = new Object();
					p.product_id = data.id;
					p.name = data.name;
					p.product_code = data.code;
					p.product_id = data.id;
					p.ecmvat_id = data.ecmvat_id;
					p.ecmvat_value = data.ecmvat_value;
					p.ecmvat_name = data.ecmvat_name;
					p.product_ean = data.ean;
					p.product_ean2 = data.ean2;
					p.unit_name = data.unit_name;
					p.unit_id = data.unit_id;
					p.price_start = data.price_start;
					p.recipient_code = data.recipient_code;
					if ($("#searchInputPrice").val() != ''
							&& !isNaN(parseFloat(UnformatNumber($(
									"#searchInputPrice").val()))))
						p.price_start = $("#searchInputPrice").val();
					if ($("#searchInputQty").val() != ''
							&& !isNaN(parseFloat(UnformatNumber($(
									"#searchInputQty").val()))))
						p.quantity = $("#searchInputQty").val();
					items.push(p);
				}
			},
			data : params
		});
	}
	FillTable(items);
	// clear results
	$('#searchResultDiv').html('');
	searchedProducts = new Array();
	$('#searchProductsInput').val('');

	$(".loading_panel").css("display", "none");
}

function getItems(editview) {
	var record = '';
	if ($("#duplicate").val() == true)
		record = $("input[name='return_id']").val();
	else
		record = $("input[name='record']").val();
	
	var type = '';
	if ($("#is_correct").val() == true)
		type=true;
	else
		type='';
	
	if (isNaN(editview))
		editview = true;
	var params = {
		job : 'getItems',
		record : record,
		type : type,
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		success : function(data) {
			items = data;
			if (editview)
				FillTable(items, false);
			else
				FillTable(items, true);
			$(".loading_panel").css("display", "none");
		},
		data : params
	});
}

function getItemsFromWZ(editview) {
	var record = '';

	if ($("#is_wz").val() == true)
		record = $("input[name='wz_id']").val();
	else
		record = $("input[name='wz_id']").val();
	
	var type = '';
	if ($("#is_correct").val() == true)
		type=true;
	else
		type='';
	
	if (isNaN(editview))
		editview = true;
	var params = {
		job : 'getItemsFromWZ',
		record : record,
		type : type,
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		success : function(data) {
			items = data;
			if (editview)
				FillTable(items, false);
			else
				FillTable(items, true);
			$(".loading_panel").css("display", "none");
		},
		data : params
	});
}

function DrawDetailSummary() {
	DrawSummary();
	$("#t_total").val(FormatNumber($("#total_total").val()));
	$("#t_interest_rate").val(FormatNumber($("#total_interest_rate").val()));
	$("#t_rate_of_commission").val(FormatNumber($("#total_rate_of_commission").val()));
	$("#t_principal_value").val(FormatNumber($("#total_principal_value").val()));

}

function changeLanguage() {
	$(".loading_panel").css("display", "block");
	var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
	for (var index = 0; index != count; index++) {
		var params = {
			job : 'getTranslation',
			product_id : $("#product_id_" + index).val(),
			language : $("#ecmlanguage").val(),
			unit_id : $("#unit_id_" + index).val(),
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			async : false,
			dataType : "json",
			success : function(data) {
				$("#name_" + index).val(data.name);
				$("#unit_name_" + index).val(data.unit_name);
				calculateRow(index);
			},
			data : params
		});
	}
	$(".loading_panel").css("display", "none");
}

function getPricesInfo(index) {
	$("#price_start_div_" + index).show('slow');
	$("#price_start_div_" + index).html(
			'<img src="modules/EcmAgreements/images/loading.gif"/>');

	var params = {
		job : 'getPricesInfo',
		product_id : $("#product_id_" + index).val(),
		pricebook_id : $("#pricebook_id :selected").val(),
		account_id : $("#parent_id").val(),
	};
	$
			.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
					html = '<ul style="font-size: 7pt;">';
					$
							.each(
									data,
									function(key, value) {
										
										if (value.name == 'pricebook') {
											html += '<li style="cursor:pointer;" onClick="$(\'#price_start_'
													+ index
													+ '\').val(\''
													+ FormatNumber(value.price)
													+ '\'); $(this).closest(\'div\').hide(\'slow\');calculateRow('
													+ index
													+ ')"><u>'
													+ $(
															"#pricebook_id :selected")
															.html()
													+ ': '
													+ FormatNumber(value.price)
													+ '</u></li>';
										} else if (value.name == $(
												"#ecmprice_name").val()) {
											html += '<li style="cursor:pointer;" onClick="$(\'#price_start_'
													+ index
													+ '\').val(\''
													+ FormatNumber(value.price)
													+ '\'); $(this).closest(\'div\').hide(\'slow\');calculateRow('
													+ index
													+ ');"><b>'
													+ value.name
													+ ': '
													+ FormatNumber(value.price)
													+ '</b></li>';
										} else {
											html += '<li style="cursor:pointer;" onClick="$(\'#price_start_'
													+ index
													+ '\').val(\''
													+ FormatNumber(value.price)
													+ '\'); $(this).closest(\'div\').hide(\'slow\');calculateRow('
													+ index
													+ ');">'
													+ value.name
													+ ': '
													+ FormatNumber(value.price)
													+ '</li>';
										}
									});
					html += '</ul>';
				},
				data : params
			});
	$("#price_start_div_" + index).html(html);
}

function getSearchInfo(product_id, product_code) {
	$("#search_info_div_" + product_id).show('slow');
	var html = '<a href="index.php?module=EcmProducts&action=DetailView&record='
			+ product_id + '" target="_blank">' + product_code + '</a><br><br>';
	html += '<table><tr><td><table><tr><td>';
	// get prices info
	var params = {
		job : 'getPricesInfo',
		product_id : product_id,
		pricebook_id : $("#pricebook_id :selected").val(),
		account_id : $("#parent_id").val(),
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async : false,
		success : function(data) {
			html += 'Ceny<br>';
			$.each(data, function(key, value) {
				if (value.name == 'pricebook')
					html += $("#pricebook_id :selected").html() + ': '
							+ FormatNumber(value.price) + '<br>';
				if (value.name == $("#ecmprice_name").val())
					html += '<b>' + value.name + ': '
							+ FormatNumber(value.price) + '</b><br>';
				else
					html += value.name + ': ' + FormatNumber(value.price)
							+ '<br>';
			});
		},
		data : params
	});
	html += '</td></tr></table></td><td><table><tr><td>';
	var params = {
		job : 'getStockArray',
		product_id : product_id,
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async : false,
		success : function(data) {
			html += 'Stany<br>';
			$.each(data, function(key, value) {
					html += key + ': ' + FormatNumber(value)
							+ '<br>';
			});
		},
		data : params
	});
	html += '</td></tr></table></td>';
	var show_purchase_prices = false;
	
	if (show_purchase_prices) {
		html+='<td><table><tr><td>';
		var params = {
				job : 'getPurchaseArray',
				product_id : product_id,
			};
			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
					console.log(data);
				},
				data : params
			});		
		html+='</td></tr></table></td>';
	}
	
	html+='</tr></table>';

	$("#search_info_div_" + product_id).html(html);
}

//sortable rows in main table
$("#"+itemsTable+" tbody").sortable();
//get parent info use ajax
function getParentInfo(parent_id, parent_type) {
	var params = {
			id : parent_id,
			type : parent_type,
			job : 'getParentInfo'
	};
		
	$.ajax({
			type: "POST",
			url: ajax_url,
			dataType : "json",
			success: function(data) {
				if (data == '-1') {
					alert('Błąd');
					$("#parent_name").val('');
					$("#parent_id").val('');
				} else {
					setParentInfo(data);
				}
			},
			data: params
	});
	getAddresses(parent_id);
	getPayers(parent_id);
}

//insert parent info in fields
function setParentInfo(data) {
	//pricebooks
	createPricebookSelect(data.pricebooks);
	if (data.ecmprice_id && data.ecmprice_name) {
		$("#ecmprice_id").val(data.ecmprice_id);
		$("#ecmprice_name").val(data.ecmprice_name);
	}
	if ($("#new_number").val() == false) return; //if edit exists load only pricebooks
	if (data.name)
		$("#parent_name_copy").val(data.name);
	if (data.parent_nip)
		$("#parent_nip").val(data.parent_nip);
	if (data.parent_nip)
		$("#parent_regon").val(data.parent_regon);
	if (data.parent_address_street)
		$("#parent_address_street").val(data.parent_address_street);
	if (data.parent_address_city)
		$("#parent_address_city").val(data.parent_address_city);
	if (data.parent_address_postalcode)
		$("#parent_address_postalcode").val(data.parent_address_postalcode);
	if (data.parent_address_country)
		$("#parent_address_country").val(data.parent_address_country);
	if (data.invoice_type && data.invoice_type!='K')
		$("#no_tax").attr('checked', true);
	if (data.ecmpaymentcondition_id && data.ecmpaymentcondition_name) {
		$("#ecmpaymentcondition_id").val(data.ecmpaymentcondition_id);
		$("#ecmpaymentcondition_name").val(data.ecmpaymentcondition_name);
	}
	if (data.ecmdeliverycondition_id && data.ecmdeliverycondition_name) {
		$("#ecmdeliverycondition_id").val(data.ecmdeliverycondition_id);
		$("#ecmdeliverycondition_name").val(data.ecmdeliverycondition_name);
	}
	if (data.currency_id) 
		$("#currency_id option[value=\""+data.currency_id+"\"]").attr('selected', 'selected');
	//hide loading
	$(".loading_panel").css("display", "none");
}

function createPricebookSelect(pricebooks) {
	var s = $("<select id=\"pricebook_id\"/>");
	var opt = '';
	$.each(pricebooks, function(index, value) {
		opt+='<option value="'+value.id+'">'+value.name+'</option>';
	});
	s.html(opt);
	$("#pricebooks").append(s);
}

function generateNumber(stock_id) {
	var params = {
			job : 'generateNumber',
			stock_id : stock_id
	};
		
	$.ajax({
			type: "POST",
			url: ajax_url,
			dataType : "json",
			success: function(data) {
				if (data == '-1') {
					//try loading again
					generateNumber(stock_id);
				} else {
					$("#document_no").val(data.document_no);
					$("#number").val(data.number);
					$(".loading_panel").css("display", "none");
				}
			},
			data: params
	});	
}
function formattedDate(date) {
    var d = new Date(date || Date.now()),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [day, month, year].join('.');
}

function generateNumberCorrect() {
	var params = {
			job : 'generateNumberCorrect'
	};
		
	$.ajax({
			type: "POST",
			url: ajax_url,
			dataType : "json",
			success: function(data) {
				if (data == '-1') {
					//try loading again
					generateNumberCorrect();
				} else {
					$("#document_no").val(data.document_no);
					$("#number").val(data.number);
					$(".loading_panel").css("display", "none");
				}
			},
			data: params
	});	
}
$.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 getCategoriesList() {
	var params = {
			job : 'getCategoriesList'
	};
		
	$.ajax({
			type: "POST",
			url: ajax_url,
			dataType : "json",
			success: function(data) {
				var html = '<option value=""></option>';
				$.each(data, function(index, value){
					html+='<option value="'+value.id+'">'+value.name+'</option>';
					$("#productSearchCategory").html(html);
				});
			},
			data: params
	});		
}

function DrawFormaWplatyTable(){
	// Initialize appendGrid
    $('#formaWplatyTable').appendGrid({
        initRows: 1,
        hideRowNumColumn: true,
        columns: [
                  { name: 'date', display: 'Data', type: 'custom', value: '', cellCss: { 'text-align': 'right' },
                      customBuilder: function (parent, idPrefix, name, uniqueIndex) {
                          // Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                          var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                          // Create a span as a container
                          var ctrl = document.createElement('span');
                          // Set the ID and name to container and append it to parent control which is a table cell
                          $(ctrl).attr({ id: ctrlId, name: ctrlId }).appendTo(parent);
                          // Create extra controls and add to container
                          $('<div style="text-align: right;vertical-align: text-top;">').appendTo(ctrl);
                          $('<input>', { type: 'text', maxLength: 10, id: ctrlId + '_date',name: ctrlId + '_date',style: 'width:100px;text-align:right;', class: 'inputs'}).appendTo(ctrl);
                          $('<img border="0" id="'+ctrlId + '_tigger'+'" align="absmiddle" alt="Wprowadź datę" src="themes/Sugar5/images/jscalendar.gif?s=bed8cd35065048ceebdc639ebe305e2c&c=1"></div>').appendTo(ctrl);
                          $('<script type="text/javascript">Calendar.setup ({inputField : "'+ctrlId + '_date'+'",daFormat : "%d.%m.%Y %H:%M",button : "'+ctrlId + '_tigger'+'",singleClick : true,dateStr : "",step : 1,weekNumbers:false});</script>').appendTo(ctrl);
         
                          // Finally, return the container control
                          return ctrl;
                      },
                      customGetter: function (idPrefix, name, uniqueIndex) {
                      	// Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                          var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                          // Check the input value and split it to array if valid
                  
                          // Set the value to different spinners
                         return $('#' + ctrlId + '_date').val();
                      
                      },
                      customSetter: function (idPrefix, name, uniqueIndex, value) {
                          // Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                          var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                          // Check the input value and split it to array if valid
                
                          // Set the value to different spinners
                         $('#' + ctrlId + '_date').val(value);
                      }
                  },
                { name: 'forma', display: 'Forma', type: 'select',  ctrlOptions: {1: 'Gotówka', 2: 'Przelew'}, ctrlCss: {'text-align': 'right','float': 'right'}},
                { name: 'amount', display: 'Kwota', type: 'text', ctrlAttr: {maxlength: 100}, ctrlCss: {width: '100%','text-align': 'right'}, ctrlClass: 'inputs',
                	onChange: function (evt, rowIndex) {
                    	// liczenie vatu
                            var data = $('#formaWplatyTable').appendGrid('getRowValue', rowIndex);
                 
                                $('#formaWplatyTable').appendGrid('setCtrlValue', 'amount', rowIndex, FormatNumber(data.amount));
                        
                        }, 
                        onClick: function (evt, rowIndex) {
                        	// zaznacznie wybranego pola
                        	 var elem = $('#formaWplatyTable').appendGrid('getCellCtrl', 'amount', rowIndex);
                            $(elem).select();
                        }},
                { name: 'number', display: 'Nr rachunku', type: 'text',ctrlAttr: {maxlength: 255}, ctrlCss: {width: '100%','text-align': 'right'}, ctrlClass: 'inputs',},
                { name: 'recordId', type: 'hidden', value: 0 }
            ],
            hideButtons: {
                
            	moveUp: true,
            	moveDown: true,
            	remove: true,
                insert: true,
             
            },
	    // custome guziczki
	    customGridButtons: {
	        insert: $('<img>').css('color', 'red').text('Insert').get(0),
	        // Use a function that create DOM element
	        moveUp: function (){
	            var button = document.createElement('img');
	            button.src = 'modules/EcmQuotes/images/moverowup.gif';
	            return button;
	        },
	        moveDown: function (){
	            var button = document.createElement('img');
	            button.src = 'modules/EcmQuotes/images/moverowdown.gif';
	            return button;
	        },
	        removeLast: function (){
	            var button = document.createElement('img');
	            button.src = 'modules/EcmQuotes/images/deleterow.gif';
	            return button;
	        },
	        append: function (){
	            var button = document.createElement('img'); 
	            button.src = 'modules/EcmQuotes/images/insertrow.gif';
	            return button;
	        }
	    },  i18n: {
	    	append: 'Dodawanie rekordu',
	    	remove: 'Usuwanie rekordu',
	    	insert: 'Dodanie rekordu nad',
	    	moveUp: 'Przesuń rekord w górę',
	    	moveDown: 'Przesun rekord w dół',
	    	removeLast: 'Usuń ostatni wiersz',
	    	rowEmpty: 'Brak rekordów'
	    	}
    });
    // Handle `Load` button click
    $('#btnLoad').button().click(function () {
        $('#tblAppendGrid').appendGrid('load', [
            { 'Album': 'Dearest', 'Artist': 'Theresa Fu', 'Year': '2009', 'Origin': 1, 'Poster': true, 'Price': 168.9, 'RecordId': 123 },
            { 'Album': 'To be Free', 'Artist': 'Arashi', 'Year': '2010', 'Origin': 3, 'Poster': true, 'Price': 152.6, 'RecordId': 125 },
            { 'Album': 'Count On Me', 'Artist': 'Show Luo', 'Year': '2012', 'Origin': 2, 'Poster': false, 'Price': 306.8, 'RecordId': 127 },
            { 'Album': 'Wonder Party', 'Artist': 'Wonder Girls', 'Year': '2012', 'Origin': 4, 'Poster': true, 'Price': 108.6, 'RecordId': 129 },
            { 'Album': 'Reflection', 'Artist': 'Kelly Chen', 'Year': '2013', 'Origin': 1, 'Poster': false, 'Price': 138.2, 'RecordId': 131 }
        ]);
    });
    
    $('thead').removeClass('ui-widget-header');
    $('td').removeClass('ui-widget-header');
    $('tbody').removeClass('ui-widget-content');
    $('td').removeClass('ui-widget-content');
    $('tfoot').removeClass('ui-widget-header');
}