var FormValidation = function () {

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

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

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

						$.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();
										App.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.$.com/Plugins/Validation

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

						$.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');
				var filter = $('#filter').val();
		        var buscar_ = { };
		        var page_ = 0;
				/* Table tools samples: https://www.datatables.net/release-datatables/extras/TableTools/ */
				 $.fn.dataTableExt.oStdClasses.sFilterInput = "form-control input-medium input-inline";
				/* Set tabletools buttons and button container */

				if(filter != ""){ buscar_ = { search: filter }; }
				if( $('#current_page').length > 0 ){	page_ = ($('#current_page').val() - 1) * 20;}
				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": "(filtrado un total de _MAX_ registros)",
								"lengthMenu": "Mostrar _MENU_ registros",
								"search": "Buscar:",
								"zeroRecords": "No se encontraron coincidencias",
								"paginate": {
		                            "sPrevious": "Ant",
		                            "sNext": "Sig"
		                        }
						},
						"order": [
								// [0, 'asc']
						],
						"lengthMenu": [
								[20, 50, 75, 100,	-1],
								[20, 50, 75, 100,	"Todos"] // change per page values here
						],
						"search": buscar_,
						// set the initial value
						"pageLength": 20,
						"iDisplayStart": page_,
						"dom": "<'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
						"fnDrawCallback": function( oSettings ) {
							$('a.filtros').on( 'click', function (e) {
								e.preventDefault();
								var url_ = $(this).attr('href');
								url_ += '?filter=' + $('#filter').val();
								url_ += '&current_page=' + $('#current_page').val();
								console.log(url_);
								window.location.href = url_;

					        });
					        $('a.filtros2').on( 'click', function (e) {
								e.preventDefault();
								var url_ = $(this).attr('href');
								url_ += '&filter=' + $('#filter').val();
								url_ += '&current_page=' + $('#current_page').val();
								console.log(url_);
								window.location.href = url_;

					        });
						}

				});

				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

				if( $('#current_page').length > 0 ){
					$('.tableadvanced').on( 'page.dt', function () {
            var oSettings = oTable.fnSettings();
            var page = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
            $('#current_page').val(page);
	        });
				}
		}

		return {

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

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


						initTable1();


				}

		};

}();

var TableAdvancedSingleSelection = function () {

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

		$.fn.dataTableExt.oStdClasses.sFilterInput = "form-control input-medium input-inline";

		var oTable = table.DataTable({
			"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": "(filtrado un total de _MAX_ registros)",
					"lengthMenu": "Mostrar _MENU_ registros",
					"search": "Buscar:",
					"zeroRecords": "No se encontraron coincidencias",
					"paginate": {
                        "sPrevious": "Ant",
                        "sNext": "Sig"
                    }
			},
			"order": [],
			"lengthMenu": [
					[20, 50, 75, 100,	-1],
					[20, 50, 75, 100,	"Todos"]
			],
			"pageLength": 20,
	        "tableTools": {
	            "sRowSelect": "single"
	        },
			"dom": "<'row'<'col-md-6 col-sm-12 hidden'T><'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>>"
		});
		var tableWrapper = $('.tableadvanced_wrapper');
		tableWrapper.find('.dataTables_length select').select2();
	}
	return {
		init: function () {
			if (!$().dataTable) {
					return;
			}
			initTable1();
		}
	};
}();

