(function($){

	$.fn.searchquery = function(formData, attempt) {
		$.ajax({
			type: "post",
			url: "app/includes/ajax.php",
			data: formData
		}).done(function(data){
			try {
				data = JSON.parse(data);
				$("#display-result").html(data);
				if(formData.cache !== "no_cache") {
					localStorage.setItem(formData.query_function, $("#display-result").html());
					var args = $("#search-form").serializeObject();
					localStorage.setItem(formData.query_function+"_args", JSON.stringify(args));
				}
				$('#bootstrap-data-table').DataTable({
			        lengthMenu: [[50, 75, 100, -1], [50, 75, 100, "All"]]
			    });

			    $('#bootstrap-data-table-export').DataTable({
			        dom: 'lBfrtip',
			        lengthMenu: [[50, 75, 100, -1], [50, 75, 100, "All"]],
			        buttons: [
			            {
					        extend: 'copy',
					        text: 'Copy',
					        className: 'btn btn-default',
					        exportOptions: {
					            columns: ':not(.notexport)'
					        }
					    },
					    {
					        extend: 'csv',
					        text: 'CSV',
					        className: 'btn btn-default',
					        exportOptions: {
					            columns: ':not(.notexport)'
					        }
					    },
					    {
					        extend: 'excel',
					        text: 'Excel',
					        className: 'btn btn-default',
					        exportOptions: {
					            columns: ':not(.notexport)'
					        }
					    },
					    {
					        extend: 'pdf',
					        text: 'PDF',
					        className: 'btn btn-default',
					        exportOptions: {
					            columns: ':not(.notexport)'
					        }
					    },
					    {
					        extend: 'print',
					        text: 'Print',
					        className: 'btn btn-default',
					        exportOptions: {
					            columns: ':not(.notexport)'
					        }
					    }
			        ]
			    });
			}
			catch(err) {
				console.log(err);
				console.log(data);
			}
			finally {
				$("#search-query-btn").html("Search Now").attr("disabled", false);
			}
		}).fail(function(e){
			if(attempt < 3) {
				attempt++;
				$("#search-query-btn").html("<em>Retrying, please wait...</em>").attr("disabled", true);
				$("#display-result").searchquery(formData, attempt);
			} else {
				$.alert("Error in network connection. Please try again later");
				$("#search-btn").html("Search Now").attr("disabled", false);
			}
		})
	}
})(jQuery)

jQuery(document).ready(function($){
	var qf = $("#search-form input[name=query_function]").val();
	var cache = $("#search-form input[name=cache]").val();
	var last_query = localStorage.getItem(qf);
	if(last_query !== null && cache !== "no_cache") {
		warningText = "<br/><span class=\"fa fa-warning text-warning\"></span><em> Notice!!! This was loaded automatically from the system cache and may not represent the current figures. To update the figures, please re-run the query above<em><br/>";
		$("#display-result").html(warningText+last_query);
		var args = localStorage.getItem(qf+"_args");
		try {
			args = JSON.parse(args);
			$.each(args, function(i, v){
				var e = $("#search-form [name="+i+"]");
				if($(e).length < 1) {
					var e = $("#search-form [name^="+i+"");
				}
				$(e).val(v);
			})
			$(".standardSelect").trigger("chosen:updated");
		} catch(err) {
			console.log(err);
		}
		finally{}
		$('#bootstrap-data-table').DataTable({
	        lengthMenu: [[50, 75, 100, -1], [50, 75, 100, "All"]]
	    });

	    $('#bootstrap-data-table-export').DataTable({
	        dom: 'lBfrtip',
	        lengthMenu: [[50, 75, 100, -1], [50, 75, 100, "All"]],
	        buttons: [
	            {
			        extend: 'copy',
			        text: 'Copy',
			        className: 'btn btn-default',
			        exportOptions: {
			            columns: ':not(.notexport)'
			        }
			    },
			    {
			        extend: 'csv',
			        text: 'CSV',
			        className: 'btn btn-default',
			        exportOptions: {
			            columns: ':not(.notexport)'
			        }
			    },
			    {
			        extend: 'excel',
			        text: 'Excel',
			        className: 'btn btn-default',
			        exportOptions: {
			            columns: ':not(.notexport)'
			        }
			    },
			    {
			        extend: 'pdf',
			        text: 'PDF',
			        className: 'btn btn-default',
			        exportOptions: {
			            columns: ':not(.notexport)'
			        }
			    },
			    {
			        extend: 'print',
			        text: 'Print',
			        className: 'btn btn-default',
			        exportOptions: {
			            columns: ':not(.notexport)'
			        }
			    }
	        ]
	    });
	}
	$(document).on("click", "#search-query-btn", function(e){
		e.preventDefault();
		$("#search-query-btn").html("<em>Loading...</em>").attr("disabled", true);
		var formData = $("#search-form").serializeObject();	
		$("#display-result").searchquery(formData, 1);
	})


});