var FormValidation = function () {

		return {
				//main function to initiate the module
				init: function () {

						// for more info visit the official plugin documentation:
						// http://docs.jquery.com/Plugins/Validation

						var form1 = $('#form');
						var error1 = $('.alert-danger', form1);
						var success1 = $('.alert-success', form1);

						jQuery.validator.setDefaults({
								errorElement: 'span', //default input error message container
								errorClass: 'help-block help-block-error', // default input error message classfocusInvalid: false, // do not focus the last invalid input
								ignore: "",
								invalidHandler: function (event, validator) { //display error alert on form submit
										success1.hide();
										error1.show();
										Metronic.scrollTo(error1, -200);
								},

								highlight: function (element) { // hightlight error inputs
										$(element)
												.closest('.form-group').addClass('has-error'); // set error class to the control group
								},

								unhighlight: function (element) { // revert the change done by hightlight
										$(element)
												.closest('.form-group').removeClass('has-error'); // set error class to the control group
								},

								success: function (label) {
										label
												.closest('.form-group').removeClass('has-error'); // set success class to the control group
								},

								submitHandler: function (form) {
										success1.show();
										error1.hide();
										form.submit();
								}
						});


				}

		};

}();

var FormValidationUsers = function () {

		return {
				//main function to initiate the module
				init: function () {

						// for more info visit the official plugin documentation:
						// http://docs.jquery.com/Plugins/Validation

						var form1 = $('.form-users');
						var error1 = $('.alert-error', form1);
						var success1 = $('.alert-success', form1);

						jQuery.validator.setDefaults({
								errorElement: 'span', //default input error message container
								errorClass: 'help-inline', // default input error message class
								focusInvalid: false, // do not focus the last invalid input
								ignore: "",
								invalidHandler: function (event, validator) { //display error alert on form submit
										success1.hide();
										error1.show();
										App.scrollTo(error1, -200);
								},

								highlight: function (element) { // hightlight error inputs
										$(element)
												.closest('.help-inline').removeClass('ok'); // display OK icon
										$(element)
												.closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
								},

								unhighlight: function (element) { // revert the change dony by hightlight
										$(element)
												.closest('.control-group').removeClass('error'); // set error class to the control group
								},

								success: function (label) {
										label
												.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
										.closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
								},

								submitHandler: function (form) {
										success1.show();
										error1.hide();
										form.submit();
								}
						});


				}

		};

}();

var TableAdvanced = function () {

		var initTable1 = function () {
				var table = $('.tableadvanced');

				/* Table tools samples: https://www.datatables.net/release-datatables/extras/TableTools/ */
				 $.fn.dataTableExt.oStdClasses.sFilterInput = "form-control input-xlarge input-inline";
				/* Set tabletools buttons and button container */


				var oTable = table.dataTable({
						// Internationalisation. For more info refer to http://datatables.net/manual/i18n
						"language": {
								"aria": {
										"sortAscending": ": activate to sort column ascending",
										"sortDescending": ": activate to sort column descending"
								},
								"emptyTable": "No hay informacion en la tabla",
								"info": "Mostrando del _START_ al _END_ de _TOTAL_ registros",
								"infoEmpty": "No se encontraron coincidencias",
								"infoFiltered": "(filtered1 de _MAX_ registros)",
								"lengthMenu": "Mostrar _MENU_ registros",
								"search": "Buscar:",
								"zeroRecords": "No se encontraron coincidencias"
						},
						"order": [
								// [0, 'asc']
						],
						"lengthMenu": [
								[20, 50, 75, 100,	-1],
								[20, 50, 75, 100,	"Todos"] // change per page values here
						],
						// set the initial value
						"pageLength": 10,
						"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>" // horizobtal scrollable datatable
						
				});

				var tableWrapper = $('.tableadvanced_wrapper'); // datatable creates the table wrapper by adding with id {your_table_jd}_wrapper

				tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown

				

		}

		return {

				//main function to initiate the module
				init: function () {

						if (!jQuery().dataTable) {
								return;
						}

					
						initTable1();
						

				}

		};

}();

var TablePagination = function () {

    var initTable3 = function () {

        var table = $('.tablePag');

        // begin: third table
        table.dataTable({

            // Internationalisation. For more info refer to http://datatables.net/manual/i18n
            "language": {
					"aria": {
							"sortAscending": ": activate to sort column ascending",
							"sortDescending": ": activate to sort column descending"
					},
					"emptyTable": "No hay informacion en la tabla",
					"info": "Mostrando del _START_ al _END_ de _TOTAL_ registros",
					"infoEmpty": "No se encontraron coincidencias",
					"infoFiltered": "(filtered1 de _MAX_ registros)",
					"lengthMenu": "Mostrar _MENU_ registros",
					"search": "Buscar:",
					"zeroRecords": "No se encontraron coincidencias"
			},
			
			"lengthMenu": [
					[20, 50, 75, 100,	-1],
					[20, 50, 75, 100,	"Todos"] // change per page values here
			],
			// set the initial value
			"pageLength": 10,
            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
            // So when dropdowns used the scrollable div should be removed.
            "dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            "bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.

            "order": [
                [0, "asc"]
            ] // set first column as a default sort by asc
        });

        var tableWrapper = jQuery('.tablePag_wrapper');

        // table.find('.group-checkable').change(function () {
        //     var set = jQuery(this).attr("data-set");
        //     var checked = jQuery(this).is(":checked");
        //     jQuery(set).each(function () {
        //         if (checked) {
        //             $(this).attr("checked", true);
        //         } else {
        //             $(this).attr("checked", false);
        //         }
        //     });
        //     jQuery.uniform.update(set);
        // });

        tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown
    }

    return {

        //main function to initiate the module
        init: function () {
            if (!jQuery().dataTable) {
                return;
            }

            initTable3();
        }

    };

}();

