/* Error de minimización. Devolviendo el contenido no minimizado.
(1,1): run-time error CSS1019: Unexpected token, found '!'
(1,2): run-time error CSS1019: Unexpected token, found 'function('
(1,12): run-time error CSS1031: Expected selector, found ')'
(1,12): run-time error CSS1025: Expected comma or open brace, found ')'
(1,4089): run-time error CSS1019: Unexpected token, found '('
(1,4090): run-time error CSS1019: Unexpected token, found '"function"'
(1,4100): run-time error CSS1019: Unexpected token, found '='
(1,4101): run-time error CSS1019: Unexpected token, found '='
(1,4115): run-time error CSS1031: Expected selector, found '&'
(1,4115): run-time error CSS1025: Expected comma or open brace, found '&'
(1,4259): run-time error CSS1019: Unexpected token, found ')'
(3,5): run-time error CSS1031: Expected selector, found '$'
(3,5): run-time error CSS1025: Expected comma or open brace, found '$'
(10,1): run-time error CSS1019: Unexpected token, found '$'
(10,2): run-time error CSS1019: Unexpected token, found '('
(10,3): run-time error CSS1019: Unexpected token, found 'function('
(10,12): run-time error CSS1019: Unexpected token, found ')'
(10,14): run-time error CSS1019: Unexpected token, found '{'
(12,2): run-time error CSS1019: Unexpected token, found '$'
(12,11): run-time error CSS1031: Expected selector, found '='
(12,11): run-time error CSS1025: Expected comma or open brace, found '='
(18,1): run-time error CSS1019: Unexpected token, found '}'
(18,2): run-time error CSS1019: Unexpected token, found ')'
(20,10): run-time error CSS1031: Expected selector, found 'Apprise('
(20,10): run-time error CSS1025: Expected comma or open brace, found 'Apprise('
(192,15): run-time error CSS1031: Expected selector, found '='
(192,15): run-time error CSS1025: Expected comma or open brace, found '='
(194,1): run-time error CSS1019: Unexpected token, found '$'
(194,2): run-time error CSS1019: Unexpected token, found '('
(194,12): run-time error CSS1031: Expected selector, found '('
(194,12): run-time error CSS1025: Expected comma or open brace, found '('
(196,2): run-time error CSS1019: Unexpected token, found ')'
(198,10): run-time error CSS1031: Expected selector, found 'init('
(198,10): run-time error CSS1025: Expected comma or open brace, found 'init('
(204,1): run-time error CSS1019: Unexpected token, found '$'
(204,3): run-time error CSS1030: Expected identifier, found 'ajaxSetup('
(204,3): run-time error CSS1019: Unexpected token, found 'ajaxSetup('
(204,13): run-time error CSS1019: Unexpected token, found '{'
(205,11): run-time error CSS1030: Expected identifier, found ' '
(206,1): run-time error CSS1031: Expected selector, found '}'
(206,1): run-time error CSS1025: Expected comma or open brace, found '}'
(208,1): run-time error CSS1019: Unexpected token, found '$'
(208,2): run-time error CSS1019: Unexpected token, found '('
(208,11): run-time error CSS1031: Expected selector, found ')'
(208,11): run-time error CSS1025: Expected comma or open brace, found ')'
(210,2): run-time error CSS1019: Unexpected token, found ')'
(212,1): run-time error CSS1019: Unexpected token, found '$'
(212,2): run-time error CSS1019: Unexpected token, found '('
(212,11): run-time error CSS1031: Expected selector, found ')'
(212,11): run-time error CSS1025: Expected comma or open brace, found ')'
(214,2): run-time error CSS1019: Unexpected token, found ')'
(219,1): run-time error CSS1019: Unexpected token, found '$'
(219,2): run-time error CSS1019: Unexpected token, found '('
(219,11): run-time error CSS1031: Expected selector, found ')'
(219,11): run-time error CSS1025: Expected comma or open brace, found ')'
(232,2): run-time error CSS1019: Unexpected token, found ')'
(234,1): run-time error CSS1019: Unexpected token, found '$'
(234,2): run-time error CSS1019: Unexpected token, found '('
(234,11): run-time error CSS1031: Expected selector, found ')'
(234,11): run-time error CSS1025: Expected comma or open brace, found ')'
(248,2): run-time error CSS1019: Unexpected token, found ')'
(250,10): run-time error CSS1031: Expected selector, found 'addFilter('
(250,10): run-time error CSS1025: Expected comma or open brace, found 'addFilter('
(261,10): run-time error CSS1031: Expected selector, found 'createFilter('
(261,10): run-time error CSS1025: Expected comma or open brace, found 'createFilter('
(306,1): run-time error CSS1019: Unexpected token, found '$'
(306,2): run-time error CSS1019: Unexpected token, found '('
(306,11): run-time error CSS1031: Expected selector, found ')'
(306,11): run-time error CSS1025: Expected comma or open brace, found ')'
(312,2): run-time error CSS1019: Unexpected token, found ')'
(314,1): run-time error CSS1019: Unexpected token, found '$'
(314,2): run-time error CSS1019: Unexpected token, found '('
(314,11): run-time error CSS1031: Expected selector, found ')'
(314,11): run-time error CSS1025: Expected comma or open brace, found ')'
(357,2): run-time error CSS1019: Unexpected token, found ')'
(359,1): run-time error CSS1019: Unexpected token, found '$'
(359,2): run-time error CSS1019: Unexpected token, found '('
(359,11): run-time error CSS1031: Expected selector, found ')'
(359,11): run-time error CSS1025: Expected comma or open brace, found ')'
(410,2): run-time error CSS1019: Unexpected token, found ')'
(412,1): run-time error CSS1019: Unexpected token, found '$'
(412,2): run-time error CSS1019: Unexpected token, found '('
(412,11): run-time error CSS1031: Expected selector, found ')'
(412,11): run-time error CSS1025: Expected comma or open brace, found ')'
(459,2): run-time error CSS1019: Unexpected token, found ')'
(461,1): run-time error CSS1019: Unexpected token, found '$'
(461,2): run-time error CSS1019: Unexpected token, found '('
(461,11): run-time error CSS1031: Expected selector, found ')'
(461,11): run-time error CSS1025: Expected comma or open brace, found ')'
(518,2): run-time error CSS1019: Unexpected token, found ')'
(520,1): run-time error CSS1019: Unexpected token, found '$'
(520,2): run-time error CSS1019: Unexpected token, found '('
(520,11): run-time error CSS1031: Expected selector, found ')'
(520,11): run-time error CSS1025: Expected comma or open brace, found ')'
(538,2): run-time error CSS1019: Unexpected token, found ')'
(540,1): run-time error CSS1019: Unexpected token, found '$'
(540,2): run-time error CSS1019: Unexpected token, found '('
(540,11): run-time error CSS1031: Expected selector, found ')'
(540,11): run-time error CSS1025: Expected comma or open brace, found ')'
(548,2): run-time error CSS1019: Unexpected token, found ')'
(550,1): run-time error CSS1019: Unexpected token, found '$'
(550,2): run-time error CSS1019: Unexpected token, found '('
(550,11): run-time error CSS1031: Expected selector, found ')'
(550,11): run-time error CSS1025: Expected comma or open brace, found ')'
(556,2): run-time error CSS1019: Unexpected token, found ')'
(558,10): run-time error CSS1031: Expected selector, found 'clearForm('
(558,10): run-time error CSS1025: Expected comma or open brace, found 'clearForm('
(562,10): run-time error CSS1031: Expected selector, found 'clearFormElem('
(562,10): run-time error CSS1025: Expected comma or open brace, found 'clearFormElem('
(566,10): run-time error CSS1031: Expected selector, found 'validateNumber('
(566,10): run-time error CSS1025: Expected comma or open brace, found 'validateNumber('
(581,10): run-time error CSS1031: Expected selector, found 'preparedDate('
(581,10): run-time error CSS1025: Expected comma or open brace, found 'preparedDate('
(594,10): run-time error CSS1031: Expected selector, found 'datePickers('
(594,10): run-time error CSS1025: Expected comma or open brace, found 'datePickers('
(602,10): run-time error CSS1031: Expected selector, found 'callFn('
(602,10): run-time error CSS1025: Expected comma or open brace, found 'callFn('
(611,10): run-time error CSS1031: Expected selector, found 'getCrudFields('
(611,10): run-time error CSS1025: Expected comma or open brace, found 'getCrudFields('
(621,10): run-time error CSS1031: Expected selector, found 'error('
(621,10): run-time error CSS1025: Expected comma or open brace, found 'error('
(624,10): run-time error CSS1031: Expected selector, found 'warning('
(624,10): run-time error CSS1025: Expected comma or open brace, found 'warning('
(627,10): run-time error CSS1031: Expected selector, found 'info('
(627,10): run-time error CSS1025: Expected comma or open brace, found 'info('
(630,10): run-time error CSS1031: Expected selector, found 'success('
(630,10): run-time error CSS1025: Expected comma or open brace, found 'success('
(634,10): run-time error CSS1031: Expected selector, found 'showNotification('
(634,10): run-time error CSS1025: Expected comma or open brace, found 'showNotification('
(657,10): run-time error CSS1031: Expected selector, found 'confirm('
(657,10): run-time error CSS1025: Expected comma or open brace, found 'confirm('
(689,10): run-time error CSS1031: Expected selector, found 'loadSelect('
(689,10): run-time error CSS1025: Expected comma or open brace, found 'loadSelect('
 */
