<%@ Page Language="C#" AutoEventWireup="true" Inherits="Kesion.NET.WebSite.Plus.Yun.Yuncs" Codebehind="Yuncs.aspx.cs" %>
<%@ Import Namespace="Kesion.Publics" %>
<!doctype html  >
<head  >
    <meta charset="UTF-8">
    <title>Demo</title>
	<link href="/admin/images/style.css" rel="stylesheet" type="text/css" />
	<script src="/KS_Inc/Jquery.js" type="text/javascript"></script>
    	<script src="/KS_Inc/Kesion.Common.js" type="text/javascript"></script>
	<style>
	.file {position: relative; width:80px;overflow: hidden;background:#b0b9bf;color: #fff;text-decoration: none;text-indent: 0;line-height: 34px;vertical-align: middle;margin-right: 10px;border-radius: 3px; text-align:center;}
    .file input {position: absolute;font-size: 100px;right: 0;top: 0;opacity: 0;}
    .file:hover {background: #13c0b1;}
	.topBtn{ margin-bottom:20px; margin-top:20px;}
	.jdt{ width:328px; height:8px; background:#f0f0f0; border-radius:10px;}
	.jdt .jdtinner{ background:#13c0b1; height:8px; border-radius:10px; position:relative;}
	.jd-data{ position:absolute; bottom:-22px;right:-10px;}

	</style>
</head>

<body  >

    <asp:Panel ID="polyv" runat="server">

        <script type="text/javascript" src="/ks_inc/webuploader/js/webuploader.min.js"></script>
        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="/ks_inc/webuploader/css/webuploader.css">


        <div class="btns">
            <div id="uploader" class="wu-example">
                <div id="thelist" class="uploader-list"></div>
                <table>
                    <tr>
                        <td width="100" style="padding: 0;">
                            <div id="picker">选择文件</div>
                        </td>
                        <td style="padding: 0;">
                            <button id="ctlBtn" class="btn btn-default">开始上传</button></td>
                    </tr>
                </table>
            </div>
        </div>

        <script>
            // 文件上传
            jQuery(function () {
                var $ = jQuery,
                    $list = $('#thelist'),
                    $btn = $('#ctlBtn'),
                    state = 'pending',
                    uploader;
                var ispost = 0;
                uploader = WebUploader.create({
                    // swf文件路径
                    swf: '/ks_inc/webuploader/js/Uploader.swf',
                    server: 'https://v.polyv.net/uc/services/rest?method=uploadfile',
                    //fileVal {Object} [可选] [默认值：'file'] 设置文件上传域的name
                    fileVal: 'Filedata',
                    //formData {Object} [可选] [默认值：{}] 文件上传请求的参数表，每次发送都会发送此对象中的参数。
                    formData: { "writetoken":"<%=accessKeyId%>" },
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.指定选择文件的按钮容器，不指定则不创建按钮。
                pick: '#picker',
                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                resize: false

            });
            uploader.on('uploadBeforeSend', function (block, data) {
                var title = $('#ctl00_KSContent_TxtName', parent.document).val();
                var tag = $('#ctl00_KSContent_ClassName', parent.document).val();
                var desc = $('#ctl00_KSContent_ClassName', parent.document).val();
                var cataid = "0";

                if (cataid == '0') {
                    cataid = '1';
                }
                if (title == undefined) {
                    title = $('#ctl00_KSContent_ClassName', parent.document).val();
                }
                if (title == undefined) {
                    title = $('#TxtName', parent.document).val();
                }
                data.cataid = cataid;
                data.JSONRPC = '{"title": "' + title + '", "tag": "' + tag + '", "desc": "' + desc + '"}';


            });

            // 当有文件添加进来的时候
            uploader.on('fileQueued', function (file, data) {
                $list.append('<div id="' + file.id + '" class="item">' +
                    '<h4 class="info">' + file.name + '</h4>' +
                    '<p class="state" style="display:none">等待上传...</p>' +
                    '</div>');

                //return;
                //触发上传
                if (state === 'uploading') {
                    // uploader.stop();
                } else {
                    //  uploader.upload();
                }
            });

            // 文件上传过程中创建进度条实时显示。
            uploader.on('uploadProgress', function (file, percentage) {
                var $li = $('#' + file.id),
                    $percent = $li.find('.progress .progress-bar');

                // 避免重复创建
                if (!$percent.length) {
                    $percent = $('<div class="progress progress-striped active">' +
                        '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                        '</div>' +
                        '</div>').appendTo($li).find('.progress-bar');
                }
                $li.find('p.state').text('上传中');

                $percent.css('width', percentage * 100 + '%');
            });
            uploader.on('uploadAccept', function (file, response) {
                //  console.log(response);
                $('#' + file.id).find('p.state').text('已上传');
            });
            uploader.on('uploadSuccess', function (file, response) {
                //  $("#tipss").hide();
                //console.log(response);
                var obj = eval(response);
                if (obj.error == '16') {
                    alert("空间已满");
                }
                else if (obj.error == '1') {
                    alert("找不到writetoken关联的user");
                }
                else if (obj.error == '2') {
                    alert("文件为空或者writetoken为空");
                }
                else if (obj.error == '3') {
                    alert("提交的json名字JSONRPC为null");
                }
                else if (obj.error == '4') {
                    alert("提交文件格式不正确");
                }
                else if (obj.error == '5') {
                    alert("readtoken为空");
                }
                else if (obj.error == '6') {
                    alert("分页输入出错");
                }
                else if (obj.error == '7') {
                    alert("vid不能为空");
                }
                else if (obj.error == '8') {
                    alert("找不到方法名");
                }
                else if (obj.error == '10') {
                    alert("userid不能为空");
                }
                else if (obj.error == '11') {
                    alert("上传目录为空");
                }
                else if (obj.error == '12') {
                    alert("远程URL文件不能访问");
                }
                else if (obj.error == '13') {
                    alert("远程视频文件格式无法识别");
                }
                else if (obj.error == '15') {
                    alert("参数异常");
                }
                else if (obj.error == '17') {
                    alert("用户无接口权限");
                }
                else if (obj.error == '18') {
                    alert("标题重复");
                }
                else if (obj.error == '19') {
                    alert("标题为空");
                }
                else if (obj.error == '20') {
                    alert("播放列表不存在");
                }
                else if (obj.error == '21') {
                    alert("参数错误");
                }
                else if (obj.error == '22') {
                    alert("参数签名错误");
                }
                else if (obj.error == '23') {
                    alert("视频不存在");
                }
                else if (obj.error == '24') {
                    alert("时间戳已过期");
                }
                else {
                    //栏目视频id参数存储
                    if ('<%=KSCMS.S("field")%>' != '') {
                        jQuery("#<%=KSCMS.S("field")%>", parent.document).val(obj.data[0].vid);
                    }
                    jQuery("#TextAddress", parent.document).val(obj.data[0].vid)
                    $.ajax({
                        url: "/Plus/course/AddYunVideos.aspx?from=<%=from%>&action=getadd&VideoType=<%=KSCMS.S("VideoType")%>&vid=" + obj.data[0].vid + "&cataid=" + obj.data[0].cataid + "&firstimage=" + obj.data[0].first_image + "&desc=" + obj.data[0].context + "&title=" + obj.data[0].title + "&tag=" + obj.data[0].tag + "&ptime=" + obj.data[0].ptime + "&status=" + obj.data[0].status + "&duration=" + obj.data[0].duration + "&filesize=" + obj.data[0].filesize + "&times=" + obj.data[0].times + "&swflink=" + obj.data[0].swf_link + "&rnd=" + Math.random(),
                            context: document.body,
                            type: "get",
                            success: function (data) {
                                if (data == 'ok') {
                                    // KesionJS.Alert("抱歉，添加视频已经上限啦");
                                }
                                else if (data == 'have') {
                                    KesionJS.Alert("抱歉，添加视频已经上限啦");
                                }
                            }
                        });

                    }

                    $('#' + file.id).find('p.state').text('已上传');
                });

                uploader.on('uploadError', function (file) {
                    $('#' + file.id).find('p.state').text('上传出错');
                });

                uploader.on('uploadComplete', function (file) {
                    $('#' + file.id).find('.progress').fadeOut();
                });

                uploader.on('all', function (type) {
                    if (type === 'startUpload') {
                        state = 'uploading';
                    } else if (type === 'stopUpload') {
                        state = 'paused';
                    } else if (type === 'uploadFinished') {
                        state = 'done';
                    }

                    if (state === 'uploading') {
                        $btn.text('暂停上传');
                    } else {
                        $btn.text('开始上传');
                    }

                });

                $btn.on('click', function (data) {
                    var title = $('#ctl00_KSContent_TxtName', parent.document).val();
                    if (title == undefined) {
                        title = $('#ctl00_KSContent_ClassName', parent.document).val();
                    }
                    if (title == undefined) {
                        title = $('#TxtName', parent.document).val();
                    }
                    if (title == '' || title == undefined) {
                        alert('上传前请先录入课程名称!');
                        return false;
                    }

                    if (state === 'uploading') {
                        uploader.stop();
                    } else {
                        uploader.upload();
                    }

                });
            });




        </script>


    </asp:Panel>

    <asp:Panel ID="aliyun" runat="server">

        <script src="/KS_INC/aliyun/aliyun-sdk.min.js"></script>
        <script src="/KS_INC/aliyun/vod-sdk-upload-1.0.6.min.js"></script>

        <input type="hidden" id="uploadAuth" size="20" value="">
        <input type="hidden" id="uploadAddress" size="20" value="">
        <input type="hidden" id="accessKeyId" size="20" value="">
        <input type="hidden" id="accessKeySecret" size="40" value="">
        <input type="hidden" id="secretToken" size="40" value="">
        <input type="hidden" id="expireTime" size="20" value="">
        <input type="hidden" id="endpoint" size="40" value="http://oss-cn-hangzhou.aliyuncs.com">
        <input type="hidden" id="bucket" size="20" value="testbucket">
        <input type="hidden" id="objectPre" size="20" value="uploadtest/">
        <input type="hidden" id="vid" size="60" value="">

        <div class="clearfix topBtn" style="padding: 0px; margin: 0px;">
            <div class="fl file">
                <input type="file" name="file" id="files" multiple />点击上传</div>
            <div class="tips" style="margin-top: 30px;">上传的文件为.mp4,.flv,.avi,.mp3格式</div>
            <button type="button" onclick="startabc()" class="fl button" style="display: none">开始上传</button>
            <div class="jdt" id="jid" style="margin-top: 6px; display: none"></div>
        </div>


        <select multiple="multiple" id="textarea" style="position: relative; width: 100%; height: 100px; vertical-align: top; border: 1px solid #cccccc; display: none"></select>

        <!--<div style="margin-top:20px;">
        <button type="button" onClick="clearLog()" class="button">清日志</button>
    </div>-->

        <script>

            var uploader;
            function startabc() {
                var files = document.getElementById("files").files;
                data = { "filename": (files[0].name), "filesize": (files[0].size), "&rnd=": (Math.random()) };
                var url = '/plus/yun/yuncs.aspx?a=uploadAuth&from=<%=from%>';
                $.ajax({
                    type: "post",
                    url: url,
                    data: data,
                    success: function (data) {

                        if (data != null) {
                            var d = data.split('|');
                            $('#uploadAddress').val(d[1]);
                            $('#uploadAuth').val(d[0]);
                            $('#vid').val(d[2]);
                            start();
                        } else {
                            alert("暂时无法上传视频请联系服务商");
                        }
                    }
                });
            }

            window.onload = new function () {
                if (document.getElementById("files").files == undefined) {
                    alert("该上传需要IE9及以上浏览器");
                }
                uploader = new VODUpload({
                    // 文件上传失败
                    'onUploadFailed': function (uploadInfo, code, message) {
                        // log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
                    },
                    // 文件上传完成
                    'onUploadSucceed': function (uploadInfo) {
                        var vid = jQuery("#vid").val();
                        var files = document.getElementById("files").files;
                        $("#jid").hide();
                        $.ajax({
                            url: "/Plus/course/AddYunVideos.aspx?from=<%=from%>&action=getadd&VideoType=10&vid=" + vid + "&title=" + files[0].name + "&status=1&filesize=" + files[0].size + "&rnd=" + Math.random(),
                    context: document.body,
                    type: "get",
                    success: function (data) {
                        if (data == 'ok') {
                            if ('<%=KSCMS.S("field")%>' != '') {//有这个参数field
                                  if (top.frames['main'] == undefined) {
                                      if ('<%=KSCMS.S("field")%>' != '') {
                                          $('#<%=KSCMS.S("field")%>', window.parent.document).val(vid);
                                      }
                                      $('#TextAddress', window.parent.document).val(vid);
                                  } else {
                                      if ('<%=KSCMS.S("field")%>' != '') {
                                          $(top.frames["main"].document.getElementById("<%=KSCMS.S("field")%>")).val(vid);
                                      }
                                      $(top.frames["main"].document.getElementById("TextAddress")).val(vid);
                                  }
                              } else {//没有这个参数field
                                  if (top.frames['main'].box1 == undefined) {
                                      if ('<%=KSCMS.S("field")%>' != '') {
                                          $('#<%=KSCMS.S("field")%>', window.parent.document).val(vid);
                                      }
                                      $('#TextAddress', window.parent.document).val(vid);
                                      top.box1.close();
                                  } else {
                                      if ('<%=KSCMS.S("field")%>' != '') {
                                          $(top.frames["main"].document.getElementById("<%=KSCMS.S("field")%>")).val(vid);
                                            }
                                            $(top.frames["main"].document.getElementById("TextAddress")).val(vid);
                                            top.frames['main'].box1.close();
                                        }
                                    }

                                }
                                else if (data == 'have') {
                                    top.alert("抱歉，添加视频已经上限啦");
                                }
                            }
                        });


                        // log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
                    },
                    // 文件上传进度			

                    'onUploadProgress': function (uploadInfo, totalSize, uploadedSize) {
                        document.getElementById("jid").innerHTML = '<div class="jdtinner" style="width:' + Math.ceil(uploadedSize * 100 / totalSize) + '%;text-align:right;color:#fff;font-size:10px;">' + Math.ceil(uploadedSize * 100 / totalSize) + '%</div>';
                        // log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(uploadedSize * 100 / totalSize) + "%");
                    },
                    // STS临时账号会过期，过期时触发函数
                    'onUploadTokenExpired': function () {
                        log("onUploadTokenExpired");
                        if (isVodMode()) {
                            // 实现时，从新获取UploadAuth
                            // uploader.resumeUploadWithAuth(uploadAuth);
                        } else if (isSTSMode()) {
                            // 实现时，从新获取STS临时账号用于恢复上传
                            // uploader.resumeUploadWithToken(accessKeyId, accessKeySecret, secretToken, expireTime);
                        }
                    },
                    // 开始上传
                    'onUploadstarted': function (uploadInfo) {
                        jQuery("#jid").show();
                        jQuery("#textarea").hide();

                        if (isVodMode()) {
                            var uploadAuth = document.getElementById("uploadAuth").value;
                            var uploadAddress = document.getElementById("uploadAddress").value;
                            uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress);
                        }
                        log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
                    }
                });

                var accessKeyId = document.getElementById("accessKeyId").value;
                var accessKeySecret = document.getElementById("accessKeySecret").value;
                var secretToken = document.getElementById("secretToken").value;
                var expireTime = document.getElementById("expireTime").value;

                if (isVodMode()) {
                    // 点播上传。每次上传都是独立的鉴权，所以初始化时，不需要设置鉴权
                    uploader.init();
                } else if (isSTSMode()) {
                    // OSS直接上传:STS方式，安全但是较为复杂，建议生产环境下使用。
                    // 临时账号过期时，在onUploadTokenExpired事件中，用resumeWithToken更新临时账号，上传会续传。
                    uploader.init(accessKeyId, accessKeySecret, secretToken, expireTime);
                } else {
                    // OSS直接上传:AK方式，简单但是不够安全，建议测试环境下使用。
                    uploader.init(accessKeyId, accessKeySecret);
                }
            };

            document.getElementById("files")
                .addEventListener('change', function (event) {
                    var endpoint = document.getElementById("endpoint").value;
                    var bucket = document.getElementById("bucket").value;
                    var objectPre = document.getElementById("objectPre").value;
                    var userData;
                    if (isVodMode()) {
                        userData = '{"Vod":{"UserData":"{"IsShowWaterMark":"false","Priority":"7"}"}}';
                    } else {
                        userData = '{"Vod":{"Title":"this is title.我是标题","Description":"this is desc.我是描述","CateId":"19",\
                "Tags":"tag1,tag2,标签3","UserData":"user data"}}';
                    }

                    for (var i = 0; i < event.target.files.length; i++) {
                        //   log("add file: " + event.target.files[i].name);

                        if (isVodMode()) {
                            // 点播上传。每次上传都是独立的OSS object，所以添加文件时，不需要设置OSS的属性
                            uploader.addFile(event.target.files[i], null, null, null, userData);
                        } else {
                            uploader.addFile(event.target.files[i], endpoint, bucket, objectPre + event.target.files[i].name, userData);
                        }

                    }
                    setTimeout("startabc()", 500);
                });

            var textarea = document.getElementById("textarea");

            function start() {
                // log("start upload.");
                uploader.startUpload();
            }

            function stop() {
                // log("stop upload.");
                uploader.stopUpload();
            }

            function resumeWithToken() {
                // log("resume upload with token.");
                var uploadAuth = document.getElementById("uploadAuth").value;

                var accessKeyId = document.getElementById("accessKeyId").value;
                var accessKeySecret = document.getElementById("accessKeySecret").value;
                var secretToken = document.getElementById("secretToken").value;
                var expireTime = document.getElementById("expireTime").value;

                if (isVodMode()) {
                    uploader.resumeUploadWithAuth(uploadAuth);
                } else if (isSTSMode()) {
                    uploader.resumeUploadWithToken(accessKeyId, accessKeySecret, secretToken, expireTime);
                }
            }

            function clearList() {
                log("clean upload list.");
                uploader.cleanList();
            }

            function getList() {
                log("get upload list.");
                var list = uploader.listFiles();
                for (var i = 0; i < list.length; i++) {
                    log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
                }
            }

            function deleteFile() {
                if (document.getElementById("deleteIndex").value) {
                    var index = document.getElementById("deleteIndex").value
                    log("delete file index:" + index);
                    uploader.deleteFile(index);
                }
            }

            function cancelFile() {
                if (document.getElementById("cancelIndex").value) {
                    var index = document.getElementById("cancelIndex").value
                    log("cancel file index:" + index);
                    uploader.cancelFile(index);
                }
            }

            function resumeFile() {
                if (document.getElementById("resumeIndex").value) {
                    var index = document.getElementById("resumeIndex").value
                    log("resume file index:" + index);
                    uploader.resumeFile(index);
                }
            }

            function clearLog() {
                textarea.options.length = 0;
            }

            function log(value) {
                if (!value) {
                    return;
                }

                var len = textarea.options.length;
                if (len > 0 && textarea.options[len - 1].value.substring(0, 40) == value.substring(0, 40)) {
                    textarea.remove(len - 1);
                } else if (len > 25) {
                    textarea.remove(0);
                }

                var option = document.createElement("option");
                option.value = value, option.innerHTML = value;
                textarea.appendChild(option);
            }

            function isVodMode() {
                var uploadAuth = document.getElementById("uploadAuth").value;
                return (uploadAuth && uploadAuth.length > 0);
            }

            function isSTSMode() {
                var secretToken = document.getElementById("secretToken").value;
                var expireTime = document.getElementById("expireTime").value;
                if (!isVodMode()) {
                    if (secretToken && secretToken.length > 0 && expireTime && expireTime.length > 0) {
                        return true;
                    }
                }
                return false;
            }
        </script>
    </asp:Panel>

    <asp:Panel ID="baiduyun" runat="server">

        <!--[if lt IE 8]><script src="../bower_components/json3/lib/json3.min.js"></script><![endif]-->
        <!--[if lt IE 9]><script src="../bower_components/js-polyfills/es5.js"></script><![endif]-->
        <!--[if lt IE 10]><script src="../bower_components/moxie/bin/js/moxie.min.js"></script><![endif]-->
        <script src="/ks_inc/baiduyun/bower_components/jquery/dist/jquery.js"></script>
        <script src="/ks_inc/baiduyun/bower_components/humanize/humanize.js"></script>
        <script src="/ks_inc/baiduyun/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
        <script src="/ks_inc/baiduyun/bower_components/bce-bos-uploader/bce-bos-uploader.bundle.min.js"></script>

        <div class="clearfix topBtn">
            <div class="fl file">
                <input type="file" name="file" id="file" multiple />点击上传</div>
            <div class="tips" style="margin-top: 30px;">上传的文件为.mp4,.flv,.avi,.mp3格式</div>
            <button type="submit" class="btn btn-success" disabled style="display: none">开始上传</button>
        </div>
        <div class="jdt" id="jspeed" style="display: none">
            <div class="jdtinner" style="width: 0%;">
                <div class="jd-data">0%</div>
            </div>
        </div>
        <span class="network-speed"></span>


        <script src="/ks_inc/baiduyun/utils.js"></script>
        <script>

            var AK = getQuery('ak', '<%=accessKeyId%>');
            var SK = getQuery('sk', '<%=secretAccessKey%>');

            // 如果使用临时 AK 和 SK，必须设置 SESSION_TOKEN 和 UPTOKEN_URL 这两个参数
            // **缺一不可**
            var SESSION_TOKEN = null;
            var UPTOKEN_URL = 'http://localhost.baidu.com:7788/ack';

            var VOD_ENDPOINT = getQuery('vod.endpoint', 'http://vod.baidubce.com');
            var VOD_BUCKET = getQuery('vod.bucket', 'bce-bos-uploader');
            var VOD_EXTS = 'avi,mp4,flv,rm,rmvb,webm'.split(',');

            var BOS_ENDPOINT = getQuery('bos.endpoint', 'http://bj.bcebos.com');
            var BOS_BUCKET = 'bce-bos-uploader';

            var DOC_ENDPOINT = getQuery('doc.endpoint', 'http://doc.baidubce.com');
            var DOC_BUCKET = getQuery('doc.bucket', 'bce-bos-uploader');
            var DOC_EXTS = 'txt,pdf,doc,docx,ppt,pptx,xls,xlsx'.split(',');
            var DOC_MAX_SIZE = baidubce.utils.parseSize('100Mb');   // 文档最大 100Mb

            var CHUNK_SIZE = '1m';

            var doc = new baidubce.sdk.DocClient.Document({
                endpoint: DOC_ENDPOINT,
                credentials: { ak: AK, sk: SK },
                sessionToken: SESSION_TOKEN
            });

            var vod = new baidubce.sdk.VodClient.Media({
                endpoint: VOD_ENDPOINT,
                credentials: { ak: AK, sk: SK },
                sessionToken: SESSION_TOKEN
            });

            function uuid() {
                var value = Math.random() * Math.pow(2, 60);
                return parseInt(value).toString(36);
            }

            function getLSIndex(type, file) {
                var index = [type, AK, file.name, file.size, CHUNK_SIZE].join('&');
                return index;
            }

            function appendLS(key, item) {
                var value = [];
                try {
                    value = JSON.parse(localStorage.getItem(key) || '[]');
                }
                catch (ex) {
                }

                value.push(item);
                localStorage.setItem(key, JSON.stringify(value));
            }


            function getUUIDFile(type, file) {
                var ext = getFileExtension(file);

                return type + '-' + uuid() + (ext ? '.' + ext : '');
            }

            function getFileExtension(file) {
                var chunks = file.name.split('.');
                var ext = chunks.length > 1 ? chunks.pop() : '';

                return ext;
            }

            function finVodKey(file, info) {
                var localKey = getLSIndex('vod', file);
                localStorage.removeItem(localKey);

                var options = {
                    description: '测试文件'
                };
                var ext = getFileExtension(file);
                if (ext) {
                    options.sourceExtension = ext;
                }

                vod.setMediaId(file.__mediaId).process(file.name, options)
                    .then(function () {

                        var row = getRowById(file.__id);

                        row.setMediaId(file.__mediaId);

                        appendLS('vods', file.__mediaId);
                    });
            }

            function getVodKey(file) {
                var localKey = getLSIndex('vod', file);
                var localValue = localStorage.getItem(localKey);
                if (!localValue) {
                    return vod.apply().then(function (response) {
                        var mediaId = response.body.mediaId;
                        var bucket = response.body.sourceBucket;
                        var key = response.body.sourceKey;
                        localStorage.setItem(localKey, JSON.stringify(response.body));
                        file.__mediaId = mediaId;
                        file.__object = key;
                        file.__done = finVodKey;
                        return {
                            bucket: bucket,
                            key: key
                        };
                    });
                }
                else {
                    localValue = JSON.parse(localValue);
                    file.__mediaId = localValue.mediaId;
                    file.__object = localValue.sourceKey;
                    file.__done = finVodKey;
                    return {
                        bucket: localValue.sourceBucket,
                        key: localValue.sourceKey
                    };
                }
            }

            function finDocKey(file, info) {
                var localKey = getLSIndex('doc', file);
                localStorage.removeItem(localKey);

                doc.createFromBos(DOC_BUCKET, file.__object, file.name)
                    .then(function (response) {
                        var documentId = response.body.documentId;
                        var row = getRowById(file.__id);
                        row.setMediaId(documentId);

                        appendLS('docs', documentId);
                    });
            }

            function getDocKey(file) {
                if (file.size > DOC_MAX_SIZE) {
                    // 如果文档超过了允许的体积，就直接上传到 BOS
                    return getBosKey(file);
                }

                var localKey = getLSIndex('doc', file);
                var localValue = localStorage.getItem(localKey) || getUUIDFile('doc', file);
                localStorage.setItem(localKey, localValue);

                file.__target = 'doc';
                file.__object = 'source/' + localValue;
                file.__done = finDocKey;

                return {
                    bucket: DOC_BUCKET,
                    key: file.__object
                };
            }

            function finBosKey(file) {
                var localKey = getLSIndex('bos', file);
                localStorage.removeItem(localKey);

                var row = getRowById(file.__id);
                row.setMediaId(file.__bosId);
            }

            function getBosKey(file) {
                var localKey = getLSIndex('bos', file);
                var localValue = localStorage.getItem(localKey) || getUUIDFile('bos', file);
                localStorage.setItem(localKey, localValue);

                file.__bosId = localValue;
                file.__object = 'uuid/' + localValue;
                file.__done = finBosKey;

                return {
                    bucket: BOS_BUCKET,
                    key: file.__object
                };
            }

            function getKey(file) {
                var ext = getFileExtension(file);

                if (ext && VOD_EXTS.indexOf(ext) != -1) {
                    // 往视频服务上传
                    return getVodKey(file);
                }
                else if (ext && DOC_EXTS.indexOf(ext) != -1) {
                    // 往文档服务上传
                    return getDocKey(file);
                }
                else {
                    // 往BOS上传
                    return getBosKey(file);
                }
            }

            var uploader = new baidubce.bos.Uploader({
                browse_button: '#file',
                multi_selection: true,
                bos_endpoint: BOS_ENDPOINT,
                bos_bucket: BOS_BUCKET,
                bos_multipart_parallel: 5,
                chunk_size: '8mb',

                bos_ak: AK,
                bos_sk: SK,
                // uptoken: SESSION_TOKEN,

                // IE下面的 PostObject 请求不能用临时 ak 和 sk, 因此
                // 需要通过这个 URL 来动态计算 policy 签名
                // uptoken_url: UPTOKEN_URL,

                max_file_size: '50Gb',
                chunk_size: CHUNK_SIZE,
                flash_swf_url: '../bower_components/moxie/bin/flash/Moxie.swf',
                init: {
                    FilesFilter: function (_, files) {
                        // 添加更多的过滤规则，比如文件大小之类的
                    },
                    FilesAdded: function (_, files) {
                        //  FilesAdded(_, files);
                        // $('#form').get(0).reset();
                    },
                    BeforeUpload: function (_, file) {
                        file.__startTime = new Date().getTime();
                        var row = getRowById(file.__id);
                        row.setStatus('circle-arrow-up');
                    },
                    UploadProgress: function (_, file, progress, event) {
                        var row = getRowById(file.__id);
                        document.getElementById("jspeed").innerHTML = '<div class="jdtinner" style="width:' + (progress * 100).toFixed(2) + '%;"><div class="jd-data">' + (progress * 100).toFixed(2) + '%</div></div>';

                        row.setProgress(progress);
                    },
                    ObjectMetas: function (_, file) {
                        if (file.__target === 'doc') {
                            // 如果文档进入 Multipart Upload 的模式，必须手工设置 x-bce-meta-md5
                            // 如果是正常的 PutObject 模式，服务器会设置 ETag
                            // 另外，文档会被限制在 100Mb 以内，所以本地计算 md5 应该不会特别慢
                            return baidubce.utils.md5sum(file).then(function (md5) {
                                return {
                                    'x-bce-meta-md5': md5
                                };
                            });
                        }
                    },
                    Key: function (_, file) {
                        return getKey(file);
                    },
                    FileUploaded: function (_, file, info) {
                        var vid = file.__mediaId;
                        var filename = file.name;;
                        var size = file.size;

                        $.ajax({
                            url: "/Plus/course/AddYunVideos.aspx?from=<%=from%>&action=getadd&VideoType=12&vid=" + vid + "&title=" + filename + "&status=1&filesize=" + size + "&rnd=" + Math.random(),
                    context: document.body,
                    type: "get",
                    success: function (data) {
                        if (data == 'ok') {
                            if (top.frames['main'].box1 == undefined) {
                                if ('<%=KSCMS.S("field")%>' != '') {
                                                    $('#<%=KSCMS.S("field")%>', window.parent.document).val(vid);
                                                }
                                                $('#TextAddress', window.parent.document).val(vid);
                                                top.box1.close();
                                            } else {
                                                if ('<%=KSCMS.S("field")%>' != '') {
                                                    $(top.frames["main"].document.getElementById("<%=KSCMS.S("field")%>")).val(vid);
                                        }
                                        $(top.frames["main"].document.getElementById("TextAddress")).val(vid);
                                        top.frames['main'].box1.close();
                                    }
                                }
                                else if (data == 'have') {
                                    top.alert("抱歉，添加视频已经上限啦");
                                }
                            }
                        });


                        localStorage.removeItem(file.__uploadId);

                        var time = ((new Date().getTime() - file.__startTime) / 1000).toFixed(2);
                        var row = getRowById(file.__id);
                        var url = [BOS_ENDPOINT, info.body.bucket, info.body.object].join('/');

                        row.setStatus('ok-circle', true);
                        row.setUrl(url);
                        row.setTime(time);
                        file.__done(file, info);
                    },
                    NetworkSpeed: function (_, bytes, time, pendings) {
                        var speed = bytes / (time / 1000);
                        var html = '上传速度：' + humanize.filesize(speed) + '/s';

                        var seconds = pendings / speed;
                        if (seconds > 1) {
                            var dhms = baidubce.utils.toDHMS(Math.ceil(seconds));
                            html += '，剩余时间：' + [
                                humanize.pad(dhms.HH, 2, '0'),
                                humanize.pad(dhms.MM, 2, '0'),
                                humanize.pad(dhms.SS, 2, '0')
                            ].join(':');
                        }

                        $('.network-speed').html(html);
                    },
                    UploadComplete: function () {

                        $("#jspeed").hide();
                        $(".network-speed").hide();
                        // $('button[type=submit]').attr('disabled', true);
                    },
                    ListParts: function (_, file, uploadId) {
                        // 恢复断点续传的时候，从本地获取 parts 的信息，避免从服务读取
                        // 有时候服务器没有开放读取的权限
                        try {
                            var parts = localStorage.getItem(uploadId);
                            return JSON.parse(parts);
                        }
                        catch (ex) {
                        }
                    },
                    ChunkUploaded: function (_, file, result) {

                        var partNumber = result.partNumber;
                        var uploadId = result.uploadId;
                        var response = result.response;
                        var eTag = response.http_headers.etag;

                        file.__uploadId = uploadId;

                        if (eTag) {
                            var parts = localStorage.getItem(uploadId);
                            if (!parts) {
                                parts = [];
                            }
                            else {
                                parts = JSON.parse(parts);
                            }

                            parts.push({
                                partNumber: partNumber,
                                eTag: eTag
                            });

                            localStorage.setItem(uploadId, JSON.stringify(parts));
                        }
                    },
                    Error: function (_, error, file) {
                        var row = getRowById(file.__id);
                        if (error.status_code === 0) {
                            row.setStatus('pause', true);
                        }
                        else {
                            row.setStatus('remove-circle', false);
                            var errorMessage = $.isPlainObject(error) ? JSON.stringify(error) : String(error);
                            row.setErrorMessage(errorMessage);
                        }
                    }
                }
            });
            window.onload = new function () {
                if (document.getElementById("file").files == undefined) {
                    alert("该上传需要IE9及以上浏览器");
                }
            }
            document.getElementById("file")
                .addEventListener('change', function (event) {
                    setTimeout("startabc()", 500);

                });
            function startabc() {
                $("#jspeed").show();
                uploader.start();
                return false;
            }

            $('button[type=submit]').click(function () {
                uploader.start();
                return false;
            });


            $('#view-vods-modal').on('shown.bs.modal', function (e) {
                var mediaIds = JSON.parse(localStorage.getItem('vods') || '[]');
                if (!mediaIds.length) {
                    return;
                }

                $('#vods .empty').text('查询中...');
                var tasks = mediaIds.map(function (mediaId) {
                    return vod.setMediaId(mediaId).get();
                });
                baidubce.sdk.Q.all(tasks).then(function (responses) {
                    var medias = responses.map(function (response) {
                        return response.body;
                    });
                    return medias;
                }).then(function (medias) {
                    var html = [];
                    for (var i = 0; i < medias.length; i++) {
                        var item = medias[i];
                        var title = item.attributes.title || '-';
                        if (item.status === 'PUBLISHED') {
                            title = '<a target="_blank" href="vod-viewer.html?id=' + item.mediaId +
                                '&title=' + encodeURIComponent(title) + '">' + title + '</a>'
                        }
                        html.push(
                            '<tr>'
                            + '<td>' + (i + 1) + '</td>'
                            + '<td class="doc-name">' + (title) + '</td>'
                            + '<td>' + humanize.filesize(item.meta.sizeInBytes) + ' / ' + item.meta.durationInSeconds + '</td>'
                            + '<td>' + (item.status) + '</td>'
                            + '<td>' + (item.createTime) + '</td>'
                            + '<td>' + (item.publishTime || '-') + '</td>'
                            + '</tr>'
                        );
                    }
                    $('#vods tbody').html(html.join(''));
                });
            });

            $('#view-docs-modal').on('shown.bs.modal', function (e) {
                var documentIds = JSON.parse(localStorage.getItem('docs') || '[]');
                if (!documentIds.length) {
                    return;
                }

                $('#docs .empty').text('查询中...');
                var tasks = documentIds.map(function (docId) {
                    return doc.get(docId);
                });
                baidubce.sdk.Q.all(tasks).then(function (responses) {
                    var documents = responses.map(function (response) {
                        return response.body;
                    });
                    return documents;
                }).then(function (documents) {
                    documents.sort(function (a, b) {
                        var ac = new Date(a.createTime).getTime();
                        var bc = new Date(b.createTime).getTime();
                        if (ac > bc) {
                            return -1;
                        }
                        else if (ac < bc) {
                            return 1;
                        }
                        return 0;
                    });
                    var html = [];
                    for (var i = 0; i < documents.length; i++) {
                        var doc = documents[i];
                        // doc.docId -> 文档阅读ID，仅当文档状态为PUBLISHED时返回该字段
                        var title = doc.status === 'PUBLISHED'
                            ? '<a target="_blank" href="http://static.bcedocument.com/reader/v2/console/index.html?docId=' + doc.documentId + '&token=TOKEN&host=BCEDOC&enviroment=online">' + doc.title + '</a>'
                            : doc.title;
                        html.push(
                            '<tr>'
                            + '<td>' + (i + 1) + '</td>'
                            + '<td class="doc-name">' + (title) + '<br/>' + doc.documentId + '</td>'
                            + '<td>' + (doc.publishInfo ? humanize.filesize(doc.publishInfo.sizeInBytes) : '-') + '</td>'
                            + '<td>' + (doc.status) + '</td>'
                            + '<td>' + (doc.createTime) + '</td>'
                            + '<td>' + (doc.publishTime || '-') + '</td>'
                            + '</tr>'
                        );
                    }
                    $('#docs tbody').html(html.join(''));
                });
            });
        </script>
    </asp:Panel>

    <asp:Panel ID="tcyun" runat="server" Visible="false">
        <script src="//imgcache.qq.com/open/qcloud/js/vod/sdk/ugcUploader.js"></script>
        <script src="//imgcache.qq.com/open/qcloud/js/vod/sdk/ugcUploader.js"></script>
        <div class="clearfix topBtn">
            <div class="fl file">
                <input type="file" name="file" id="file" multiple />点击上传</div>
            <form id="form1">
                <input id="uploadVideoNow-file" type="file" style="display: none;" />
            </form>

            <div class="tips" style="margin-top: 30px;">上传的文件为.mp4,.flv,.avi,.mp3格式</div>
            <button type="submit" class="btn btn-success" disabled style="display: none">开始上传</button>

        </div>
        <!-- 上传进度显示 -->
        <div class="jdt" id="jspeed" style="display: none">
            <div class="jdtinner" style="width: 0%;">
                <div class="jd-data">0%</div>
            </div>
        </div>
        <span class="network-speed"></span>


        <div class="row" id="resultBox"></div>

        <script>


            var index = 0;
            var cosBox = [];

            /** 
             * 计算签名
            **/

            var getSignature = function (callback) {
                $.ajax({
                    url: '?domethod=gettcsignature',
                    type: 'POST',
                    //   dataType: 'json',
                    success: function (res) {
                        callback(res)
                    }
                });
            };
            /** 
             * 示例1：直接上传视频
            **/
            $('#file').on('change', function (e) {
                var num = addUploaderMsgBox('hasVideo');
                var videoFile = this.files[0];
                $('#result').append(videoFile.name + '\n');
                var resultMsg = qcVideo.ugcUploader.start({
                    videoFile: videoFile,
                    getSignature: getSignature,
                    allowAudio: 1,
                    success: function (result) {
                        if (result.type == 'video') {
                            $('[name=videoresult' + num + ']').text('上传成功');
                            $('[name=cancel' + num + ']').remove();
                            cosBox[num] = null;
                        } else if (result.type == 'cover') {
                            $('[name=coverresult' + num + ']').text('上传成功');
                        }
                    },
                    error: function (result) {
                        if (result.type == 'video') {
                            $('[name=videoresult' + num + ']').text('上传失败>>' + result.msg);
                        } else if (result.type == 'cover') {
                            $('[name=coverresult' + num + ']').text('上传失败>>' + result.msg);
                        }
                    },
                    progress: function (result) {
                        if (result.type == 'video') {
                            $('[name=videoname' + num + ']').text(result.name);
                            $('[name=videosha' + num + ']').text(Math.floor(result.shacurr * 100) + '%');
                            $('[name=videocurr' + num + ']').text(Math.floor(result.curr * 100) + '%');
                            $('[name=cancel' + num + ']').attr('taskId', result.taskId);
                            cosBox[num] = result.cos;
                        } else if (result.type == 'cover') {
                            $('[name=covername' + num + ']').text(result.name);
                            $('[name=coversha' + num + ']').text(Math.floor(result.shacurr * 100) + '%');
                            $('[name=covercurr' + num + ']').text(Math.floor(result.curr * 100) + '%');
                        }
                    },
                    finish: function (result) {
                        $('[name=videofileId' + num + ']').text(result.fileId);
                        parent.document.getElementById("TextAddress").value = result.fileId;
                        $.ajax({
                            url: '?domethod=savetcvideo',
                            type: 'POST',
                            data: { tcvid: result.fileId },
                            success: function (msg) {
                                //   alert(msg);
                            }
                        });

                        $('[name=videourl' + num + ']').text(result.videoUrl);
                        if (result.message) {
                            $('[name=videofileId' + num + ']').text(result.message);
                        }
                    }
                });
                if (resultMsg) {
                    $('[name=box' + num + ']').text(resultMsg);
                }
                $('#form1')[0].reset();
            });
            $('#uploadVideoNow').on('click', function () {
                $('#file').click();
            });


            /**
             * 添加上传信息模块
             */
            var addUploaderMsgBox = function (type) {
                var html = '<div class="uploaderMsgBox" name="box' + index + '">';
                if (!type || type == 'hasVideo') {
                    html += '视频名称：<span name="videoname' + index + '"></span>；' +
                        // '计算sha进度：<span name="videosha' + index + '">0%</span>；' +
                        '上传进度：<span name="videocurr' + index + '">0%</span>';
                    //   'fileId：<span name="videofileId' + index + '">   </span>；'
                    //    '上传结果：<span name="videoresult' + index + '">   </span>；<br>' +
                    //   '地址：<span name="videourl' + index + '">   </span>；' +

                }
                if (!type || type == 'hasCover') {
                    html += '封面名称：<span name="covername' + index + '"></span>；' +
                        //  '计算sha进度：<span name="coversha' + index + '">0%</span>；' +
                        '上传进度：<span name="covercurr' + index + '">0%</span>；' +
                        //   '上传结果：<span name="coverresult' + index + '">   </span>；<br>' +
                        //  '地址：<span name="coverurl' + index + '">   </span>；<br>' +
                        '</div>'
                }
                html += '</div>';

                $('#resultBox').append(html);
                return index++;
            };


            // 上传按钮点击事件
            $('#uploadFile').on('click', function () {
                var secretId = $('#secretId').val();
                var secretKey = $('#secretKey').val();
                startUploader();
                $('#form2')[0].reset();
            });


        </script>

        <script>
            var _mtac = {};
            (function () {
                var mta = document.createElement("script");
                mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.2";
                mta.setAttribute("name", "MTAH5");
                mta.setAttribute("sid", "500586412");
                var s = document.getElementsByTagName("script")[0];
                s.parentNode.insertBefore(mta, s);
            })();
        </script>
    </asp:Panel>

    <asp:Panel runat="server" ID="ccvedio" Visible="false">
        <script type="text/javascript" src="/KS_inc/swfobject.js"></script>
        <style>
            #SwfBrowse embed {
                position: absolute;
                width: 100%;
                height: 100%;
                left: 0;
                z-index: 5;
                top: 0;
            }
        </style>

        <!--flash控件地址 -->
        <input id="flashUrl" name="flashUrl" class="form-control" value="http://union.bokecc.com/flash/api/uploader.swf" disabled="disabled" type="hidden">
        <div class="clearfix topBtn" style="height: 500px">
            <div style="display: none">
                <input value="" type="text" style="width: 300px" placeholder="请输入视频标签（非必填，默认为上传文件名称）" id="cctag" />
                <input value="" type="text" style="width: 300px" placeholder="请输入视频描述（必填，长度小于200字符）" id="ccdescription" /><br />
            </div>
            <input value="" type="text" style="width: 300px" placeholder="请输入分类ID（非必填，默认分类）" id="ccclassId" />
            <div class="fl file">
                <div style="z-index: 4; width: 100px; height: 42px" id="SwfBrowse"></div>
                <div style="z-index: 1; position: absolute; left: 0; top: 0; width: 100%; text-align: center; line-height: 42px;">点击上传</div>
            </div>
            <span class="tips">上传成功后，要进行转码，因此视频在5-10分钟内无法观看</span>
            <input name="videofilename" id="videofilename" type="hidden" disabled="disabled" class="form-control" />

            <div id="upload_message" class="fl upload-message"></div>
            <div id="upload_prompt"></div>
        </div>
        <script type="text/javascript">
            var fileVid = '<%=DateTime.Now.ToFileTimeUtc().ToString()%>';

            var swfobj = new SWFObject($("#flashUrl").val(), 'uploadswf', '50', '30', '8');
            swfobj.addVariable('progress_interval', '1');
            swfobj.addVariable('notify_url', '<%=Utils.GetRootPath()%>/plus/yun/yuncs.aspx?domethod=changeccvid&oldvid=' + fileVid);
            swfobj.addParam('allowFullscreen', 'true');
            swfobj.addParam('allowScriptAccess', 'always');
            swfobj.addParam('wmode', 'transparent');
            swfobj.write('SwfBrowse');
            var filename;
            // 获取名字
            function on_spark_selected_file(file_name, file_size) {
                $("#videofilename").val(file_name);
                filename = file_name;
                DoUpload();
            }
            // 上传处理过程
            function on_spark_upload_validated(status, ccid) {
                switch (status) {
                    case "OK":
                        filename = null;
                        document.getElementById("videofilename").value = "";
                        break;
                    case "INVALID_REQUEST": $("#upload_prompt").html("参数有误，请重新输入"); break;
                    case "SPACE_NOT_ENOUGH": $("#upload_prompt").html("账户剩余空间不足"); break;
                    case "SERVICE_EXPIRED": $("#upload_prompt").html("账户服务已过期"); break;
                    case "PROCESS_FAIL": $("#upload_prompt").html(" 服务器处理失败，请稍候再试"); break;
                    case "TOO_MANY_REQUEST": $("#upload_prompt").html("访问过于频繁"); break;
                    case "PERMISSION_DENY": $("#upload_prompt").html("无API使用权限，请检查用户ID和授权KEY是否正确"); break;
                }
            }
            //上传进度显示
            function on_spark_upload_progress(progress) {
                $("#upload_progress").show();
                if (progress == 100) {
                    $("#upload_prompt").html("已上传100%");
                    parent.document.getElementById("TextAddress").value = fileVid;

                } else if (progress < 0) {
                    $("#upload_prompt").html("上传发生错误，请稍后再试");
                } else if (progress < 100) {
                    $("#upload_prompt").html("已上传" + progress + "%");
                }
            }
            function DoUpload() {
                //filename = $("#file").val();
                //var length = filename.split("\\").length;
                //if (length - 1 > 0) {
                //    filename = filename.split("\\")[length - 1];
                //}
                //filename = filename.split(".")[0];
          
                $.ajax({
                    type: "Post",
                    url: "?domethod=getccstr",
                    data: { ccclassId: $("#ccclassId").val(), ccdescription: $("#ccdescription").val(), cctag: $("#cctag").val(), filename: filename, fileVid: fileVid },
                    success: function (msg) {
                        $("#uploadswf")[0].start_upload(msg);
                    }
                });
            }
           
          
        </script>


    </asp:Panel>

    <asp:Panel ID="yunxin" runat="server" Visible="false" >
        <form id="form1" runat="server">
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="Button3" runat="server" Text="上传" OnClick="Button3_Click" />
            <div style="display:none;">
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
            <script>
                if ($("#Label1").html() != '' || $("#Label1").html() != 'Label')
                {
                    parent.document.getElementById("TextAddress").value = $("#Label1").html();
                }
            </script>
        </form>
    </asp:Panel>

</body>
</html>