var handleDateFormat = function () {
		var shortDateFormat = 'dd/MM/yyyy';
		var longDateFormat	= 'dd/MM/yyyy HH:mm:ss';

		$(".shortDateFormat").each(function (idx, elem) {
				if (jQuery(elem).is(":input")) {
						jQuery(elem).val(jQuery.format.date(jQuery(elem).val(), shortDateFormat));
				} else {
						jQuery(elem).text(jQuery.format.date(jQuery(elem).text(), shortDateFormat));
				}
		});
		$(".longDateFormat").each(function (idx, elem) {
				if (jQuery(elem).is(":input")) {
						jQuery(elem).val(jQuery.format.date(jQuery(elem).val(), longDateFormat));
				} else {
						jQuery(elem).text(jQuery.format.date(jQuery(elem).text(), longDateFormat));
				}
		});
}

var handleDatePickers = function () {

	if (jQuery().datepicker) {
		$('.date-picker').datepicker({
			rtl: Metronic.isRTL(),
			orientation: "left",
			autoclose: true
		});
		//$('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
	}

	/* Workaround to restrict daterange past date select: http://stackoverflow.com/questions/11933173/how-to-restrict-the-selectable-date-ranges-in-bootstrap-datepicker */
}
var handleMultiSelect = function () {
		$('.multi-select').multiSelect({
				keepOrder: true
		});
		$('#select-all').click(function(){
		  $('.multi-select').multiSelect('select_all');
		  return false;
		});
		$('#deselect-all').click(function(){
		  $('.multi-select').multiSelect('deselect_all');
		  return false;
		});

}



var oTable;


var handleInputMasks = function () {
		$.extend($().inputmask.defaults, {
				'autounmask': true
		});

		$(".mask_phone").inputmask("mask", {"mask": "(999) 999-9999"}); //specifying fn & options
		$(".mask_number").inputmask({ "mask": "9", "repeat": 10, "greedy": false });	// ~ mask "9" or mask "99" or ... mask "9999999999"
		$(".mask_decimal").inputmask('decimal', { rightAlignNumerics: false }); //disables the right alignment of the decimal input
		$(".mask_currency").inputmask('999,999,999.99', { numericInput: true });
		// $(".mask_rfc").inputmask("mask", {"mask":"9-a{1,3}9{1,3}" });
}


$(document).ready(function() {

		if($('.numbersep').get(0) ){
				var numbersSeparation = function () {
						var numers = $('span.numbers');
						return numers.each(function(){
								$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
						})
				}
		}

		if($('#form').get(0) ){
				FormValidation.init();
		}

		if($('.tableadvanced').get(0) ){
				TableAdvanced.init();
		}

		if($('.tablePag').get(0) ){
				TablePagination.init();
		}

		if($('.longDateFormat').get(0) || $('.shortDateFormat').get(0)){
				handleDateFormat();
		}
		if($('.date-picker').get(0)){
			handleDatePickers();
		}
		
		if ($('.date-range').get(0) ){
				handleDateRangePickers();
		}

		if ($('.mask_phone').get(0) || $('.mask_number').get(0) || $('.mask_decimal').get(0) || $('.mask_currency').get(0)){
				handleInputMasks();
		}

		if ($('.multi-select').get(0)){
				 handleMultiSelect();
		}

		// $('.form_modal').click(function () {
	 //    	var $modal = $('#form_modal');
	 //        $modal.modal();
	 //    });
	//Override the default confirm dialog by rails
	$.rails.allowAction = function(link){
	  if (link.data("confirm") == undefined){
	    return true;
	  }
	  $.rails.showConfirmationDialog(link);
	  return false;
	}
	//User click confirm button
	$.rails.confirmed = function(link){
	  link.data("confirm", null);
	  link.trigger("click.rails");
	}
	//Display the confirmation dialog
	$.rails.showConfirmationDialog = function(link){
		bootbox.dialog({

	    	message: link.data("confirm"),
	    	buttons: {
				"Cancelar": {   
					label: "Cancelar",
					className: "btn-default"
				},
				success: {   
					label: "OK",
					className: "btn-primary",
					callback: function() {
						$.rails.confirmed(link);
					}
				}
	       	}
    	}); 
	}
	

});