var TableWithCheckbox = function () {
		//var rows_selected = [];
		var initTableCheckbox = function () {
				var table = $('.tableWithCheckbox');

				/* 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
			          	'columnDefs': [{
				            'targets': 0,
				            'searchable':false,
				            'orderable':false,
				            'className': 'dt-body-center',
			             	'render': function (data, type, full, meta) {
			                 	return '<input type="checkbox" name="id[]">';
			             	}
			          	}],
						"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": "(filtrado un total de _MAX_ registros)",
								"lengthMenu": "Mostrar _MENU_ registros",
								"search": "Buscar:",
								"zeroRecords": "No se encontraron coincidencias",
								"paginate": {
		                            "sPrevious": "Ant",
		                            "sNext": "Sig"
		                        }
						},
						'order': [3, 'asc'],
					      "rowCallback": function(row, data, dataIndex){
					         // Get row ID
					         var rowId = data[0];

					         // If row ID is in the list of selected row IDs
					         if($.inArray(rowId, rows_selected) !== -1){
					            $(row).find('input[type="checkbox"]').prop('checked', true);
					            $(row).addClass('selected');
					         }
					      },
						"lengthMenu": [
								[20, 50, 75, 100,	-1],
								[20, 50, 75, 100,	"Todos"] // change per page values here
						],
						// set the initial value
						"pageLength": -1,
						"dom": "<'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


				var table = $('.tableWithCheckbox').DataTable();
					// Handle click on checkbox
				   $('.tableWithCheckbox tbody').on('click', 'input[type="checkbox"]', function(e){
				      var $row = $(this).closest('tr');

				      // Get row data
				      var data = table.row($row).data();

				      // Get row ID
				      // var rowId = data[0];
				      var rowId = $row.attr('id').substring($row.attr('id').indexOf('_') + 1, $row.attr('id').length);
				      // Determine whether row ID is in the list of selected row IDs
				      var index = $.inArray(rowId, rows_selected);

				      // If checkbox is checked and row ID is not in list of selected row IDs
				      if(this.checked && index === -1){
				         rows_selected.push(rowId);

				      // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
				      } else if (!this.checked && index !== -1){
				         rows_selected.splice(index, 1);
				      }

				      if(this.checked){
				         $row.addClass('selected');
				        //$row.css('background-color', '#34495E');
				      } else {
				        //$row.css('background-color', '#F9F9F9');
				        $row.removeClass('selected');
				      }

				      // Update state of "Select all" control
				      updateDataTableSelectAllCtrl(table);

				      // Prevent click event from propagating to parent
				      e.stopPropagation();
				   });

				   // Handle click on table cells with checkboxes
				   $('.tableWithCheckbox').on('click', 'tbody td, thead th:first-child', function(e){
				      $(this).parent().find('input[type="checkbox"]').trigger('click');
				   });

				   // Handle click on "Select all" control
				   $('thead input[name="select_all"]', table.table().container()).on('click', function(e){
				      if(this.checked){
				         $('.tableWithCheckbox tbody input[type="checkbox"]:not(:checked)').trigger('click');
				      } else {
				         $('.tableWithCheckbox tbody input[type="checkbox"]:checked').trigger('click');
				      }

				      // Prevent click event from propagating to parent
				      e.stopPropagation();
				   });

				   // Handle table draw event
				   table.on('draw', function(){
				      // Update state of "Select all" control
				      updateDataTableSelectAllCtrl(table);
				   });

				   function updateDataTableSelectAllCtrl(table){
				   var $table             = table.table().node();
				   var $chkbox_all        = $('tbody input[type="checkbox"]', $table);
				   var $chkbox_checked    = $('tbody input[type="checkbox"]:checked', $table);
				   var chkbox_select_all  = $('thead input[name="select_all"]', $table).get(0);

				   // If none of the checkboxes are checked
				   if($chkbox_checked.length === 0){
				      chkbox_select_all.checked = false;
				      if('indeterminate' in chkbox_select_all){
				         chkbox_select_all.indeterminate = false;
				      }

				   // If all of the checkboxes are checked
				   } else if ($chkbox_checked.length === $chkbox_all.length){
				      chkbox_select_all.checked = true;
				      if('indeterminate' in chkbox_select_all){
				         chkbox_select_all.indeterminate = false;
				      }

				   // If some of the checkboxes are checked
				   } else {
				      chkbox_select_all.checked = true;
				      if('indeterminate' in chkbox_select_all){
				         chkbox_select_all.indeterminate = true;
				      }
				   }
				}
		}
		return {
				//main function to initiate the module
				init: function () {
					if (!$().dataTable) {
							return;
					}
					initTableCheckbox();

				}
		};
}();


var tableWithCheckboxAjax = function () {
		//var arrayForRows = [];
		var initTableCheckboxAjax = function (tableClass, columns, order, extraParams, arrayForRows) {
				var table = $(tableClass);

				/* 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({
					    "processing": true,
					    "serverSide": true,
						"ajax": {
						    "url": $(tableClass).data('source'),
						    "data": function ( d ) {
						    	d.busqueda = $(tableClass).closest('.dataTables_wrapper').find('input[type="search"]').val();
						        // son los parametros custom de cada tabla, se envia el obj.
								for(var param in extraParams){
							 		d[param] = extraParams[param];
								}
					    	}
					    },
					    "drawCallback": function( settings ) {
					        arrayForRows.length = 0;
					    },
					    'columns': columns,
			          	'columnDefs': [{
				            'targets': 0,
				            'searchable':false,
				            'orderable':false,
				            'className': 'dt-body-center',
			             	'render': function (data, type, full, meta) {
			                 	return '<input type="checkbox" name="id[]">';
			             	}
			          	}],
						"language": {
								"aria": {
										"sortAscending": ": activate to sort column ascending",
										"sortDescending": ": activate to sort column descending"
								},
								"sProcessing": "Cargando...",
								"emptyTable": "No hay informacion en la tabla",
								"info": "Mostrando del _START_ al _END_ de _TOTAL_ registros",
								"infoEmpty": "No se encontraron coincidencias",
								"infoFiltered": "(filtrado un total de _MAX_ registros)",
								"lengthMenu": "Mostrar _MENU_ registros",
								"search": "Buscar:",
								"zeroRecords": "No se encontraron coincidencias",
								"paginate": {
		                            "sPrevious": "Ant",
		                            "sNext": "Sig"
		                        }
						},
						'order': [order, 'asc'],
					      "rowCallback": function(row, data, dataIndex){
					         // Get row ID
					         var rowId = data[0];

					         // If row ID is in the list of selected row IDs
					         if($.inArray(rowId, arrayForRows) !== -1){
					            $(row).find('input[type="checkbox"]').prop('checked', true);
					            $(row).addClass('selected');
					         }
					      },
						"lengthMenu": [
								[20, 50, 75, 100,	-1],
								[20, 50, 75, 100,	"Todos"] // change per page values here
						],
						// set the initial value
						"pageLength": 20,
						"dom": "<'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


				var table = $(tableClass).DataTable();
					// Handle click on checkbox
				   $(tableClass + ' tbody').on('click', 'input[type="checkbox"]', function(e){
				      var $row = $(this).closest('tr');

				      // Get row data
				      var data = table.row($row).data();

				      // Get row ID
				      // var rowId = data[0];
				      var rowId = $row.attr('id').substring($row.attr('id').indexOf('_') + 1, $row.attr('id').length);
				      // Determine whether row ID is in the list of selected row IDs
				      var index = $.inArray(rowId, arrayForRows);

				      // If checkbox is checked and row ID is not in list of selected row IDs
				      if(this.checked && index === -1){
				         arrayForRows.push(rowId);

				      // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
				      } else if (!this.checked && index !== -1){
				         arrayForRows.splice(index, 1);
				      }

				      if(this.checked){
				         $row.addClass('selected');
				        //$row.css('background-color', '#34495E');
				      } else {
				        //$row.css('background-color', '#F9F9F9');
				        $row.removeClass('selected');
				      }

				      // Update state of "Select all" control
				      updateDataTableSelectAllCtrl(table);

				      // Prevent click event from propagating to parent
				      e.stopPropagation();
				   });

				   // Handle click on table cells with checkboxes
				   $(tableClass).on('click', 'tbody td, thead th:first-child', function(e){
				      $(this).parent().find('input[type="checkbox"]').trigger('click');
				   });

				   // Handle click on "Select all" control
				   $('thead input[name="select_all"]', table.table().container()).on('click', function(e){
				      if(this.checked){
				         $(tableClass + ' tbody input[type="checkbox"]:not(:checked)').trigger('click');
				      } else {
				         $(tableClass + ' tbody input[type="checkbox"]:checked').trigger('click');
				      }

				      // Prevent click event from propagating to parent
				      e.stopPropagation();
				   });

				   // Handle table draw event
				   table.on('draw', function(){
				      // Update state of "Select all" control
				      updateDataTableSelectAllCtrl(table);
				   });

				   function updateDataTableSelectAllCtrl(table){
					   var $table             = table.table().node();
					   var $chkbox_all        = $('tbody input[type="checkbox"]', $table);
					   var $chkbox_checked    = $('tbody input[type="checkbox"]:checked', $table);
					   var chkbox_select_all  = $('thead input[name="select_all"]', $table).get(0);

					   // If none of the checkboxes are checked
					   if($chkbox_checked.length === 0){
					      chkbox_select_all.checked = false;
					      if('indeterminate' in chkbox_select_all){
					         chkbox_select_all.indeterminate = false;
					      }

					   // If all of the checkboxes are checked
					   } else if ($chkbox_checked.length === $chkbox_all.length){
					      chkbox_select_all.checked = true;
					      if('indeterminate' in chkbox_select_all){
					         chkbox_select_all.indeterminate = false;
					      }

					   // If some of the checkboxes are checked
					   } else {
					      chkbox_select_all.checked = true;
					      if('indeterminate' in chkbox_select_all){
					         chkbox_select_all.indeterminate = true;
					      }
					   }
					}
		}
		return {
				//main function to initiate the module
				init: function (tableClass, columns, order, data, arrayForRows) {
					if (!$().dataTable) {
							return;
					}
					initTableCheckboxAjax(tableClass, columns, order, data, arrayForRows);

				}
		};
}();



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": "(filtrado un total 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": 20,
            // 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 = $('.tablePag_wrapper');

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

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

    return {

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

            initTable3();
        }

    };

}();

var TableChecks = function () {
	var initTable1 = function () {

        var table = $('.tablechecks');

        // begin first 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": "(filtrado un total de _MAX_ registros)",
					"lengthMenu": "Mostrar _MENU_ registros",
					"search": "Buscar:",
					"zeroRecords": "No se encontraron coincidencias",
					"paginate": {
                        "sPrevious": "Ant",
                        "sNext": "Sig"
                    }
			},

            // Or you can use remote translation file
            //"language": {
            //   url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json'
            //},

            // 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'f>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.

            "columnDefs": [ {
                "targets": 0,
                "orderable": false,
                "searchable": false
            }],

            "lengthMenu": [
                [20, 50, 75, 100,	-1],
				[20, 50, 75, 100,	"Todos"] // change per page values here
            ],
            // set the initial value
            "pageLength": 20,
            "columnDefs": [{  // set default column settings
                'orderable': false,
                'targets': [0]
            }, {
                "searchable": false,
                "targets": [0]
            }],
            "order": [
                [1, "asc"]
            ] // set first column as a default sort by asc
        });

        var tableWrapper = $('.tablechecks_wrapper');

        table.find('.group-checkable').on('change', function () {
            var set = $(this).attr("data-set");
            var checked = $(this).is(":checked");
            $(set).each(function () {
                if (checked) {
                    $(this).prop("checked", true);

                } else {
                    $(this).prop("checked", false);

                }
            });
            $.uniform.update(set);
        });

        table.on('change', 'tbody tr .checkboxes', function () {
            $(this).parents('tr').toggleClass("active");
        });
    }
    return {

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

            initTable1();
        }

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

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

var handleDatePickers = function () {

	if ($().datepicker) {
		$('.date-picker').datepicker({
			rtl: App.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 () {

		$('.searchable').multiSelect({
		  selectableHeader: "<input type='text' class='search-input form-control' autocomplete='off' placeholder='Buscar productos disponibles'>",
		  selectionHeader: "<input type='text' class='search-input form-control' autocomplete='off' placeholder='Buscar productos seleccionados'>",
		  afterInit: function(ms) {
		    var that = this,
		        $selectableSearch = that.$selectableUl.prev(),
		        $selectionSearch = that.$selectionUl.prev(),
		        selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',
		        selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected';

		    that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
		    .on('keydown', function(e){
		      if (e.which === 40){
		        that.$selectableUl.focus();
		        return false;
		      }
		    });

		    that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
		    .on('keydown', function(e){
		      if (e.which == 40){
		        that.$selectionUl.focus();
		        return false;
		      }
		    });
		  },
		  afterSelect: function(){
		    this.qs1.cache();
		    this.qs2.cache();
		  },
		  afterDeselect: function(){
		    this.qs1.cache();
		    this.qs2.cache();
		  }
		});
		$('.multi-select').multiSelect({
				keepOrder: true,
			    selectableOptgroup: true
		});
		$('#select-all').click(function(){
		  $('.multi-select').multiSelect('select_all');
		  return false;
		});
		$('#deselect-all').click(function(){
		  $('.multi-select').multiSelect('deselect_all');
		  return false;
		});

}

var handleNestedSelects = function (){
	$('select[data-option-dependent=true]').each(function (i) {
		var observer_dom_id = $(this).data('opt-id');
		var observed_dom_id = $(this).data('option-observed');
		var url_mask = $(this).data('option-url');
		var key_method = $(this).data('option-key-method');
		var value_method = $(this).data('option-value-method');

		var prompt = $('<option value=\"\">').text('Seleccione');
		if($(this).data('option-prompt') != undefined ){
			prompt = $('<option value=\"\">').text( $(this).data('option-prompt') );
		}
		// var prompt = $(this).has('option[value=]').size() ? $(this).find('option[value=]') : $('<option value=\"\">').text('Select a specialization');
		var regexp = /:[0-9a-zA-Z_]+:/g;
		var observer = $('select.' + observer_dom_id);
		var observed = $('.' + observed_dom_id);

		if (!observer.val() && observed.size() > 1) {
			observer.attr('disabled', true);
		}
		observed.on('change', function () {
			observer.empty().append(prompt);
			if (observed.val()) {
				url = url_mask.replace(regexp, observed.val());
				$.getJSON(url, function (data) {
					$.each(data, function (i, object) {
						observer.append($('<option>').attr('value', object[key_method]).text(object[value_method]));
						observer.attr('disabled', 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}" });
}

var TableAdvancedPrintable = function () {

	var initTablePrintable = function () {
	 	var filter = $('#filter').val();
    var buscar_ = { };
    var page_ = 0;

	 	$.fn.dataTableExt.oStdClasses.sFilterInput = "form-control input-medium input-inline";

	 	if(filter != ""){ buscar_ = { search: filter }; }
		if( $('#current_page').length > 0 ){	page_ = ($('#current_page').val() - 1) * 20;}

		$.extend(true, $.fn.DataTable.TableTools.classes, {
	  		"container": " pull-right margin-bottom-10",
	      	"buttons": {
	     	 	"normal": "btn btn-primary margin-right-10",
	          	"disabled": "disabled"
	      	},
	      	"collection": {
	          	"container": "DTTT_dropdown dropdown-menu tabletools-dropdown-menu "
	      	}
	  	});


		var table = $('.tableadvancedprintable');
  	var oTable = table.dataTable({
	    	"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
		    "tableTools": {
		        "sSwfPath": "/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
		        "aButtons": [
		          {
		            "sExtends":    "collection",
		            "sButtonText": "Acciones <i class='fa fa-angle-down'></i>",
		            "aButtons": [{
		              	"sExtends": "print",
		              	"footer": false,
										"exportOptions": {
		                    "columns":  ':not(:last-child)',
		               	},
		              	"sButtonText": "Imprimir",
		              	"sInfo": 'Presiona "CTR+P" para imprmir o "ESC" para salir',
		              	"sMessage": function() {
		                	return "<h2>" + $('#title_for_print').val() + "</h2>";
		              	},
		              	"fnClick": function( nButton, oConfig ) {
	                  		$(window).keyup(closePrintView);
	                  		this.fnPrint( true, oConfig );
	              		}
		            }]
	          	}]
		    },
		    "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": "(filtrado un total de _MAX_ registros)",
		        "lengthMenu": "Mostrar _MENU_ registros",
		        "search": "Buscar:",
		        "zeroRecords": "No se encontraron coincidencias",
		        "paginate": {
		          "sPrevious": "Ant",
		          "sNext": "Sig"
		        }
		    },
				"order": [
						// [0, 'asc']
				],
		    "lengthMenu": [
		        [20, 50, 75, 100, -1],
		        [20, 50, 75, 100, "Todos"] // change per page values here
		    ],
		    "search": buscar_,
				// set the initial value
				"pageLength": 20,
				"iDisplayStart": page_,
		    "bServerSide": false,
		    "fnDrawCallback": function( oSettings ) {
					$('a.filtros').on( 'click', function (e) {
						e.preventDefault();
						var url_ = $(this).attr('href');
						url_ += '?filter=' + $('#filter').val();
						url_ += '&current_page=' + $('#current_page').val();
						console.log(url_);
						window.location.href = url_;

			    });
			    $('a.filtros2').on( 'click', function (e) {
						e.preventDefault();
						var url_ = $(this).attr('href');
						url_ += '&filter=' + $('#filter').val();
						url_ += '&current_page=' + $('#current_page').val();
						console.log(url_);
						window.location.href = url_;

			    });
				}
	  	});

	  	var closePrintView = function(e) {
	      	if(e.which == 27) {
	          	printViewClosed();
	      	}
	  	};

	  	function printViewClosed() {
	  		$(window).unbind('keyup', closePrintView);
	  	}

	  	if( $('#current_page').length > 0 ){
				$('.tableadvancedprintable').on( 'page.dt', function () {
            var oSettings = oTable.fnSettings();
            var page = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
            $('#current_page').val(page);
        });
			}
	}

	return {
		init: function () {
			if (!$().dataTable) {
					return;
			}
			initTablePrintable();
		}
	};
}();

var TableAdvancedPrintableAjax = function () {

	var initTablePrintableAjax = function () {
	 	$.fn.dataTableExt.oStdClasses.sFilterInput = "form-control input-medium input-inline";

	  	var table = $('.tableadvancedprintableAjax').DataTable({
		    "processing": true,
		    "serverSide": true,
			"ajax": {
			    "url": $('.tableadvancedprintableAjax').data('source'),
			    "data": function ( d ) {
			        d.busqueda = $('input[type="search"]').val();
			        d.location = $('#pointsale').val();
			        d.category = $('#category').val();
			        d.sub_category = $('#sub_category').val();
		    	}
		    },
			"dom": "<'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>>",
		    "language": {
		        "aria": {
		            "sortAscending": ": activate to sort column ascending",
		            "sortDescending": ": activate to sort column descending"
		        },
		        "emptyTable": "No hay informacion en la tabla",
		        "sProcessing": "Cargando...",
		        "info": "Mostrando del _START_ al _END_ de _TOTAL_ registros",
		        "infoEmpty": "No se encontraron coincidencias",
		        "infoFiltered": "(filtrado un total de _MAX_ registros)",
		        "lengthMenu": "Mostrar _MENU_ registros",
		        "search": "Buscar:",
		        "zeroRecords": "No se encontraron coincidencias",
		        "paginate": {
		          "sPrevious": "Ant",
		          "sNext": "Sig"
		        }
		    },
			"order": [
					// [0, 'asc']
			],
		    "lengthMenu": [
		        [20, 50, 75, 100, -1],
		        [20, 50, 75, 100, "Todos"] // change per page values here
		    ],
		    "pageLength": 20
		});

	  	var closePrintView = function(e) {
	      	if(e.which == 27) {
	          	printViewClosed();
	      	}
	  	};

	  	function printViewClosed() {
	  		$(window).unbind('keyup', closePrintView);
	  	}
	}

	return {
		init: function () {
			if (!$().dataTable) {
					return;
			}
			initTablePrintableAjax();
		}
	};
}();

var TableAdvancedAjax = function () {
	//create JSON array for aoColumnDefs
		var initTableAjax = function () {
				var table = $('.tableadvancedAjax');
				var filter = $('#filter').val();
		    var buscar_ = { };
		    var page_ = 0;

			 	$.fn.dataTableExt.oStdClasses.sFilterInput = "form-control input-medium input-inline";
			 	if(filter != ""){ buscar_ = { search: filter }; }
				if( $('#current_page').length > 0 ){	page_ = ($('#current_page').val() - 1) * 20;}

				var oTable = table.dataTable({
			    "processing": true,
			    "serverSide": true,
					"ajax": {
					    "url": $('.tableadvancedAjax').data('source'),
					    "data": function ( d ) {
					        d.busqueda = $('input[type="search"]').val();
					        $('#filter').val(d.busqueda);
				    	}
				    },
					"language": {
							"aria": {
									"sortAscending": ": activate to sort column ascending",
									"sortDescending": ": activate to sort column descending"
							},
							"emptyTable": "No hay informacion en la tabla",
							"sProcessing": "Cargando...",
							"info": "Mostrando del _START_ al _END_ de _TOTAL_ registros",
							"infoEmpty": "No se encontraron coincidencias",
							"infoFiltered": "(filtrado un total de _MAX_ registros)",
							"lengthMenu": "Mostrar _MENU_ registros",
							"search": "Buscar:",
							"zeroRecords": "No se encontraron coincidencias",
							"paginate": {
	                            "sPrevious": "Ant",
	                            "sNext": "Sig"
	                        }
					},
					"order": [
							// [0, 'asc']
					],
					"lengthMenu": [
							[20, 50, 75, 100,	-1],
							[20, 50, 75, 100,	"Todos"] // change per page values here
					],
					"dom": "<'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
					"search": buscar_,
					// set the initial value
					"pageLength": 20,
					"iDisplayStart": page_,
			    "fnDrawCallback": function( oSettings ) {
						$('a.filtros').on( 'click', function (e) {
							e.preventDefault();
							var url_ = $(this).attr('href');
							url_ += '?filter=' + $('#filter').val();
							url_ += '&current_page=' + $('#current_page').val();
							console.log(url_);
							window.location.href = url_;

				    });
				    $('a.filtros2').on( 'click', function (e) {
							e.preventDefault();
							var url_ = $(this).attr('href');
							url_ += '&filter=' + $('#filter').val();
							url_ += '&current_page=' + $('#current_page').val();
							console.log(url_);
							window.location.href = url_;

				    });
					}
				});

				var tableWrapper = $('.tableadvancedAjax_wrapper');

				tableWrapper.find('.dataTables_length select').select2();

				if( $('#current_page').length > 0 ){
					$('.tableadvancedAjax').on( 'page.dt', function () {
	            var oSettings = oTable.fnSettings();
	            var page = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
	            $('#current_page').val(page);
	        });
				}
		}

		return {
				init: function () {
						if (!$().dataTable) {
								return;
						}
						initTableAjax();
				}

		};

}();

var FormWizard = function () {
  return {
    //main function to initiate the module
    init: function () {
      if (!jQuery().bootstrapWizard) {
        return;
      }

        var form = $('#submit_form');
        var error = $('.alert-danger', form);
        var success = $('.alert-success', form);

        // jQuery.validator.setDefaults({
        //   doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
        //   errorElement: 'span', //default input error message container
        //   errorClass: 'help-block help-block-error', // default input error message class
        //   focusInvalid: false, // do not focus the last invalid input



        //   errorPlacement: function (error, element) { // render error placement for each input type
        //     if (element.attr("name") == "gender") { // for uniform radio buttons, insert the after the given container
        //       error.insertAfter("#form_gender_error");
        //     } else if (element.attr("name") == "modulos[]") { // for uniform checkboxes, insert the after the given container
        //       error.insertAfter("#form_payment_error");
        //     } else {
        //       error.insertAfter(element); // for other inputs, just perform default behavior
        //     }
        //   },

        //   invalidHandler: function (event, validator) { //display error alert on form submit
        //     success.hide();
        //     error.show();
        //     App.scrollTo(error, -200);
        //   },

        //   highlight: function (element) { // hightlight error inputs
        //     $(element)
        //     .closest('.form-group').removeClass('has-success').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) {
        //     if (label.attr("for") == "gender" || label.attr("for") == "modulos[]") { // for checkboxes and radio buttons, no need to show OK icon
        //       label
        //       .closest('.form-group').removeClass('has-error').addClass('has-success');
        //       label.remove(); // remove error label here
        //     } else { // display success icon for other inputs
        //       label
        //       .addClass('valid') // mark the current input as valid and display OK icon
        //       .closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
        //     }
        //   },

        //   submitHandler: function (form) {
        //     success.show();
        //     error.hide();
        //     form.submit();
        //     //add here some ajax code to submit your form or just call form.submit() if you want to submit the form without ajax
        //   }

        // });

        var displayConfirm = function() {
          $('#tab4 .form-control-static', form).each(function(){
            var input = $('[name="'+$(this).attr("data-display")+'"]', form);
            if (input.is(":radio")) {
              input = $('[name="'+$(this).attr("data-display")+'"]:checked', form);
            }
            if (input.is(":text") || input.is("textarea")) {
              $(this).html(input.val());
            } else if (input.is("select")) {
              $(this).html(input.find('option:selected').text());
            } else if (input.is(":radio") && input.is(":checked")) {
              $(this).html(input.attr("data-title"));
            } else if ($(this).attr("data-display") == 'modulos[]') {
              var modulos = [];
              $('[name="modulos[]"]:checked', form).each(function(){
                modulos.push($(this).attr('data-title'));
              });
              $(this).html(modulos.join(" <br>"));
            }
          });
        }
        var displayConfirm = function() {
          $('.form-control-static', form).each(function(){
            var input = $('[name="'+$(this).attr("data-display")+'"]', form);
            if (input.is(":radio")) {
              input = $('[name="'+$(this).attr("data-display")+'"]:checked', form);
            }
            if (input.is(":text") || input.is("textarea")) {
              $(this).html(input.val());
            } else if (input.is("select") && !(input.attr("multiple")) ) {
              $(this).html(input.find('option:selected').text());
            } else if (input.is(":radio") && input.is(":checked")) {
              $(this).html(input.attr("data-title"));
            } else if ($(this).attr("data-display") == 'modulos[]') {
              var modulos = [];
              $('#modulos :selected', form).each(function(){
                modulos.push($(this).html());
              });
              $(this).html(modulos.join(" <br>"));
            }
          });
        }

        var handleTitle = function(tab, navigation, index) {
          var total = navigation.find('li').length;
          var current = index + 1;
          // set wizard title
          $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
          // set done steps
          jQuery('li', $('#form_wizard_1')).removeClass("done");
          var li_list = navigation.find('li');
          for (var i = 0; i < index; i++) {
            jQuery(li_list[i]).addClass("done");
          }

          if (current == 1) {
            $('#form_wizard_1').find('.button-previous').hide();
          } else {
            $('#form_wizard_1').find('.button-previous').show();
          }

          if (current >= total) {
            $('#form_wizard_1').find('.button-next').hide();
            $('#form_wizard_1').find('.button-submit').show();
            displayConfirm();
          } else {
            $('#form_wizard_1').find('.button-next').show();
            $('#form_wizard_1').find('.button-submit').hide();
          }
          App.scrollTo($('.page-title'));
        }

        // default form wizard
        $('#form_wizard_1').bootstrapWizard({
          'nextSelector': '.button-next',
          'previousSelector': '.button-previous',
          onTabClick: function (tab, navigation, index, clickedIndex) {
            return false;
            /*
            success.hide();
            error.hide();
            if (form.valid() == false) {
            return false;
          }
          handleTitle(tab, navigation, clickedIndex);
          */
        },
        onNext: function (tab, navigation, index) {
          // success.hide();
          // error.hide();

          // if (form.valid() == false) {
          //   return false;
          // }

          handleTitle(tab, navigation, index);
        },
        onPrevious: function (tab, navigation, index) {
          // success.hide();
          // error.hide();

          handleTitle(tab, navigation, index);
        },
        onTabShow: function (tab, navigation, index) {
          var total = navigation.find('li').length;
          var current = index + 1;
          var $percent = (current / total) * 100;
          $('#form_wizard_1').find('.progress-bar').css({
            width: $percent + '%'
          });
        }
      });

      $('#form_wizard_1').find('.button-previous').hide();
      $('#form_wizard_1 .button-submit').click(function () {
        // alert('Finished! Hope you like it :)');
        if(window.location.pathname.includes('users')) {
        	$('#submit_form').submit();
        } else {
        	submitForm();
        }
      }).hide();
    }

  };

}();


