// JavaScript Document
//agrego funciones al prototype
if (typeof String.prototype.trim !== 'function') { // funcion para quitar espacios en blanco al inicio y final  de la cadena
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, "");
    }
}

if (typeof String.prototype.ucwords !== 'function') { // funcion para pasar a mayusculas el primer caracter de cada palabra
    String.prototype.ucwords = function() {
        str = this.toLowerCase()
        return (str + '').replace(/^([a-z])|\s+([a-z])/g, function($1) {
            return $1.toUpperCase();
        });
    }
}
var statusErrorMap = {
    '400': "Server understood the request but request content was invalid.",
    '401': "Unauthorised access.",
    '403': "Forbidden resouce can't be accessed",
    '500': "Internal Server Error.",
    '503': "Service Unavailable"
};
jQuery.fn.reset = function() {
    $(this).each(function() {
        this.reset();
    });
}
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
jQuery.jPrintArea = function(el)
{
    var iframe = document.createElement('IFRAME');
    var doc = null;
    $(iframe).attr('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
    document.body.appendChild(iframe);
    doc = iframe.contentWindow.document;
    var links = window.document.getElementsByTagName('link');
    for (var i = 0; i < links.length; i++)
        if (links[i].rel.toLowerCase() == 'stylesheet')
            doc.write('<link type="text/css" rel="stylesheet" href="' + links[i].href + '"></link>');
    doc.write('<div class="' + $(el).attr("class") + '">' + $(el).html() + '</div>');
    doc.close();
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
    doc.write("");
    document.body.removeChild(iframe);
}
$.formatMsg = function(source, params) {
    if (arguments.length === 1) {
        return function() {
            var args = $.makeArray(arguments);
            args.unshift(source);
            return $.validator.format.apply(this, args);
        };
    }
    if (arguments.length > 2 && params.constructor !== Array) {
        params = $.makeArray(arguments).slice(1);
    }
    if (params.constructor !== Array) {
        params = [params];
    }
    $.each(params, function(i, n) {
        source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
    });
    return source;
};

$.extend({
    fRight: function(str, n) {
        if (n <= 0)
            return "";
        else if (n > String(str).length)
            return str;
        else {
            var iLen = String(str).length;
            return String(str).substring(iLen, iLen - n);
        }
    },
    fLeft: function(str, n) {
        if (n <= 0)
            return "";
        else if (n > String(str).length)
            return str;
        else
            return String(str).substring(0, n);
    },
    validaErrorRta: function(error, mod, func) {
        var modulo = mod;
        if (error != 0) { 
            if (error == 'session') { 
                modulo = 'global'
            }
            jAlert(getMsg(modulo, error), dtsLang.project.empresa, 'error', function() {
                if (error == 'session') {
                    $.fn.colorbox.close();
                    location.reload();
                    return true;
                }
                return true;
            });
            return true;
        } else {
            return false;
        }
    },
    toFixedFix: function(n, decimals) {
        var k = Math.pow(10, decimals);
        return '' + Math.round(n * k) / k;
    },
    numberFormat: function(valor, decimals, thousands_sep, dec_point, retNum) {
        var thousands_sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
                dec_point = (typeof dec_point === 'undefined') ? '.' : dec_point,
                decimals = !isFinite(+decimals) ? 1 : Math.abs(decimals), s,
                retornaNum = (typeof retNum === 'undefined') ? false : retNum

        valor = parseFloat(valor);
        valor = isNaN(valor) ? 0.0 : valor;
        
        s = (decimals ? $.toFixedFix(valor, decimals) : '' + Math.round(valor)).split('.');

        if (!retornaNum) {
            if (s[0].length > 3) {
                s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, thousands_sep);
            }
        }
        if ((s[1] || '').length < decimals) {
            s[1] = s[1] || '';
            s[1] += new Array(decimals - s[1].length + 1).join('0');
        }

        return retornaNum ? parseFloat(s.join(dec_point)) : s.join(dec_point) ;
    },
});

function errorCode(x, e) {
    var message;

    if (x) {
        message = statusErrorMap[x];
        if (!message) {
            message = "Unknow Error  xxx \n.";
        }
    } else if (e == 'parsererror') {
        message = "Error.\nParsing JSON Request failed.";
    } else if (e == 'timeout') {
        message = "Request Time out.";
    } else if (e == 'abort') {
        message = "Request was aborted by the server";
    } else {
        message = "Unknow Error \n.";
    }
    return message;
}

