function clean_form_errors(form) {
    element = form.find('.has-error');
    element.removeClass('has-error has-feedback');
    element.find('.help-block').remove();
    element.find('.form-control-feedback').remove()
}

function show_form_errors(response, form) {
    if(response.status !== 422) return;
    $.each(response.responseJSON, function(campo, errores) {
        parent = form.find('[name="' + campo + '"]');
        if(parent.length) parent = parent.parent();
        else parent = form.find('[name="' + campo + '[]"]').parent();
        parent.addClass('has-error has-feedback');
        //parent.append('<i class="form-control-feedback glyphicon glyphicon-remove"></i>');
        parent.append('<small class="help-block">' + errores[0] + '</small>');
    });
}

function success_notification(response, size) {
    notification(response.message, size);
}

function error_notification(response, size) {
    if(response.status === 422) {
        $.each(response.responseJSON, function(campo, errores) {
            if (campo.indexOf('notification.') >= 0) notification({type: 'error', content: errores[0]}, size);
        });
        return; // error 422 (Unprocessable Entity) cuando hay errores en campos del formulario
    }
    if(response.status === 403) message = {type: 'error', content: 'No está autorizado para realizar esta acción'};
    else message = response.responseJSON.message;
    notification(message, size);
}

function notification(message, size) {
    size = size || 'small';
    type = message.type || 'success';
    content = message.content || '';
    timeout = message.timeout || 5000;

    if(type === 'success') {
        title = message.title || 'Exito';
        color = message.color || '#739E73';
        icon = message.icon || 'fa fa-check';
    } else if(type === 'error') {
        title = message.title || 'Error';
        color = message.color || '#C46A69';
        icon = message.icon || 'fa fa-warning';
    }

    if(size === 'small') {
        $.smallBox({
            title : title,
            content : content,
            color : color,
            icon : icon,
            timeout : timeout
        });
    } else if(size === 'big') {
        $.bigBox({
            title : title,
            content : content,
            color : color,
            icon : icon,
            timeout : timeout
        });                
    }
}

function getOS() {
	var userAgent = window.navigator.userAgent,
		platform = window.navigator.platform,
		macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
		windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
		iosPlatforms = ['iPhone', 'iPad', 'iPod'],
		os = null;

	if (macosPlatforms.indexOf(platform) !== -1) {
		os = 'Mac OS';
	} else if (iosPlatforms.indexOf(platform) !== -1) {
		os = 'iOS';
	} else if (windowsPlatforms.indexOf(platform) !== -1) {
		os = 'Windows';
	} else if (/Android/.test(userAgent)) {
		os = 'Android';
	} else if (!os && /Linux/.test(platform)) {
		os = 'Linux';
	}
	return os;
}

$.fn.formPopulate = function(data_url, callback) {
    id = this.find('input[name=id]').eq(0).val();
    var form = this;
    $.getJSON( data_url + '/' + id, function( data ) {
        form.find('input, select, textarea').each(function() {
            name = $(this).attr('name');
            if ($(this).prop('tagName') == 'INPUT') { // input
                type = $(this).attr('type');
                if(type == 'hidden') return true; // salta inputs hidden
                if(type == 'file') return true; // salta inputs file
            } else if ($(this).prop('tagName') == 'SELECT') { // select

            }
            name = name.replace('[]', '');
            if(data[name] != null && typeof data[name] == 'object') {
                ids = [];
                $.each(data[name], function(index, value) {
                    ids.push(value.id);
                });
                data[name] = ids;
            }
            $(this).val(data[name]);
        });
        if(jQuery.isFunction(callback))
            callback(data);
    });
};

//Setup para selects ajax
function setup_select2(id, url, placeholder) {
    $(id).select2({
        ajax: {
            url: url,
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;

                return {
                    results: data.data,
                    pagination: {
                        more: data.current_page < data.last_page
                    }
                };
            },
            cache: true
        },
        placeholder: placeholder,
        allowClear: false,
        minimumInputLength: 1,
        language: "es"
    });

    $('.select2-container').css('width', '100%');
}

function currency (value) {
    var arreglo = value.split('.');
    value = arreglo[0];
    var decimales = (1 in arreglo) ? ',' + arreglo[1] : '';
    var puntos = Math.ceil(value.length / 3) - 1;
    var mod = value.length % 3;
    var start = 0;
    var end = mod == 0? 3 : mod;
    var i;
    var result = '';
    if(value.length > 3) {
        for(i=0;i<puntos;i++) {
            if(result == '') {
                result = value.slice(start, end) + '.' + value.slice(end, end + 3);
                start = end + 3;
                end = end + 6;
            } else {
                result = result + '.' + value.slice(start, end);
                start = end;
                end = end + 3;
            }
        }
    } else {
        result = value;
    }
    return '$' + result + decimales;
}

function sortTable(n, tablename) {
    var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
    table = typeof tablename != 'undefined' ? document.getElementById(tablename) : event.target.closest('table');
    switching = true;
    // Set the sorting direction to ascending:
    dir = "asc";
    /* Make a loop that will continue until
     no switching has been done: */
    while (switching) {
        // Start by saying: no switching is done:
        switching = false;
        rows = table.rows;
        /* Loop through all table rows (except the
         first, which contains table headers): */
        for (i = 1; i < (rows.length - 1); i++) {
            // Start by saying there should be no switching:
            shouldSwitch = false;
            /* Get the two elements you want to compare,
             one from current row and one from the next: */
            x = rows[i].getElementsByTagName("TD")[n];
            y = rows[i + 1].getElementsByTagName("TD")[n];
            /* Check if the two rows should switch place,
             based on the direction, asc or desc: */
            if (dir == "asc") {
                if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                    // If so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            } else if (dir == "desc") {
                if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                    // If so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            }
        }
        if (shouldSwitch) {
            /* If a switch has been marked, make the switch
             and mark that a switch has been done: */
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
            // Each time a switch is done, increase this count by 1:
            switchcount ++;
        } else {
            /* If no switching has been done AND the direction is "asc",
             set the direction to "desc" and run the while loop again. */
            if (switchcount == 0 && dir == "asc") {
                dir = "desc";
                switching = true;
            }
        }
    }
}