var FormWizard_sale_return = function () {
  	return {
	    init: function () {
	      	if (!jQuery().bootstrapWizard) {
	        	return;
	      	}

	        var form = $('#submit_form');
	        var error = $('.alert-danger', form);
	        var success = $('.alert-success', form);

	        var handleTitle = function(tab, navigation, index) {
	          var total = navigation.find('li').length;
	          var current = index + 1;
	          jQuery('li', $('#form_wizard_product_return')).removeClass("done");
	          var li_list = navigation.find('li');
	          for (var i = 0; i < index; i++) {
	            jQuery(li_list[i]).addClass("done");
	          }

	          if (current == 1) {
	            $('#form_wizard_product_return').find('.button-previous').hide();
	          } else {
	            $('#form_wizard_product_return').find('.button-previous').show();
	          }

	          if (current >= total) {
	            $('#form_wizard_product_return').find('.button-next').hide();
	            $('#form_wizard_product_return').find('.button-submit').show();
	          } else {
	            $('#form_wizard_product_return').find('.button-next').show();
	            $('#form_wizard_product_return').find('.button-submit').hide();
	          }
	          // App.scrollTo($('.page-title'));
	        }

	        $('#form_wizard_product_return').bootstrapWizard({
	          'nextSelector': '.button-next',
	          'previousSelector': '.button-previous',
	          onTabClick: function (tab, navigation, index, clickedIndex) {
	            return false;
	        },
	        onNext: function (tab, navigation, index) {
	          shouldStep = nextStep(index);
	          if (index != 0) {
	          	$('#form_wizard_product_return').find('.button-previous').show();
	          } else {
	          	$('#form_wizard_product_return').find('.button-previous').hide();
	          }

	          if(shouldStep) {
	          	handleTitle(tab, navigation, index);
	          }
	          return shouldStep;
	        },
	        onPrevious: function (tab, navigation, index) {
	          handleTitle(tab, navigation, index);
	        },
	        onTabShow: function (tab, navigation, index) {
	          var total = navigation.find('li').length;
	          var current = index + 1;
	          var $percent = (current / total) * 100;
	          $('#form_wizard_product_return').find('.progress-bar').css({
	            width: $percent + '%'
	          });
	        }
	      });

	      $('#form_wizard_product_return').find('.button-previous').hide();
	      $('#form_wizard_product_return .button-submit').click(function () {
	      	$(this).hide();
	        submitForm();
	      }).hide();
	    }
	};
}();