!function(e){e(["jquery"],function(e){return function(){function t(e,t,n){return f({type:O.error,iconClass:g().iconClasses.error,message:e,optionsOverride:n,title:t})}function n(t,n){return t||(t=g()),v=e("#"+t.containerId),v.length?v:(n&&(v=c(t)),v)}function i(e,t,n){return f({type:O.info,iconClass:g().iconClasses.info,message:e,optionsOverride:n,title:t})}function o(e){w=e}function s(e,t,n){return f({type:O.success,iconClass:g().iconClasses.success,message:e,optionsOverride:n,title:t})}function a(e,t,n){return f({type:O.warning,iconClass:g().iconClasses.warning,message:e,optionsOverride:n,title:t})}function r(e){var t=g();v||n(t),l(e,t)||u(t)}function d(t){var i=g();return v||n(i),t&&0===e(":focus",t).length?void h(t):void(v.children().length&&v.remove())}function u(t){for(var n=v.children(),i=n.length-1;i>=0;i--)l(e(n[i]),t)}function l(t,n){return t&&0===e(":focus",t).length?(t[n.hideMethod]({duration:n.hideDuration,easing:n.hideEasing,complete:function(){h(t)}}),!0):!1}function c(t){return v=e("<div/>").attr("id",t.containerId).addClass(t.positionClass).attr("aria-live","polite").attr("role","alert"),v.appendTo(e(t.target)),v}function p(){return{tapToDismiss:!0,toastClass:"toast",containerId:"toast-container",debug:!1,showMethod:"fadeIn",showDuration:300,showEasing:"swing",onShown:void 0,hideMethod:"fadeOut",hideDuration:1e3,hideEasing:"swing",onHidden:void 0,extendedTimeOut:1e3,iconClasses:{error:"toast-error",info:"toast-info",success:"toast-success",warning:"toast-warning"},iconClass:"toast-info",positionClass:"toast-top-right",timeOut:5e3,titleClass:"toast-title",messageClass:"toast-message",target:"body",closeHtml:"<button>&times;</button>",newestOnTop:!0,preventDuplicates:!1,progressBar:!1}}function m(e){w&&w(e)}function f(t){function i(t){return!e(":focus",l).length||t?(clearTimeout(O.intervalId),l[r.hideMethod]({duration:r.hideDuration,easing:r.hideEasing,complete:function(){h(l),r.onHidden&&"hidden"!==b.state&&r.onHidden(),b.state="hidden",b.endTime=new Date,m(b)}})):void 0}function o(){(r.timeOut>0||r.extendedTimeOut>0)&&(u=setTimeout(i,r.extendedTimeOut),O.maxHideTime=parseFloat(r.extendedTimeOut),O.hideEta=(new Date).getTime()+O.maxHideTime)}function s(){clearTimeout(u),O.hideEta=0,l.stop(!0,!0)[r.showMethod]({duration:r.showDuration,easing:r.showEasing})}function a(){var e=(O.hideEta-(new Date).getTime())/O.maxHideTime*100;f.width(e+"%")}var r=g(),d=t.iconClass||r.iconClass;if(r.preventDuplicates){if(t.message===C)return;C=t.message}"undefined"!=typeof t.optionsOverride&&(r=e.extend(r,t.optionsOverride),d=t.optionsOverride.iconClass||d),T++,v=n(r,!0);var u=null,l=e("<div/>"),c=e("<div/>"),p=e("<div/>"),f=e("<div/>"),w=e(r.closeHtml),O={intervalId:null,hideEta:null,maxHideTime:null},b={toastId:T,state:"visible",startTime:new Date,options:r,map:t};return t.iconClass&&l.addClass(r.toastClass).addClass(d),t.title&&(c.append(t.title).addClass(r.titleClass),l.append(c)),t.message&&(p.append(t.message).addClass(r.messageClass),l.append(p)),r.closeButton&&(w.addClass("toast-close-button").attr("role","button"),l.prepend(w)),r.progressBar&&(f.addClass("toast-progress"),l.prepend(f)),l.hide(),r.newestOnTop?v.prepend(l):v.append(l),l[r.showMethod]({duration:r.showDuration,easing:r.showEasing,complete:r.onShown}),r.timeOut>0&&(u=setTimeout(i,r.timeOut),O.maxHideTime=parseFloat(r.timeOut),O.hideEta=(new Date).getTime()+O.maxHideTime,r.progressBar&&(O.intervalId=setInterval(a,10))),l.hover(s,o),!r.onclick&&r.tapToDismiss&&l.click(i),r.closeButton&&w&&w.click(function(e){e.stopPropagation?e.stopPropagation():void 0!==e.cancelBubble&&e.cancelBubble!==!0&&(e.cancelBubble=!0),i(!0)}),r.onclick&&l.click(function(){r.onclick(),i()}),m(b),r.debug&&console&&console.log(b),l}function g(){return e.extend({},p(),b.options)}function h(e){v||(v=n()),e.is(":visible")||(e.remove(),e=null,0===v.children().length&&v.remove())}var v,w,C,T=0,O={error:"error",info:"info",success:"success",warning:"warning"},b={clear:r,remove:d,error:t,getContainer:n,info:i,options:{},subscribe:o,success:s,version:"2.1.0",warning:a};return b}()})}("function"==typeof define&&define.amd?define:function(e,t){"undefined"!=typeof module&&module.exports?module.exports=t(require("jquery")):window.toastr=t(window.jQuery)});
// Global Apprise variables
var $Apprise = null,
		$overlay = null,
		$body = null,
		$window = null,
		AppriseQueue = [];