function color(grid, rowid, nota_dic) {
    switch (nota_dic) {
        case 'Excelente':
            grid.setCell(rowid, 'nota_dic', '', {color: '#338E2B'});
            break;
        case 'Bueno':
            grid.setCell(rowid, 'nota_dic', '', {color: 'blue'});
            break;
        case 'Aceptable':
            grid.setCell(rowid, 'nota_dic', '', {color: '#EB9E0E'});
            break;
        case 'Insuficiente':
            grid.setCell(rowid, 'nota_dic', '', {color: 'red'});
            break;
    }
}
function innerSearch(node, pat) {
    var skip = 0;
    if (node.nodeType == 3) {
        var pos = node.data.toUpperCase().indexOf(pat);
        if (pos >= 0) {
            skip = 1;
        }
    } else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
        for (var i = 0; i < node.childNodes.length; ++i) {
            skip += innerSearch(node.childNodes[i], pat);
            //alert(skip);
        }
    }
    return skip;
}
function ajaxFileUpload($cc) {
    var name = $("#fileToUpload").val();
    var ext = name.split('.')
    if (!(ext[1] && /^(jpg|png|jpeg|gif)$/.test(ext[1]))) {// extensiones permitidas
        alert('Error: Solo se permiten imagenes');
        // cancela upload
        return false;
    } else {
        //button.text('Uploading');
        $("#txtext").val(ext[1]);
        $("#buttonUpload").attr('diseable');
    }
    $.ajaxFileUpload({
        url: 'includes/fileupload.php',
        secureuri: false,
        fileElementId: 'fileToUpload',
        dataType: 'json',
        data: {cc: $cc},
        success: function(data, status) {
            if (typeof (data.error) != 'undefined') {
                if (data.error != '') {
                    alert(data.error);
                } else {
                    //alert(data.msg);
                }
            }
            $("#buttonUpload").removeAttr('diseable');
        },
        error: function(data, status, e) {
            alert(e);
        }
    }
    )

    return true;

}

function getMsg(lug_msg, id_msg) {
    var msg = ''
    if (dtsLang[lug_msg][id_msg]) {
        return dtsLang[lug_msg][id_msg];
    }
    $.ajax({
        type: "POST",
        url: "includes/mostrar_msg.php",
        data: {lug_msg: lug_msg, id_msg: id_msg},
        async: false,
        success: function(ms) {
            msg = ms;
        }
    });
    while (msg.indexOf("@") > 0) {
        msg = msg.replace('@', '\n');
    }
    return msg;
}

//coloca estilo a las tabla 
function notifica_e(msg) {
    $.notifyBar({cls: "error",
        html: msg,
        delay: 1500,
        animationSpeed: "normal"
    });
}

function notifica_ok(msg, tiempo) {
    tp = (tiempo) ? tiempo : 2000;
    $.blockUI({
        message: '<table border=0 style="margin-left:30px; font-size:14px;"><tr><td align="left">' + msg + '</td></tr></table>',
        fadeIn: 700,
        fadeOut: 700,
        timeout: tp,
        showOverlay: false,
        centerY: false,
        css: {
            width: '380px',
            top: '70px',
            left: '',
            right: '15px',
            border: 'none',
            padding: '8px 3px 8px 3px',
            background: '#BBFFB6 url(css/images/exito.png) no-repeat left center',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .9,
            color: '#060',
            height: 'auto',
//				'vertical-align': 'middle',
            'border-radius': '10px',
            'z-index': 9999
        },
        zindex: 10000
    });
}

function colorear_tb(id) {
    $(document).ready(function() {
        $('#' + id).styleTable({
            th_bgcolor: '#BCD4EC',
            th_color: '#fff',
            th_image: 'css/images/bg_hover.png',
            tr_odd_image: 'css/images/bg.jpg',
            tr_even_image: 'css/images/bg.jpg',
            tr_hover_image: 'css/images/bg_topbar.gif',
            font_name: 'Verdana',
            font_size: '11'
        });
    })
}

