{% load i18n l10n %}

{% get_current_language as LANGUAGE_CODE %}


<div id="{{view_name}}_div_excel_csv" class="excel_container">
	<a id = "excel_{{view_name}}" href="#"  alt="{% trans 'Save CDRs whith current settings' %}">Excel</a>
	<a id="csv_{{view_name}}" href="#"  alt="{% trans 'Save CDRs whith current settings' %}">CSV</a>
</div>


<script type="text/javascript" lang="text/javascript">

	

	$("#excel_{{view_name}}").button({icons: {primary: "ui-icon-disk"}});
 	$("#csv_{{view_name}}").button({icons: {primary: "ui-icon-disk"}});  //.attr('style','font-size:0.7em');
	
	

	$('#excel_{{view_name}}').click(function(e) {
		if (checkTotalRowNum('{{view_name}}') == true)
		{
			{{view_name}}_callback('excel');
			saveExcel('{{view_name}}_filters_form','{{URL_EXCEL}}',param);
			createMessagesLocal('{{view_name}}_result_messages',"{% trans 'Generating excel ... ' %}", 'info', 3000);	
		}
		else
		{
			createMessagesLocal('{{view_name}}_result_messages',"{% trans 'There is a lot of data. Please select a filter' %}", 'error', 3000);	
		}

		return false;
	});

	$('#csv_{{view_name}}').click(function(e) {
		console.log('calculando csv')
		url = '{{URL_EXCEL}}'
		url = url.replace('excel','csv')
		{{view_name}}_callback('excel');
		saveExcel('{{view_name}}_filters_form',url,param);

		return false;
	});


function checkTotalRowNum(name_view)
{
	num_total_row = $('#'+name_view+'_grid_pager_right').children().html();
	num_total_row= num_total_row.substring(num_total_row.indexOf("of")+3,num_total_row.length);
	num_total_row = num_total_row.replace(',','');
	num_total_row = parseInt(num_total_row);

	if (num_total_row<65000)
		return true
	else
		return false

}





function saveExcel(form_id,url,param)
{
	console.log('paraaaaam',param);

	if (param == null){
	   param = 0;
	 }
	error = false;
	if (param != 0)
		data = $('#'+form_id).serialize() + param ;
	else
		data = $('#'+form_id).serialize();


	$.fileDownload(url, {
		data: data,
	    failCallback: function () {
	 		error = true
	 		createMessagesLocal('{{view_name}}_result_messages',"{% trans 'There was a problem generating your report, please try again.' %}", 'error', 3000);	
	    },
		//preparingMessageHtml: console.log("We are preparing your report, please wait..."),
		//failMessageHtml: "There was a problem generating your report, please try again.",
	});

	if (error == false){
		createMessagesLocal('{{view_name}}_result_messages',"{% trans 'We are preparing your report, please wait...' %}", 'success', 3000);	
	}
}



</script>