// Add overlay and set opacity for cross-browser compatibility
$(function() {
	
	$Apprise = $('<div class="apprise">'),
	$overlay = $('<div class="apprise-overlay">'),
	$body = $('body'),
	$window = $(window)
	
	$body.append( $overlay.css('opacity', '.94') ).append($Apprise);
});

function Apprise(text, options) {
	
	// Restrict blank modals
	if(text===undefined || !text) {
		return false;
	}
	
	// Necessary variables
	var $this = this,
			$_inner = $('<div class="apprise-inner">'),
			$_buttons = $('<div class="apprise-buttons">'),
			$_input = $('<input type="text">');
	
	// Default settings (edit these to your liking)
	var settings = {
	
		animation: 700,	// Animation speed
		buttons: {
			confirm: {
				action: function() { $this.closeApprise(); }, // Callback function
				className: null, // Custom class name(s)
				id: 'confirm', // Element ID
				text: 'Ok', // Button text
			}
		},
		input: false, // input dialog
		override: false, // Override browser navigation while Apprise is visible
	};
	
	// Merge settings with options
	$.extend(settings, options);
	
	// Close current Apprise, exit
	if(text==='close') { 
		$this.closeApprise();
		return;
	}
	
	// If an Apprise is already open, push it to the queue
	if($Apprise.is(':visible')) {

		AppriseQueue.push({text: text, options: settings});
	
		return;
	}
	
	// Width adjusting function
	this.adjustWidth = function() {
		
		var window_width = $window.width(), w = "20%", l = "40%";

		if(window_width<=800) {
			w = "90%", l = "5%";
		} else if(window_width <= 1400 && window_width > 800) {
			w = "70%", l = "15%";
		} else if(window_width <= 1800 && window_width > 1400) {
			w = "50%", l = "25%";
		} else if(window_width <= 2200 && window_width > 1800) {
			w = "30%", l = "35%";
		}
		
		$Apprise.css('width', w).css('left', l);
		
	};
	
	// Close function
	this.closeApprise = function() {
		
		$Apprise.animate({
			top: '-100%'
		}, settings.animation, function() {
			
			$overlay.fadeOut(300);
			$Apprise.hide();
			
			// Unbind window listeners
			$window.unbind("beforeunload");
			$window.unbind("keydown");

			// If in queue, run it
			if(AppriseQueue[0]) { 
				Apprise(AppriseQueue[0].text, AppriseQueue[0].options);
				AppriseQueue.splice(0,1);
			}
		});
		
		return;
	};
	
	// Keypress function
	this.keyPress = function() {
		
		$window.bind('keydown', function(e) {
			// Close if the ESC key is pressed
			if(e.keyCode===27) {
				$this.closeApprise();
			} else if(e.keyCode===13) {

				if(Object.keys(settings.buttons).length===1) {
					$this.closeApprise();
				}
			}
		});
	};
	
	// Add buttons
	$.each(settings.buttons, function(i, button) {
		
		if(button) {
			
			// Create button
			var $_button = $('<button id="apprise-btn-' + button.id + '">').append(button.text);
			
			// Add custom class names
			if(button.className) {
				$_button.addClass(button.className);
			}
			
			// Add to buttons
			$_buttons.append($_button);
			
			// Callback (or close) function
			$_button.on("click", function() {
				
				// Build response object
				var response = {
					clicked: button, // Pass back the object of the button that was clicked
					input: ($_input.val() ? $_input.val() : null) // User inputted text
				};
				
				button.action( response );
				//$this.closeApprise();
			});
		}
	});
	
	// Disabled browser actions while open
	if(settings.override) {
		$window.bind('beforeunload', function(e){ 
			return "An alert requires attention";
		});
	}
	
	// Adjust dimensions based on window
	$this.adjustWidth();
	
	$window.resize( function() { $this.adjustWidth() } );
	
	// Append elements, show Apprise
	$Apprise.html('').append( $_inner.append('<div class="apprise-content">' + text + '</div>') ).append($_buttons);
	
	if(settings.input) {
		$_inner.find('.apprise-content').append( $('<div class="apprise-input">').append( $_input ) );
	}
	
	$overlay.fadeIn(300);
	$Apprise.show().animate({
		top: '30%',
	}, 
		settings.animation, 
		function() {
			$this.keyPress();
		}
	);
	
	// Focus on input
	if(settings.input) {
		$_input.focus();
	}
	
} // end Apprise();

