"use strict";
var webvideo = (function (){
    var webvideo = function(api){

        this.Vid = api.id;
        this.Vwidth = api.width;
        this.Vheight = api.height;
        this.Vsrc = api.src;
        this.Vdefinition = api.definition || 0;
        this.fixed = api.fixed || 0;
        this.Vimage = api.image || 'http://qnoss2.lanlanlife.com/1b20062c8951ed036cb209d6185bebdc_1x1.jpg';

        if (typeof this.Vid !== "undefined" && typeof this.Vwidth !== "undefined" && typeof this.Vheight !== "undefined" && typeof this.Vsrc !== "undefined") this._init();

    };

    /*----- 公共变量 -----*/
    var startbutton = [
        '<svg width="58px" height="58px" viewBox="0 0 58 58" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">',
        '<!-- Generator: Sketch 3.4 (15575) - http://www.bohemiancoding.com/sketch -->',
        '<title>开始</title>',
        '<desc>Created with Sketch.</desc>',
        '<defs></defs>',
        '<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">',
        '<g id="默认" sketch:type="MSArtboardGroup" transform="translate(-159.000000, -68.000000)">',
        '<g id="开始" sketch:type="MSLayerGroup" transform="translate(160.000000, 69.000000)">',
        '<circle id="Oval-1" stroke="#FFFFFF" fill-opacity="0.37" fill="#000000" sketch:type="MSShapeGroup" cx="28" cy="28" r="28"></circle>',
        '<polygon id="Triangle-1" fill="#FFFFFF" sketch:type="MSShapeGroup" transform="translate(31.250852, 28.198349) rotate(-270.000000) translate(-31.250852, -28.198349) " points="31.0525028 17.4492006 44.0525028 38.4492006 18.0525028 38.4492006 "></polygon>',
        '</g>',
        '</g>',
        '</g>',
        '</svg>'
        ];
    var suspendbutton = [
        '<?xml version="1.0" encoding="UTF-8" standalone="no"?>',
        '<svg width="58px" height="58px" viewBox="0 0 58 58" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">',
        '<!-- Generator: Sketch 3.4 (15575) - http://www.bohemiancoding.com/sketch -->',
        '<title>暂停</title>',
        '<desc>Created with Sketch.</desc>',
        '<defs></defs>',
        '<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">',
        '<g id="暂停" sketch:type="MSArtboardGroup" transform="translate(-159.000000, -68.000000)">',
        '<g sketch:type="MSLayerGroup" transform="translate(160.000000, 69.000000)">',
        '<circle id="Oval-1" stroke="#FFFFFF" fill-opacity="0.37" fill="#000000" sketch:type="MSShapeGroup" cx="28" cy="28" r="28"></circle>',
        '<path d="M33,16 L35,16 L35,40 L33,40 L33,16 Z M21,16 L23,16 L23,40 L21,40 L21,16 Z" id="Rectangle-10" fill="#FFFFFF" sketch:type="MSShapeGroup"></path>',
        '</g>',
        '</g>',
        '</g>',
        '</svg>'
    ];
    var screen = [
        '<?xml version="1.0" encoding="UTF-8" standalone="no"?>',
        '<svg width="13px" height="13px" viewBox="0 0 13 13" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">',
        '<!-- Generator: Sketch 3.4 (15575) - http://www.bohemiancoding.com/sketch -->',
        '<title>全屏</title>',
        '<desc>Created with Sketch.</desc>',
        '<defs></defs>',
        '<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">',
        '<g id="暂停" sketch:type="MSArtboardGroup" transform="translate(-343.000000, -194.000000)" stroke="#FFFFFF">',
        '<g id="功能条" sketch:type="MSLayerGroup" transform="translate(0.000000, 189.000000)">',
        '<g id="全屏" transform="translate(343.000000, 5.000000)" sketch:type="MSShapeGroup">',
        '<path d="M12,8 L13,8 L13,13 L8,13 L8,12 L8,12" id="Rectangle-3"></path>',
        '<path d="M5,11.9942017 L5,13 L0,13 L0,8 L0.996765137,8" id="Rectangle-4"></path>',
        '<path d="M8,1.00390625 L8,0 L13,0 L13,5 L12,5" id="Rectangle-2"></path>',
        '<path d="M0.996337891,5 L0,5 L0,0 L5,0 L5,0.998352051" id="Rectangle-1"></path>',
        '</g>',
        '</g>',
        '</g>',
        '</g>',
        '</svg>'
    ]
    var progressFlag = null;
    var functime = null;
    var functotal = null;
    var funcpass = null;
    var settimestart = 1;
    /*----- 公共变量end -----*/

    /*----- 公共方法 -----*/
    //判断浏览器
    (function navigar(){
        var browser={
            versions:function(){
                var u = navigator.userAgent, app = navigator.appVersion;
                return {
                    trident: u.indexOf('Trident') > -1, //IE内核
                    presto: u.indexOf('Presto') > -1, //opera内核
                    webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
                    iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
                    iPad: u.indexOf('iPad') > -1, //是否iPad
                    webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                    weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
                    qq: u.match(/\sQQ/i) == " qq" //是否QQ
                };
            }(),
            language:(navigator.browserLanguage || navigator.language).toLowerCase()
        };

        webvideo.prototype.browser = browser.versions
    })();
    //获取id节点
    function getId(idName){
        return document.getElementById(idName);
    };
    // 选择器
    function selectors(idName,dataName){
        var domArray = getId(idName).getElementsByTagName('*');
        var patt1=new RegExp(dataName);
        var dom = null;

        var fn=function(doms){
            return doms.attributes[0]==undefined? null:doms.attributes[0].name;
        };
        for(var i = 0;i<domArray.length;i++){
            if( patt1.test(fn(domArray[i])) ) {
                dom=domArray[i];
                return dom
                break;
            }
        }
    };
    //窗口绘制
    function frome(id,width,height,src,image){
        var DomId = getId(id);
        var DomWidth = DomId.clientWidth;

        var IfWidth = width > DomWidth ? 1 : 0;

        var bili = DomWidth/width;

        var CGR = {
            width : DomWidth+'px',
            height : IfWidth? (height*bili+5)+'px' : (parseInt(height)+5)+'px',
            videoWidth : IfWidth? DomWidth+'px' : width+'px',
            videoHeight : IfWidth? height*bili+'px' :height+'px'
        };

        var VideoFrome = document.createElement("video");
        var VideoDiv = document.createElement("div");
        var VideoSource = document.createElement("source");

        VideoDiv.style.backgroundColor = "#000";
        VideoDiv.style.width = CGR.width;
        VideoDiv.style.height = CGR.height;
        VideoDiv.setAttribute('video-div','videodiv');
        VideoDiv.style.position = "relative";


        VideoFrome.style.width = CGR.videoWidth;
        VideoFrome.style.height = CGR.videoHeight;
        VideoFrome.style.zIndex = '8';
        VideoFrome.style.position = 'absolute';
        VideoFrome.setAttribute('video-frome','webvideofuncfrome');

        VideoFrome.setAttribute('oncontextmenu','return false');
        VideoFrome.setAttribute('preload','auto');
        VideoFrome.setAttribute('x-webkit-airplay','true');
        VideoFrome.setAttribute('webkit-playsinline','true');
        VideoFrome.setAttribute('poster',image);

        VideoSource.src = src;
        VideoSource.type = "video/mp4";

        if(!IfWidth) {
            VideoFrome.style.position = "absolute";
            VideoFrome.style.left = "50%";
            VideoFrome.style.webkitTransform = "translateX(-50%)";
        }

        VideoFrome.appendChild(VideoSource);
        VideoDiv.appendChild(VideoFrome);
        DomId.appendChild(VideoDiv);
    };
    //开始暂停
    function twoswitch(id){

        var VideoFrome =  selectors(id,'video-frome');
        var VideoDiv =  selectors(id,'video-div');

        var start = document.createElement("div");
        var suspend = document.createElement("div");
        var startsuspendfrome = document.createElement("div");


        startsuspendfrome.style.position = "absolute";
        startsuspendfrome.style.top = "50%";
        startsuspendfrome.style.left = "50%";
        startsuspendfrome.style.webkitTransform = "translate(-50%,-50%)";
        startsuspendfrome.style.zIndex = '9999';

        start.innerHTML=startbutton.join("");
        start.setAttribute('video-start','start');

        suspend.style.display = "none";
        suspend.innerHTML = suspendbutton.join("");
        suspend.setAttribute('video-suspend','suspend');


        startsuspendfrome.appendChild(start);
        startsuspendfrome.appendChild(suspend);
        VideoDiv.appendChild(startsuspendfrome);

        start.addEventListener('mousedown',function(){
            VideoFrome.play();

            this.style.display = "none";

            progressFlag = setInterval(passone.pass(id),500);

            funcpass = setInterval(func.passtwo(id),500);

            functotal();

            var Videofuncdom = selectors(id,'video-funcdom');

            Videofuncdom.style.zIndex = "1";

        },false);

        suspend.addEventListener("mousedown",function(){
            VideoFrome.pause();

            this.style.display = "none";
            start.style.display = "block";

            clearInterval(progressFlag);
            clearInterval(funcpass);
            clearTimeout(functime);

            var Videofuncdom = selectors(id,'video-funcdom');

            Videofuncdom.style.zIndex = "10";

            settimestart = 1;
        },false);

        VideoFrome.addEventListener("mousedown",function(){

            if(VideoFrome.paused){
                start.style.display = "block";
            }else{
                suspend.style.display = "block";

                var Videofuncdom = selectors(id,'video-funcdom');

                Videofuncdom.style.zIndex = "10";

                if(settimestart){
                    settimestart = 0;
                    functime = setTimeout(function(){
                        settimestart = 1;
                        suspend.style.display = "none";
                        Videofuncdom.style.zIndex = "1";
                    },5000);
                }
            }

        },false);
    };
    //进度条
    var passone = {
        //dom结构
        dom:function(id){
            var VideoDiv =  selectors(id,'video-div');
            var within = document.createElement("div");
            var abroad = document.createElement("div");

            within.setAttribute("video-within","within");
            abroad.setAttribute("video-abroad","abroad");

            within.style.height = '5px';
            within.style.width = '100%';
            within.style.backgroundColor = '#f1f1f1';
            within.style.position = 'absolute';
            within.style.bottom = '0px';
            within.style.left = '0px';
            within.style.zIndex = '9';

            abroad.style.height = '5px';
            abroad.style.backgroundColor = '#e77c8e';
            abroad.style.width = '0px';

            within.appendChild(abroad);

            VideoDiv.appendChild(within);
        },
        //进度条
        pass : function(id){
            var VideoFrome =  selectors(id,'video-frome');
            var Videowithin = selectors(id,'video-within');
            var Videostart = selectors(id,'video-start');
            var abroad = selectors(id,'video-abroad');

            var setInt = function(){
                var percent = (VideoFrome.currentTime / VideoFrome.duration);
                abroad.style.width = parseInt(percent * (Videowithin.offsetWidth))+'px';
                if (VideoFrome.ended){
                    clearInterval(progressFlag);
                    Videostart.style.display = 'block';
                    var Videofuncdom = selectors(id,'video-funcdom');

                    Videofuncdom.style.zIndex = "10";
                    Videofuncdom.style.display = "block";
                }
            };
            return setInt;
        }
    };
    //功能条
    var func = {
        //背景
        dom : function(id){
            var Videofrome = selectors(id,'video-div');

            var domfrome = document.createElement('div');

            domfrome.style.height = '11%';
            domfrome.style.width = '100%';
            domfrome.style.bottom = '0px';
            domfrome.style.left = '0px';
            domfrome.style.backgroundColor = 'rgba(0,0,0,0.6)';
            domfrome.style.position = 'absolute';
            domfrome.style.zIndex = '10';

            domfrome.setAttribute('video-funcdom','funcdom');

            Videofrome.appendChild(domfrome);

            func.total(id);
            func.passtwo(id);
            func.currenttime(id);
            // func.fullScreen(id);
        },
        //总时长
        currenttime : function(id){
            var Videofrome = selectors(id,'video-frome');
            var Videofunc = selectors(id,'video-funcdom');
            var currenttimediv = document.createElement('span');
            var fen = null;
            var miao = null;

            currenttimediv.style.size = '12px';
            currenttimediv.style.color = '#fff';
            currenttimediv.style.display = 'inline-block';
            currenttimediv.style.height = '100%';
            currenttimediv.style.float = 'left';
            currenttimediv.style.marginLeft = '2%';

            var currenttimedaddevent = function () {

                fen = parseInt(Videofrome.duration/60)<10 ? "0"+parseInt(Videofrome.duration/60).toString():parseInt(Videofrome.duration/60);

                miao = parseInt(Videofrome.duration%60)<10 ? "0"+parseInt(Videofrome.duration%60).toString():parseInt(Videofrome.duration%60);

                currenttimediv.style.lineHeight = Videofunc.offsetHeight+2+'px';

                currenttimediv.innerText = fen+':'+miao;

                Videofunc.appendChild(currenttimediv);

                Videofrome.removeEventListener("loadedmetadata",currenttimedaddevent, false);
            };
            Videofrome.addEventListener("loadedmetadata",currenttimedaddevent, false);
        },
        //当前时长
        total : function(id){
            var Videofrome = selectors(id,'video-frome');
            var Videofunc = selectors(id,'video-funcdom');
            var totaldiv = document.createElement('span');
            var fen = null;
            var miao = null;

            totaldiv.style.size = '12px';
            totaldiv.style.color = '#fff';
            totaldiv.style.display = 'inline-block';
            totaldiv.style.height = '100%';
            totaldiv.style.marginLeft = '3%';
            totaldiv.style.float = 'left';

            var totaldaddevent = function () {

                totaldiv.style.lineHeight = Videofunc.offsetHeight+2+'px';

                fen = parseInt(Videofrome.currentTime/60)<10 ? "0"+(parseInt(Videofrome.currentTime/60).toString()):parseInt(Videofrome.currentTime/60);

                miao = parseInt(Videofrome.currentTime%60)< 10 ? "0"+parseInt(Videofrome.currentTime%60).toString():parseInt(Videofrome.currentTime%60);


                totaldiv.innerText = fen+':'+miao;

                Videofunc.appendChild(totaldiv);

                Videofrome.removeEventListener("loadedmetadata",totaldaddevent, false);
            };
            Videofrome.addEventListener("loadedmetadata",totaldaddevent, false);


            functotal = function() {
                var funcsetInt = setInterval(function () {
                    fen = parseInt(Videofrome.currentTime/60)<10 ? "0"+parseInt(Videofrome.currentTime/60).toString():parseInt(Videofrome.currentTime/60);

                    miao = parseInt(Videofrome.currentTime%60)< 10 ? "0"+parseInt(Videofrome.currentTime%60).toString():parseInt(Videofrome.currentTime%60);

                    totaldiv.innerText = fen + ':' + miao;
                    if(Videofrome.paused) clearInterval(funcsetInt);
                }, 500);
            };

        },
        //进度条
        passtwo : function(id){
            var Videofrome = selectors(id,'video-frome');
            var Videofunc = selectors(id,'video-funcdom');
            var passtwodiv = document.createElement('span');
            var passtwostrip = document.createElement('span');
            var passtwopass = document.createElement('span');
            var passtwobutton = document.createElement('span');

            passtwodiv.style.width = '60%';
            passtwodiv.style.height = '100%';
            passtwodiv.style.display = 'inline-block';
            passtwodiv.style.float = 'left';
            passtwodiv.style.position = 'relative';
            passtwodiv.style.marginLeft = '10px';
            passtwodiv.setAttribute('video-passtwo','passtwo');

            passtwostrip.style.display = "block";
            passtwostrip.style.width = "100%";
            passtwostrip.style.height = "3px";
            passtwostrip.style.backgroundColor = "#D8D8D8";
            passtwostrip.style.position = 'absolute';
            passtwostrip.style.top = '50%';
            passtwostrip.style.left = '50%';
            passtwostrip.style.webkitTransform = "translate(-50%,-50%)";
            passtwostrip.setAttribute('video-passtwostrip','passtwostrip');

            passtwopass.style.display = 'block';
            passtwopass.style.height = '100%';
            passtwopass.style.width = '0';
            passtwopass.style.backgroundColor = '#ED728D';
            passtwopass.setAttribute('video-passtwopass','passtwopass');

            passtwobutton.style.display = 'block';
            passtwobutton.style.position = 'absolute';
            passtwobutton.style.width = '8px';
            passtwobutton.style.height = '8px';
            passtwobutton.style.borderRadius = '50%';
            passtwobutton.style.backgroundColor = "#ED728D";
            passtwobutton.style.zIndex = '2';
            passtwobutton.style.top = '50%';
            passtwobutton.style.left = '-4px';
            passtwobutton.style.webkitTransform = "translate(0%,-50%)";
            passtwobutton.setAttribute('video-passtwobutton','passtwobutton');

            passtwostrip.appendChild(passtwopass);
            passtwodiv.appendChild(passtwobutton);
            passtwodiv.appendChild(passtwostrip);


            function enhanceVideoSeek(e){
                var left = parseInt(this.getBoundingClientRect().left);
                var length = e.pageX - left;
                var percent = length / this.offsetWidth;
                passtwopass.style.width = parseInt(percent * (this.offsetWidth))+"px";
                passtwobutton.style.left = parseInt(percent * (this.offsetWidth)-4)+"px";

                Videofrome.currentTime = percent * Videofrome.duration;
            }

            passtwodiv.addEventListener('mousedown',enhanceVideoSeek,false);

            var passtwoaddevent = function () {

                Videofunc.appendChild(passtwodiv);

                Videofrome.removeEventListener("loadedmetadata",passtwoaddevent, false);
            };
            Videofrome.addEventListener("loadedmetadata",passtwoaddevent, false);

            var passtwopassevent = function(){
                var percent = (Videofrome.currentTime / Videofrome.duration);
                var passtwostripwidth = selectors(id,'video-passtwostrip').offsetWidth;
                var passtwopasswidth = selectors(id,'video-passtwopass');
                var passtwoapssbotton = selectors(id,'passtwobutton');
                passtwopasswidth.style.width = parseInt(percent * (passtwostripwidth))+'px';
                passtwoapssbotton.style.left =  parseInt(percent * (passtwostripwidth)-4)+'px';
                if (Videofrome.ended){
                    clearInterval(progressFlag);
                }
            };

            return passtwopassevent;
        },
        //全屏、退出全屏
        fullScreen : function(id){
            var Videodiv = selectors(id,'video-div');
            var Videofunc = selectors(id,'video-funcdom');
            var Videofrome = selectors(id,'video-frome');

            var screendom = document.createElement('span');

            screendom.style.display = 'inline-block';
            screendom.style.float = 'right';
            screendom.style.marginRight = '3%';
            screendom.style.width = '13px';
            screendom.style.height = '100%';
            screendom.innerHTML = screen.join("");

            screendom.addEventListener('click',function(){
                Videofrome.webkitRequestFullscreen();
            },false);

            var screenaddevent = function () {

                screendom.style.lineHeight = Videofunc.offsetHeight+2+'px';

                Videofunc.appendChild(screendom);



                Videofrome.removeEventListener("loadedmetadata",screenaddevent, false);
            };
            Videofrome.addEventListener("loadedmetadata",screenaddevent, false);
        }
    };
    /*----- 公共方法end -----*/

    webvideo.prototype._init = function() {
        this._iphonedom();
    };

    webvideo.prototype._iphonedom = function() {
        frome(this.Vid,this.Vwidth,this.Vheight,this.Vsrc,this.Vimage);
        twoswitch(this.Vid);
        passone.dom(this.Vid);
        func.dom(this.Vid);
    };
    return webvideo;
})();