function calcular_edad(fech_nac, fec_com) {
    fecha_hoy = fec_com.split('-')

    anioac = fecha_hoy[0];
    mesac = fecha_hoy[1];
    diaac = fecha_hoy[2];

    fn = fech_nac.split('-')
    anionac = fn[0]
    mesnac = fn[1]
    dianac = fn[2]

    diff_year = anioac - anionac
    diff_month = mesac - mesnac
    diff_day = diaac - dianac

    if (diff_month < 0 || (diff_month == 0 && diff_day < 0))
        diff_year = diff_year - 1 //no aparecían los dos guiones del postincremento :|

    return diff_year;
}

//-----------------------------------------------------
function fRight(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

function fLeft(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}

//---------------------------------------------------------------------------------------------------------------------


/*
 Ultimate Age calculator script- By JavaScript Kit (http://www.javascriptkit.com)
 Over 200+ free scripts here!
 Credit must stay intact for use
 Modified by Gabriel Espinoza Erices (May 12, 2011) to remove the countunit from the return value in order to get a number instead of a string.
 */

var one_day = 1000 * 60 * 60 * 24;
var one_month = 1000 * 60 * 60 * 24 * 30;
var one_year = 1000 * 60 * 60 * 24 * 30 * 12;

function displayage(yr, mon, day, unit, decimal, round) {
    today = new Date();
    var pastdate = new Date(yr, mon - 1, day);

    var countunit = unit;
    var decimals = decimal;
    var rounding = round;

    finalunit = (countunit == "days") ? one_day : (countunit == "months") ? one_month : one_year;
    decimals = (decimals <= 0) ? 1 : decimals * 10;

    if (unit != "years") {
        if (rounding == "rounddown") {
            //document.write(Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals + " " + countunit);
            return (Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals);
        }
        else {
            //document.write(Math.ceil((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals + " " + countunit);
            return (Math.ceil((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals);
        }
    }
    else {
        yearspast = today.getFullYear() - yr - 1;
        tail = (today.getMonth() > mon - 1 || today.getMonth() == mon - 1 && today.getDate() >= day) ? 1 : 0;
        pastdate.setFullYear(today.getFullYear());
        pastdate2 = new Date(today.getFullYear() - 1, mon - 1, day);
        tail = (tail == 1) ? tail + Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals : Math.floor((today.getTime() - pastdate2.getTime()) / (finalunit) * decimals) / decimals;
        //document.write(yearspast + tail + " " + countunit);
        return (yearspast + tail);
    }
}

//Sample usage
//displayage (year, month, day, unit, decimals, rounding)
//Unit can be "years", "months", or "days"
//Decimals specifies demical places to round to (ie: 2)
//Rounding can be "roundup" or "rounddown"

//displayage(1997, 11, 24, "years", 0, "rounddown")

/*-------------------------------------------------------------------------------------------------------------------------------------*/
/* bootstrap-tooltip.js v2.1.1
 * http://twitter.github.com/bootstrap/javascript.html#tooltips
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ===========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */


!function($) {

    "use strict"; // jshint ;_;


    /* TOOLTIP PUBLIC CLASS DEFINITION
     * =============================== */

    var Tooltip = function(element, options) {
        this.init('tooltip', element, options)
    }

    Tooltip.prototype = {
        constructor: Tooltip 

        , init: function(type, element, options) {
            var eventIn
                    , eventOut

            this.type = type
            this.$element = $(element)
            this.options = this.getOptions(options)
            this.enabled = true

            if (this.options.trigger == 'click') {
                this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
            } else if (this.options.trigger != 'manual') {
                eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus'
                eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur'
                this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
                this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
            }

            this.options.selector ?
                    (this._options = $.extend({}, this.options, {trigger: 'manual', selector: ''})) :
                    this.fixTitle()
        }

        , getOptions: function(options) {
            options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data())

            if (options.delay && typeof options.delay == 'number') {
                options.delay = {
                    show: options.delay
                    , hide: options.delay
                }
            }

            return options
        }

        , enter: function(e) {
            var self = $(e.currentTarget)[this.type](this._options).data(this.type)

            if (!self.options.delay || !self.options.delay.show)
                return self.show()

            clearTimeout(this.timeout)
            self.hoverState = 'in'
            this.timeout = setTimeout(function() {
                if (self.hoverState == 'in')
                    self.show()
            }, self.options.delay.show)
        }

        , leave: function(e) {
            var self = $(e.currentTarget)[this.type](this._options).data(this.type)

            if (this.timeout)
                clearTimeout(this.timeout)
            if (!self.options.delay || !self.options.delay.hide)
                return self.hide()

            self.hoverState = 'out'
            this.timeout = setTimeout(function() {
                if (self.hoverState == 'out')
                    self.hide()
            }, self.options.delay.hide)
        }

        , show: function() {
            var $tip
                    , inside
                    , pos
                    , actualWidth
                    , actualHeight
                    , placement
                    , tp

            if (this.hasContent() && this.enabled) {
                $tip = this.tip()
                this.setContent()

                if (this.options.animation) {
                    $tip.addClass('fade')
                }

                placement = typeof this.options.placement == 'function' ?
                        this.options.placement.call(this, $tip[0], this.$element[0]) :
                        this.options.placement

                inside = /in/.test(placement)

                $tip
                        .remove()
                        .css({top: 0, left: 0, display: 'block'})
                        .appendTo(inside ? this.$element : document.body)

                pos = this.getPosition(inside)

                actualWidth = $tip[0].offsetWidth
                actualHeight = $tip[0].offsetHeight

                switch (inside ? placement.split(' ')[1] : placement) {
                    case 'bottom':
                        tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
                        break
                    case 'top':
                        tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
                        break
                    case 'left':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
                        break
                    case 'right':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
                        break
                }

                $tip
                        .css(tp)
                        .addClass(placement)
                        .addClass('in')
            }
        }

        , setContent: function() {
            var $tip = this.tip()
                    , title = this.getTitle()

            $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
            $tip.removeClass('fade in top bottom left right')
        }

        , hide: function() {
            var that = this
                    , $tip = this.tip()

            $tip.removeClass('in')

            function removeWithAnimation() {
                var timeout = setTimeout(function() {
                    $tip.off($.support.transition.end).remove()
                }, 500)

                $tip.one($.support.transition.end, function() {
                    clearTimeout(timeout)
                    $tip.remove()
                })
            }

            $.support.transition && this.$tip.hasClass('fade') ?
                    removeWithAnimation() :
                    $tip.remove()

            return this
        }

        , fixTitle: function() {
            var $e = this.$element
            if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
                $e.attr('data-original-title', $e.attr('title') || '').removeAttr('title')
            }
        }

        , hasContent: function() {
            return this.getTitle()
        }

        , getPosition: function(inside) {
            return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), {
                width: this.$element[0].offsetWidth
                , height: this.$element[0].offsetHeight
            })
        }

        , getTitle: function() {
            var title
                    , $e = this.$element
                    , o = this.options

            title = $e.attr('data-original-title')
                    || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)

            return title
        }

        , tip: function() {
            return this.$tip = this.$tip || $(this.options.template)
        }

        , validate: function() {
            if (!this.$element[0].parentNode) {
                this.hide()
                this.$element = null
                this.options = null
            }
        }

        , enable: function() {
            this.enabled = true
        }

        , disable: function() {
            this.enabled = false
        }

        , toggleEnabled: function() {
            this.enabled = !this.enabled
        }

        , toggle: function() {
            this[this.tip().hasClass('in') ? 'hide' : 'show']()
        }

        , destroy: function() {
            this.hide().$element.off('.' + this.type).removeData(this.type)
        }

    }


    /* TOOLTIP PLUGIN DEFINITION
     * ========================= */

    $.fn.tooltip = function(option) {
        return this.each(function() {
            var $this = $(this)
                    , data = $this.data('tooltip')
                    , options = typeof option == 'object' && option
            if (!data)
                $this.data('tooltip', (data = new Tooltip(this, options)))
            if (typeof option == 'string')
                data[option]()
        })
    }

    $.fn.tooltip.Constructor = Tooltip

    $.fn.tooltip.defaults = {
        animation: true
        , placement: 'top'
        , selector: false
        , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
        , trigger: 'hover'
        , title: ''
        , delay: 0
        , html: true
    }

}(window.jQuery);
 	