var isLoading = true;

$(function () {
    init();
});

function init() {
    preparedDate();
    validateNumber();
    datePickers();
}

$.ajaxSetup({
    cache: false
});

$(document).on("change", ".checkbox-true-false", function () {
    $(this).val($(this).prop("checked") ? true : false);
});

$(document).on("hidden.bs.modal", ".modal", function () {
    //clearFormElem(".modal");
});
//$(document).on("show.bs.modal", ".modal", function () {
//    clearFormElem(".modal");
//});

$(document).on("click", ".add-filter", function () {
    var option = $(this).closest('.row').find('select option:selected');
    var formid = $(this).data("formid");
    var value = $(option).val();
    if (value != '-1') {
        var model = {
            type: $(option).data('type'),
            description: $(option).text().trim(),
            name: value,
            url: $(option).data('url')
        }
        addFilter(formid, model);
    }
});

$(document).on('click', '.close-filter', function () {
    var value = $(this).data("value");
    var div = $(this).closest('div');
    var parentDiv = div.parent();

    $('.select-filter option[value=' + value + ']').show();
    resetFilter($(this).closest('form'));
    $(div).remove();

    if ($(parentDiv).find('.control-filter').length == 0) {
        $(parentDiv).find('.btn-filter').addClass('hide');
    }

    resizeAllGrids();
});