var MakeChart = function(type, data, container, categoryField, valueField) {

	if(type == 'serial') {
		var chart = AmCharts.makeChart(container, {
		  "type": 'serial',
		  "theme": "light",
		  "dataProvider": data,
		  "gridAboveGraphs": true,
		  "startDuration": 1,
		  "graphs": [ {
		    "balloonText": "[[category]]: <b>[[value]]</b>",
		    "fillAlphas": 0.8,
		    "lineAlpha": 0.2,
		    "type": "column",
		    "valueField": valueField
		  } ],
		  "chartCursor": {
		    "categoryBalloonEnabled": false,
		    "cursorAlpha": 0,
		    "zoomable": false
		  },
		  "categoryField": categoryField,
		  "categoryAxis": {
		    "gridPosition": "start",
		    "gridAlpha": 0,
		    "tickPosition": "start",
		    "tickLength": 20
		  }
		});
	} else if(type == 'pie') {
		// pie chart
		var chart = AmCharts.makeChart( container, {
		  "type": "pie",
		  "theme": "light",
		  "dataProvider": data,
		  "titleField": categoryField,
		  "valueField": valueField,
		  "labelRadius": 5,
		  "radius": "42%",
		  "innerRadius": "60%",
		  "labelText": "[[title]]",
		});
	}
}

