(function(sg) {



    // ejemplo de prueba	
    sg.addCustomTag({
        name: "sg-test",
        tagInit: function(element) {
            var texto = $(element).text();
            var html;
            html = '<p>' + texto + '</p>';
            $(element).html(html);
        }
    });
    //fin ejemplo de prueba

    sg.addCustomTag({
        name: "sg-video-tube",
        attr: ["sg-titulo-video"],
        tagInit: function(element) {
            var url = $(this).text();
            var html;
            var ancho = $(this).attr('width');
            var alto = $(this).attr('height');
            html = '<div class="video_play" id="videos">';
            html += ' <iframe id="video" width="' + ancho + '" height="' + alto + '" src="' + url + '" frameborder="0" allowfullscreen></iframe>';
            html += '</dvi>';
            posTop = $(this).offset().top;
            posleft = $(this).offset().left;
            $(this).html(html);
            $(this).css({
                'display': 'inline-block',
            });
            var cCartel = document.createElement('div');
            cCartel.setAttribute('class', 'cCartel');
            var tituloCartel = document.createElement('div');
            tituloCartel.setAttribute('class', 'titulocartel');
            var textTitulo = $(element).attr('data-sg-titulo-video');
            var lazos = new Image();
            lazos.src = '../../common/img/lazos.png';
            lazos.width = ancho * 0.6;
            lazos.onload;
            lazos.setAttribute('class', 'lazos')
            var tapVideo = document.createElement('div');
            tapVideo.setAttribute('class', 'tapVideo');
            $(this).append(cCartel);
            element = $(this);
            var cartel = $(this).children('.cCartel');
            cartel.append(lazos);
            console.log(posTop, posleft);
            cartel.append(tituloCartel);
            var hijoCartel = cartel.children('.titulocartel');
            hijoCartel.html('<h2>' + textTitulo + '</h2>');
            cartel.css({
                'text-align': 'center',
                'display': 'block',
                'position': 'absolute',
                'top': posTop - alto * 0.2,
                'left': posleft,
                'z-index': '100'
            });
            $('.titulocartel').css({
                'background': '#131a2d',
                'position': 'relative',
                'z-index': '80',
                'color': '#fff',
                'font-size': '1em',
                'padding': '10px',
                'border-radius': '10px',
                'box-shadow': '0px 0px 10px #000'
            });
            $('.titulocartel h2').css({
                'padding': '7px 10px 11px 10px',
                'border-radius': '7px',
                'border': '3px dashed #f3ec82'
            });
            //cVideo = document.getElementById('videos');
            var ancho_cartel = cartel.width();
            //console.log(ancho_cartel +' '+ ancho);

            if (ancho_cartel > ancho) {
                nuevoleft = (ancho_cartel - ancho) / 2;
                cartel.css('left', posleft - nuevoleft);
            } else {
                nuevoleft = (ancho - ancho_cartel) / 2;
                cartel.css('left', posleft + nuevoleft);
            }

            $(this).append(tapVideo);
            var tapVideo = $(this).children('.tapVideo');
            tapVideo.css({
                'position': 'absolute',
                'top': posTop,
                'left': posleft,
                'width': ancho,
                'height': alto,
                'display': 'inline-block',
                'z-index': '50'
            });
            $('.lazos').css('position', 'relative');
        },
        event: "click",
        eventHandle: function(element, event) {
            var cartel = $(this).children('.cCartel');
            var lazos = cartel.children('.lazos');
            lazos.animate({
                height: "toggle"
            }, 700, function() {
                cartel.children('.titulocartel').fadeOut();
                $(this).children('.tapVideo').remove();
                lazos.remove();
            });
        }
    });

    // sg-number - ATRIBUTO PARA INPUTS SOLO NUMERICOS

    sg.addCustomAttr({
        applyAll: true,
        name: "sg-number",
        init: function(element, attrValue) {
            $(element).keydown(function(e) {
                if (e.keyCode == 8) {

                } else if (e.keyCode == 13) {

                } else if ((e.keyCode < 48 || e.keyCode > 57) ^ (e.keyCode < 96 || e.keyCode > 105)) {

                } else {
                    e.preventDefault();
                }
            });
        },
    });

    // FINALIZA sg-numer

    // sg-texto - ATRIBUTO PARA INPUTS SOLO TEXTO

    sg.addCustomAttr({
        applyAll: true,
        name: "sg-texto",
        init: function(element, attrValue) {
            $(element).keydown(function(e) {
                if (e.keyCode == 8) {

                } else if (e.keyCode == 13) {

                } else if ((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) {

                } else {
                    e.preventDefault();
                }
            });
        },
    });

    // FINALIZA sg-texto


    // sg-titulos - ATRIBUTO PARA AJUSTES DE TITULOS
    sg.addCustomAttr({
        applyAll: true,
        name: "sg-titulos",
        init: function(element, attrValue) {
            $(element).css({
                'line-height': '62px',
                'font-size': '3.5em',
                'margin-top': '-40px'
            });
        },
    });
    // FINALIZA sg-titulos

    // sg-caption - CREDITOS EN LAS IMAGES // NOTA si la imgen es un drag dejar sg-draggable="true"
    sg.addCustomAttr({
        applyAll: true,
        name: "sg-caption",
        init: function(element, attrValue) {
            var nuevoElement = $(element).clone();
            var ubicacion = $(element).attr('data-sg-caption-top');
            $(element).before('<div class="caption" title="' + attrValue + '"></div>');
            if ($(element).attr('data-sg-draggable') == 'true') {
                var revert = $(element).attr('data-sg-revert');
                var dropselector = $(element).attr('data-sg-drop-selector');
                $(element).prev($(element).contents()).attr({
                    'data-sg-draggable': 'true',
                    'data-sg-revert': revert,
                    'data-sg-drop-selector': dropselector
                });

                nuevoElement.removeAttr('data-sg-draggable');
            }
            $(element).prev().append(nuevoElement);
            if (ubicacion == 'true') {
                $(element).prev().addClass('posi');
            }
            $(element).remove();
        },
    });
    // FINALIZA sg-caption

    // FUNCION POP PARA SOLO MENSAJES
    sg.extend({
        PopPupMensaje: function(mensaje, ColorB, ancho, alto) {
            if (ColorB == undefined) {
                ColorB = 'green';
            }
            if (ancho == undefined) {
                ancho = 400;
            }
            if (alto == undefined) {
                alto = 150;
            }
            var contepop = document.createElement('div');
            contepop.setAttribute("class", "contepopM");
            var contepup = document.createElement('div');
            contepup.setAttribute("class", "contepupM");
            $('.ggb_contenidoInterno').append(contepop);
            $('.contepopM').css({
                'position': 'fixed',
                'top': '-1000px',
                'left': '-800px',
                'width': '350%',
                'height': '380%',
                'z-index': '400',
                'background': 'rgba(0, 0, 0, 0.3)',
                'display': 'block'
            });
            $('.ggb_contenidoInterno').append(contepup);
            $('.contepupM').css({
                'position': 'fixed',
                'top': '50%',
                'left': '50%',
                'width': ancho,
                'height': alto,
                'margin-left': -(ancho / 2) + 'px',
                'margin-top': -(alto / 2) + 'px',
                'z-index': '500',
                'background': '#EDCCA8',
                'border': '3px solid',
                'border-color': ColorB,
                'text-align': 'center',
                'display': 'block'
            });
            html = '<div>';
            html += '</div>';
            $('.contepupM').html(mensaje);
        }
    });

    // FIN FUNCION POP SOLO MENSAJES

    sg.addCustomTag({
        name: "sg-conte-pop",
        attr: ["sg-pup"],
        tagInit: function(element) {
            var contepop = document.createElement('div');
            contepop.setAttribute("class", "contepop");
            var contepup = document.createElement('div');
            contepup.setAttribute("class", "contepup");
            $(element).css('display', 'inline-block');
            cualpop = $(element).attr('data-sg-pup');
            contepop.setAttribute("key", cualpop);
            contepup.setAttribute("key", cualpop);
            $('.ggb_contenidoInterno').append(contepop);
            $('.contepop').css({
                'display': 'none',
                'position': 'fixed',
                'top': '-1000px',
                'left': '-800px',
                'width': '350%',
                'height': '380%',
                'z-index': '400',
                'background': 'rgba(0, 0, 0, 0.3)',
            });
            $('.contepop[key=' + cualpop + ']').append(contepup);
            $('.contepup[key=' + cualpop + ']').append($(element).contents());
            var alto = $(element).height();
            var ancho = $(element).width();
            $('.contepup').css({
                'position': 'fixed',
                'display': 'none',
                'top': '50%',
                'left': '50%',
                'z-index': '500',
            });
            $(element).css('display', 'none');
        }
    });

    sg.extend({
        abrirPop: function(target) {
            $('.contepop[key=' + target + ']').css('display', 'block');
            $('.contepup[key=' + target + ']').css('display', 'block');
            var ancho = $('.contepup[key=' + target + ']').width();
            var alto = $('.contepup[key=' + target + ']').height();
            $('.contepup[key=' + target + ']').css({
                'margin-left': -(ancho / 2) + 'px',
                'margin-top': -(alto / 2) + 'px',
            })
        }
    });

    sg.extend({
        cerrarPop: function(target) {
            $('.contepop[key=' + target + ']').css('display', 'none');
            $('.contepup[key=' + target + ']').css('display', 'none');
        }
    });


    sg.addCustomTag({
        name: "sg-video-play",
        attr: ["src", "type", "ancho", "alto"],
        tagInit: function(element) {
            var src = $(element).attr('src');
            var type = $(element).attr('type');
            var key = $(element).attr('video-key');
            var elemento = $(element);
            elemento.append('<div class="reproductor">');
            var reproductor = elemento.children('div.reproductor');
            reproductor.append('<video width="100%">');
            elemento.children('div.reproductor').children('video').attr('video-key', key);
            var html = '<source src="' + src + '" type="' + type + '""></source>';
            video = elemento.children('div.reproductor').children('video')
            video.html(html);
            reproductor.append('<div class="controles">');
            var controles = reproductor.children('.controles');
            html = '<div class="estado" data-sg-click="sg.playVideo(' + key + ')" style="vertical-align: 7px;"><i class="fa fa-play"></i></div>';
            controles.append(html);
            html = '<div class="progreso" data-sg-click="sg.progreso(' + key + ', event)" style="vertical-align: 7px;"><div class="conteprose"></div></div>';
            controles.append(html);
            html = '<div class="tiempo" style="vertical-align: 7px;"><span class="min">00</span>:<span class="seg">00</span></div>';
            controles.append(html);
            // html = '<div class="audio" data-sg-click="sg.videomute(' + key + ')"><i class="fa fa-volume-up"></i></div>'
            // controles.append(html);
            html = '<div class="expandir" data-sg-click="sg.videoexpande(' + key + ')" style="vertical-align: 7px;"><i class="fa fa-expand"></i></div>';
            controles.append(html);
            html = '<div class="logo" style="padding-left: 5px;"><img src="img/logo-player.png" height=25px></div>';
            controles.append(html);
            var ancho = elemento.attr('ancho');
            var alto = elemento.attr('alto');
            if (ancho) {
                reproductor.width(ancho);
            }
            if (alto) {
                video.height(alto);
            }
        },
        /*
        event: "pause",
        eventHandle: function(element, event) {
            console.log('ok');
        }*/
    });



    var progresos = new Array();
    var esteVideo;
    var tseg = new Array();
    var tmin = new Array();
    var divide = new Array();
    var control = new Array();
    var timeAnte = new Array();
    sg.extend({
        playVideo: function(target) {
            var video = $('video[video-key=' + target + ']');
            var estado = video.siblings('.controles').children('.estado');
            var controlplay = estado.children('i');
            clases = controlplay.attr('class').split(' ')[1];
            if (clases == 'fa-play') {
                video.get(0).play();
                esteVideo = target;
                timeAnte[esteVideo - 1] = video.get(0).currentTime;
                progresos[target - 1] = setInterval(function() {
                    var video = $('video[video-key=' + esteVideo + ']');
                    var estado = video.siblings('.controles').children('.estado');
                    var progress = video.siblings('.controles').children('.progreso');
                    var conprogreso = progress.children('.conteprose');
                    var anchoTotal = progress.width();
                    var ancho = video.get(0).currentTime * anchoTotal / video.get(0).duration;
                    conprogreso.css({
                        'width': ancho + 'px'
                    });
                    var tiempo = video.siblings('.controles').children('.tiempo');
                    var segundos = tiempo.children('.seg');
                    var minutos = tiempo.children('.min');

                    if (video.get(0).duration > video.get(0).currentTime) {
                        divide[esteVideo - 1] = Math.floor((video.get(0).currentTime / 60));
                        if (divide[esteVideo - 1] != 0) {
                            control[esteVideo - 1] = divide[esteVideo - 1] * 60;
                        } else {
                            control[esteVideo - 1] = 1;
                        }
                        if (Math.floor(video.get(0).currentTime) == 0)
                            tseg[esteVideo - 1] = Math.floor(video.get(0).currentTime);
                        else
                            tseg[esteVideo - 1] = Math.floor(video.get(0).currentTime) - control[esteVideo - 1];
                        tmin[esteVideo - 1] = Math.floor(video.get(0).currentTime / 60);
                        if (tseg[esteVideo - 1] < 10) {
                            segundos.html('0' + tseg[esteVideo - 1]);
                        } else if (tseg[esteVideo - 1] >= 10 && tseg[esteVideo - 1] < 60) {
                            segundos.html(tseg[esteVideo - 1]);
                        }
                        if (tmin[esteVideo - 1] < 10) {
                            minutos.html('0' + tmin[esteVideo - 1]);
                        } else {
                            minutos.html(tmin[esteVideo - 1]);
                        }

                    } else {
                        tseg[esteVideo - 1] = 0;
                        tmin[esteVideo - 1] = 0;
                        divide[esteVideo - 1] = 0;
                        control[esteVideo - 1] = 0;
                        video.get(0).currentTime = 0;
                        video.get(0).pause();
                        estado.children('i').remove();
                        estado.append('<i class="fa fa-play">');
                        conprogreso.css({
                            'width': '0px'
                        });
                        minutos.html('00');
                        segundos.html('00');
                        clearInterval(progresos[target - 1]);
                    }
                }, 1000);
                estado.children('i').remove();
                estado.append('<i class="fa fa-pause">');
            } else {
                video.get(0).pause();
                clearInterval(progresos[target - 1]);
                estado.children('i').remove();
                estado.append('<i class="fa fa-play">');
            }
        }
    });

	sg.extend({
        pauseVideo: function(target) {
            var video = $('video[video-key=' + target + ']');
            var estado = video.siblings('.controles').children('.estado');
            var controlplay = estado.children('i');
			video.get(0).pause();
			estado.children('i').remove();
            estado.append('<i class="fa fa-play">');
        }
    });

    sg.extend({
        videomute: function(target) {
            var video = $('video[video-key=' + target + ']');
            var audio = video.siblings('.controles').children('.audio');
            var controlplay = audio.children('i');
            clases = controlplay.attr('class').split(' ')[1];
            if (clases == 'fa-volume-up') {
                video.get(0).volume = 0;
                audio.children('i').remove();
                audio.append('<i class="fa fa-volume-off">');
            } else {
                video.get(0).volume = 1;
                audio.children('i').remove();
                audio.append('<i class="fa fa-volume-up">');
            }
        }
    });

    sg.extend({
        progreso: function(target, event) {
            var matrix = $("#stage").css('transform').split('(')[1].split(',')[0];
            var video = $('video[video-key=' + target + ']');
            var elemento = event.target;
            var elem = $(event.target);
            var posX = event.clientX - elemento.getBoundingClientRect().left;
            var posY = event.clientY - elemento.getBoundingClientRect().top;
            var progress = video.siblings('.controles').children('.progreso');
            var conprogreso = progress.children('.conteprose');
            posX = posX / matrix;
            video.get(0).currentTime = posX * video.get(0).duration / elem.width();
            conprogreso.css({
                'width': posX + 'px'
            });
        }
    });

    sg.extend({
        videoexpande: function(target) {
            var video = $('video[video-key=' + target + ']');
            video = video.get(0);
            if (video.requestFullscreen) {
                video.requestFullscreen();
            } else if (video.msRequestFullscreen) {
                video.msRequestFullscreen();
            } else if (video.mozRequestFullScreen) {
                video.mozRequestFullScreen();
            } else if (video.webkitRequestFullscreen) {
                video.webkitRequestFullscreen();
            }

        }

    });

})(sg)