function addFilter(formid, model) {

    $('.btn-filter').removeClass('hide');
    var selector = '#' + formid + ' div:first';
    var html = createFilter(model);
    $(selector).prepend(html);
    preparedDate();

    resizeAllGrids();
}

function createFilter(filter) {
    var placeholder = filter.placeholder ? filter.placeholder : filter.description;
    var container = '<div class="form-group col-md-3 control-filter">';
    var label = '<label class="control-label" for="id' + filter.name + '">' + filter.description + '</label>';
    //var btnClose = '<button type="button" data-value="' + filter.name + '" class="close close-filter"><span aria-hidden="true">×</span><span class="sr-only">Cerrar</span></button>';
    var btnClose = '';
    var componen = '';
    var disabled = filter.defaultValue != null && filter.defaultValue.length > 0 ? ' disabled' : '';
    switch (filter.type) {
        case 1://textbox
            componen = '<input type="text" placeholder="' + placeholder + '" name="' + filter.name + '" id="id' + filter.name + '" class="form-control text-uppercase input-sm" value = "' + filter.defaultValue + '" ' + disabled + ' />';
            break;
        case 2://select
            componen = '<select name="' + filter.name + '" id="id' + filter.name + '" class="form-control input-sm chosen-select" ' + disabled + '><option value="">-- Seleccionar --</option></select>';
            loadSelect('id' + filter.name, filter.url, filter.defaultValue);
            break;
        case 3://date
            componen = '<div class=""><div class="input-group date" id="txtDate" data-date-format="dd/MM/yyy">' +
                '<input type="text" id="id' + filter.name + '" name="' + filter.name + '" readonly="readonly" class="form-control input-sm" />' +
                '<span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div>';
            break;
        case 4://date Range
            container = '<div class="form-group col-md-3 control-filter">' + btnClose +
                '<div class="row">' +
                '<div class="col-md-6" style="padding-right: 1px;">' +
                '<label class="control-label" for="idfrom' + filter.name + '">' + filter.description + ' - Desde</label>' +
                '<div data-date-format="dd/MM/yyyy" id="from" class="input-group date">' +
                '<input type="text" class="form-control input-sm" readonly="readonly" name="from' + filter.name + '" id="idfrom' + filter.name + '">' +
                '<span class="input-group-addon"><i class="fa fa-calendar"></i></span>' +
                '</div></div>' +
                '<div class="col-md-6" style="padding-left: 1px;">' +
                '<label class="control-label" for="idto' + filter.name + '">' + filter.description + ' - Hasta</label>' +
                '<div data-date-format="dd/MM/yyyy" id="to" class="input-group date">' +
                '<input type="text" class="form-control input-sm" readonly="readonly" id="idTo' + filter.name + '" name="to' + filter.name + '">' +
                '<span class="input-group-addon">' +
                '<span class="fa-calendar fa"></span>' +
                '</span></div></div></div></div>';
            return container;
        default:

    }

    return container + label + btnClose + componen + '</div>';
}