$(document).on("page:change", function() {
	 Layout.init();
	$(document).ajaxError(function(event,xhr,options,exc) {
		var errors = JSON.parse(xhr.responseText);
	    var er ="<ul>";
	    for(var i = 0; i < errors.length; i++){
	        var list = errors[i];
	        er += "<li>"+list+"</li>"
	    }
	    er+="</ul>"
		var kk = " <div class='alert alert-danger'><strong>Tiene un error no se puede guardar</strong><br>"+er+"</div> "
	    $("#error_explanation").html(kk);

	});

		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($('.nestedselect').get(0) ){
			handleNestedSelects();
		}

		if($('.make-switch').get(0)){
			$(":checkbox").bootstrapSwitch();
		}

		if($('.select2').get(0)){
			$('select.select2').select2({
				placeholder: "Seleccione",
			   	"language": {
			       "noResults": function(){
			           return "No se encontraron coincidencias";
			       }
			   	},
			    escapeMarkup: function (markup) {
			        return markup;
			    }
			});
		}

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

		if($('.tableadvanced').get(0) ){

				TableAdvanced.init();
				$('.dataTables_filter input[type=search]').on( 'keyup', function () {
				    $('#filter').val( this.value );
				} );


		}
		if($('.tableadvancedSingleSelection').get(0) ){
				TableAdvancedSingleSelection.init();
		}
		if($('.tableadvancedprintable').get(0) ){

				TableAdvancedPrintable.init();

				$('.dataTables_filter input[type=search]').on( 'keyup', function () {
				    $('#filter').val( this.value );
				} );
		}
		if($('.tableadvancedprintableAjax').get(0) ){

				TableAdvancedPrintableAjax.init();
		}
		if($('.tableadvancedAjax').get(0) ){

				TableAdvancedAjax.init();
		}
		if($('.tablechecks').get(0) ){

				TableChecks.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();
		}
		if($('.tableWithCheckbox').get(0) ){
			TableWithCheckbox.init();
		}
		// if($('.tableWithCheckboxAjax').get(0) ){
		// 	tableWithCheckboxAjax.init();
		// }
		if($('.tableCheckBoxNoSearch').get(0) ){
			tableCheckBoxNoSearch.init();
		}

	    if($('#form_wizard_1').get(0) ){
	        FormWizard.init();
	    }
	    if($('#form_wizard_product_return').get(0) ){
	        FormWizard_sale_return.init();
	    }


		// $('.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);
					}
				}
	       	}
    	});
	}


});


