$(document).ready(function(){
	$("#clearTrader").on('click', clearTrader);
    $("#selectTrader").on('click', selectTrader);
	$("#clearAccount").on('click', clearAccount);
    $("#selectAccount").on('click', selectAccount);
	Calendar.setup ({
		inputField : "date_from",
		daFormat : "%d.%m.%Y",
		button : "date_from_trigger",
		singleClick : true,
		dateStr : "",
		step : 1
	});
	
	Calendar.setup ({
		inputField : "date_to",
		daFormat : "%d.%m.%Y",
		button : "date_to_trigger",
		singleClick : true,
		dateStr : "",
		step : 1
	});
	
	$.tablesorter.addParser({ 
        // set a unique id 
        id: 'money', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s) { 
            // format your data for normalization 
            return s.replace('.','').replace(',','.'); 
        },
        // set type, either numeric or text 
        type: 'numeric' 
    });
	
	$.tablesorter.addParser({ 
        // set a unique id 
        id: 'INCOME_OVERHEAD', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s) { 
            // format your data for normalization 
			var position = s.indexOf("(");
			var cutted_string = trim(s.substring(0,position));
			cutted_string = cutted_string.replace('.','').replace(',','.');
            return cutted_string;
        },
        // set type, either numeric or text 
        type: 'numeric' 
    });
	
	$("#myTable").tablesorter({
        theme: 'blue',
		sortList: [[0,0], [4,0]],
		textExtraction: getTextExtractor(),
		headers: { 
			
			

			4: { 
				sorter:'money' 
			},
			5: { 
				sorter:'money' 
			},
			6: { 
				sorter:'INCOME_OVERHEAD' 
			},
			7: { 
				sorter:'INCOME_OVERHEAD' 
			},
		} 
    });
});
function generateXLS(){
	var data = {}
	$.each($("#SearchTable").find('input, select'), function (key,input){
	  data[$(input).prop('name')] = $(input).val();
	  
	});
	$.ajax({
		type: "POST",
		url: 'index.php?module=EcmReports&action=ReportSalesByProduct&to_pdf=1&to_xls=1',
		dataType: "html",
		data: data,
        async: false,
		success: function(response){
			var new_window = window.open(response);
		},
	//	dataType: 'html',
	});
}
function generatePDF(){
	var data = {}
	$.each($("#SearchTable").find('input, select'), function (key,input){
	  data[$(input).prop('name')] = $(input).val();
	  
	});
	var sortable={};
	$.each($("#myTable").find('.sortby'), function (key,input){
		if($(input).hasClass('headerSortDown')){
		  sortable[$(input).html().trim()] = 'ASC';
		}else if($(input).hasClass('headerSortUp')){
			 sortable[$(input).html().trim()] = 'DESC';
		}
		  
		});
	data['sort']=sortable;
	
	$.ajax({
		type: "POST",
		url: 'index.php?module=EcmReports&action=ReportSalesByProduct&to_pdf=1',
		dataType: "html",
		data: data,
        async: false,
		success: function(response){
			var new_window = window.open(response);
		},
	//	dataType: 'html',
	});
}

function clearTrader() {
    console.log('Czyszczenie wybranego sprzedawcy');
    $('#trader').val('');
	console.log('Gotowe!');
}

function selectTrader() {
    open_popup('Users', 600, 400, '', true, false, {'call_back_function': 'setTrader', 'form_name': 'ReportSalesByProduct', 'field_to_name_array': {'id': 'id'}}, 'single', true);
}

function setTrader(selectedTrader){
	$("#trader").val(selectedTrader.name_to_value_array.id);
}

function clearAccount() {
    console.log('Czyszczenie wybranego sprzedawcy');
	$('#account_id').val('');
	$('#account_name').val('');
	console.log('Gotowe!');
}

function selectAccount() {
    open_popup('Accounts', 800, 500, '', true, false, {'call_back_function': 'set_return', 'form_name': 'ReportSalesByProduct', 'field_to_name_array': {"id":"account_id","name":"account_name"}}, 'single', true);
}
function getTextExtractor()
{
  return (function() {
    var patternLetters = /[öäüÖÄÜáàâéèêúùûóòôÁÀÂÉÈÊÚÙÛÓÒÔßąĄśŚćĆęĘńŃłŁ]/g;
    var patternDateDmy = /^(?:\D+)?(\d{1,2})\.(\d{1,2})\.(\d{2,4})$/;
    var lookupLetters = {
      "ä": "a", "ö": "o", "ü": "u",
      "Ä": "A", "Ö": "O", "Ü": "U",
      "á": "a", "à": "a", "â": "a",
      "é": "e", "è": "e", "ê": "e",
      "ú": "u", "ù": "u", "û": "u",
      "ó": "o", "ò": "o", "ô": "o",
      "Á": "A", "À": "A", "Â": "A",
      "É": "E", "È": "E", "Ê": "E",
      "Ú": "U", "Ù": "U", "Û": "U",
      "Ó": "O", "Ò": "O", "Ô": "O",
      "ß": "s",'a':'ą','Ą':'A','ś':'s,','Ś':'S','ć':'c','Ć':'C','ę':'e','ń':'n','Ń':'N','ł':'l','Ł':'L','Ę':'E',
    };
    var letterTranslator = function(match) { 
      return lookupLetters[match] || match;
    }

    return function(node) {
      var text = $.trim($(node).text());
      var date = text.match(patternDateDmy);
      if (date)
        return [date[3], date[2], date[1]].join("-");
      else
        return text.replace(patternLetters, letterTranslator);
    }
  })();
}