$(document).on("change", ".reloadChild", function () {
    var child = $(this).data('childid');
    var url = $(this).data('url');
    var value = $(this).val();
    loadSelect(child, url,value);

});

$(document).on("click", "a.delete:not(.disabled),li.delete:not(.disabled)", function (event, preventConfirm) {
    
    var $element = $(this),
        grids = $element.data("grid") ? $element.data("grid").split(' ') : undefined,
        url = $element.data('action'),
        id = $element.data('id'),
        callback = $element.data('callback');

    var cont = function (data) {
        if (grids) {
            for (var i = 0; i < grids.length; i++) {
                reloadGrid(grids[i], 1);
            }
        }

        callFn(callback, data);
    };

    confirm("Estás seguro de eliminar ?", function () {
        if (url) {
            $.ajax({
                type: "get",
                url: url,
                data: {
                    'id': id
                },
                success: function (d) {
                    if (d.success) {
                        success(d.message);
                        cont(d);
                    }
                },
                error: function (err) {
                    error(err);
                },
                dataType: 'json'
            });
        } else {
            cont(id);
        }
    });
    event.preventDefault();
    event.stopPropagation();
});

$(document).on("click", "a.changeState:not(.disabled),li.changeState:not(.disabled)", function (event, preventConfirm) {

    var $element = $(this),
        grids = $element.data("grid") ? $element.data("grid").split(' ') : undefined,
        url = $element.data('action'),
        id = $element.data('id'),
        ruc = $element.data('ruc'),
        state = $element.data('state'),
        callback = $element.data('callback');
    var cont = function (data) {
        if (grids) {
            for (var i = 0; i < grids.length; i++) {
                reloadGrid(grids[i], 1);
            }
        }

        callFn(callback, data);
    };

    var msj = "";
    if (state == "Inactivo") {
        msj = "activar";
    } else {
        msj = "desactivar";
    }

    confirm("¿Estás seguro de "+ msj + " la empresa " + ruc + "?", function () {
        if (url) {
            $.ajax({
                type: "get",
                url: url,
                data: {
                    'id': id
                },
                success: function (d) {
                    if (d.success) {
                        success(d.message);
                        cont(d);
                    }
                },
                error: function (err) {
                    error(err);
                },
                dataType: 'json'
            });
        } else {
            cont(id);
        }
    });
    event.preventDefault();
    event.stopPropagation();
});

$(document).on("submit", "form.modal-Crud", function () {
    var $form = $(this),
        data = getCrudFields($form),
        grids = $form.data("grid") ? $form.data("grid").split(' ') : undefined,
        modal = $form.data("modal"),
        url = $form.attr('action'),
        callback = $form.data("callback");

    var cont = function () {
        if (grids && grids != '') {
            for (var i = 0; i < grids.length; i++) {
                reloadGrid(grids[i], 1);
            }
        }

        if (callback && callback != '') {
            callFn(callback, data);
        }

        if (modal && modal != '') {
            $('#' + modal).modal('hide');
        }
    };

    if (url && url != '') {
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            dataType: 'json',
            success: function (d) {
                if (d.success == true) {
                    success(d.message || "Grabado Correctamente !!");
                    cont();
                } else {
                    error(d.message.length == 0 ? "Ocurrió un error. Por favor vuelva a interntarlo" : d.message);
                }
            },
            error: function (e) {
                error("Ocurrió un error. Por favor vuelva a interntarlo");
            },
        });
    } else {
        cont();
    }

    return false;
});

$(document).on("click", ".load-modal", function () {
    var $element = $(this),
        modal = $element.data("modal") || $element.closest("ul").data("modal"),
        url = $element.data('action'),
        id = $element.data('id'),
        hiddenId = $element.data('hidden'),
        callback = $element.data('callback'),
        viewUrl = $element.data('viewurl');

    if (hiddenId) {
        $("#" + hiddenId).val(id);
    }

    var data = { 'id': id };
    var dataType = "json";
    if (viewUrl) {
        data = "";
        dataType = "html";
    }

    if (url) {
        $.ajax({
            type: "get",
            url: url,
            data: data,
            dataType: dataType,
            success: function (d) {
                if (viewUrl) {
                    $('#' + modal).find(".modal-content").html(d);

                    if (hiddenId) {
                        $("#" + hiddenId).val(id);
                    }

                    jQuery.validator.unobtrusive.parse('#' + modal);
                    callFn(callback, id);
                } else {
                    callFn(callback, d);
                }

                if (modal) {
                    $('#' + modal).modal('show');
                }
            },
            error: function () {
                error("Error");
            }
        });
    } else {
        if (modal) {
            $('#' + modal).modal('show');
        }

        callFn(callback, id);
    }

    return false;
});

$(document).ajaxSend(function (e, response, options) {
    var preventLoading = false;
    if (!isLoading) {
        preventLoading = true;
        isLoading = true;
    } else {
        if (options.port) {

        } else if (options.url) {
            if (options.url.toString().indexOf("sidx") != -1) {
                preventLoading = true;
            }
        }
    }
    if (!preventLoading) {
        $("#loading-panel").show();
        $("#loading-panel").animate({ "right": "+=300px" }, "slow");
    }
});

$(document).ajaxComplete(function (event, xhr, options) {
    $("#loading-panel").animate({ "right": "-=300px" }, "slow", function () {
        $("#loading-panel").hide();
    });
    //if (xhr && xhr.responseJSON && xhr.responseJSON.success != undefined && !xhr.responseJSON.success) {
    //    var msg = xhr.responseJSON.message ? xhr.responseJSON.message : "Oops, it was an error, please try again";
    //    error(msg);
    //}
});

$(document).ajaxError(function (event, xhr, options, exception) {
    if (xhr.status === 0) {
        xhr.abort();
    } else {
        error(xhr.status == 500 ? xhr.responseText : xhr.statusText);
    }
});

function clearForm(id) {
    clearFormElem('#' + id);
}

function clearFormElem(elem) {
    $(elem).find('input, textarea, select').removeClass('input-validation-error').val('');
}

function validateNumber() {
    $(document).on("keypress", ".number,input[data-val-number]", function (event, elem) {
        if (!event.charCode) return true;
        var key = event.which;
        if (key >= 48 && key <= 57 // 0-9
            || key == 44 //,(colon)
            || key == 45 //-Minus
            || key == 46 //.(Numpad dot)
        ) {
            return true;
        }
        return false;
    });
}

function preparedDate() {
    $('.date-from,.date-to,.date,.calendar').datetimepicker({
        pickTime: false,
        language: 'es',
        icons: {
            time: "fa fa-clock-o",
            date: "fa fa-calendar",
            up: "fa fa-arrow-up",
            down: "fa fa-arrow-down"
        }
    });
}

function datePickers() {
    var input = $("input.calendar");
    $(input).removeClass("calendar").wrap("<div><div class='input-group date' data-date-format='dd/MM/yyy'></div>");
    $(input).parent().append("<span class='input-group-addon'><i class='fa fa-calendar'></i></span>");

    preparedDate();
}

function callFn(fn, object) {
    if (typeof window[fn] === "function") {
        var func = window[fn];
        return func.call(name, object);
    }

    return null;
};

function getCrudFields(formId) {
    var form = $(formId);
    var arr = form.serializeArray({ checkboxesAsBools : true });
    //arr = $.grep(arr, function (n) {
    //    return (n.value.length > 0);
    //});

    return arr;
}

function error(message) {
    showNotification('error', message);
}
function warning(message) {
    showNotification('warning', message);
}
function info(message) {
    showNotification('info', message);
}
function success(message) {
    showNotification('success', message);
}

function showNotification(type, message) {
    var title, color, icon;
    if (type == 'warning') {
        title = 'Warning';
        color = '#C79121';
        icon = 'fa fa-warning';
    } else if (type == 'error') {
        title = 'Error';
        color = '#CD3C54';
        icon = 'fa fa-thumbs-down';
    } else if (type == 'success') {
        title = 'Success';
        color = '#437C6A';
        icon = 'fa fa-thumbs-up';
    } else {
        title = 'Info';
        color = '#547989';
        icon = 'fa fa-info-circle';
    }

    toastr[type](message);
}

function confirm(message, confirmCallback, cancelCallback, confirmButtonText, cancelButtonText) {
    confirmButtonText = confirmButtonText || "Aceptar";
    cancelButtonText = cancelButtonText || "Cancelar";
    var options = {
        animation: 400,
        buttons: {

            cancel: {
                text: cancelButtonText,
                className: "btn btn-danger btn-xs",
                action: function () {
                    Apprise("close");
                    if ($.isFunction(cancelCallback)) {
                        cancelCallback.call(this);
                    }
                }
            },
            confirm: {
                text: confirmButtonText,
                className: "btn btn-primary btn-xs",
                action: function () {
                    Apprise("close");
                    if ($.isFunction(confirmCallback)) {
                        confirmCallback.call(this);
                    }
                }
            },
        }
    };
    Apprise(message, options);
}

function loadSelect(id, url, filterId) {
    if (url) {
        $.ajax({
            type: "get",
            url: url,
            data:{id :filterId===''?'0':filterId},
            success: function (d) {
                if (d.success) {

                    var select = $('#' + id);
                    var first = $(select).find('option').first();
                    $(select).html('');

                    var stringOptions = '';
                    for (var i = 0; i < d.values.length; i++) {
                        var item = d.values[i];

                        var selected = item.value == filterId ? ' selected' : '';

                        var option = '<option value="' + item.value + '" ' + selected + '>' + item.text + '</option>';
                        stringOptions += option;
                    }
                    $(select).append(first);
                    $(select).append(stringOptions);
                    $('#' + id).trigger('chosen:updated');
                } else {
                    error("Error");
                }
            },
            error: function (err) {
               error(err);
            },
            dataType: 'json'
        });
    }
}


