text: /*global Qiniu */
  /*global plupload */
  /*global FileProgress */
  /*global hljs */
  
  
  $(function() {
      var uploader = Qiniu.uploader({
          runtimes: 'html5,flash,html4',   //上传模式,依次退化
          browse_button: 'pickfiles',      //上传选择的点选按钮，**必需**
          container: 'container',
          drop_element: 'container',
          max_file_size: '20mb',           //最大文件体积限制
          flash_swf_url: 'js/plupload/Moxie.swf',
          dragdrop: true,
          chunk_size: '4mb',
          uptoken_url: uptoken_url,    //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
          domain: qiniu_domain,        //bucket 域名，下载资源时用到，**必需**
          // downtoken_url: '/downtoken',
          unique_names: true,
          save_key: false,
          // x_vars: {
          //     'id': '1234',
          //     'time': function(up, file) {
          //         var time = (new Date()).getTime();
          //         // do something with 'time'
          //         return time;
          //     },
          // },
          auto_start: true,    //选择文件后自动上传，若关闭需要自己绑定事件触发上传
          init: {
              'FilesAdded': function(up, files) {
                  $('table').show();
                  $('#success').hide();
                  plupload.each(files, function(file) {
                       // 文件添加进队列后,处理相关的事情
                      var progress = new FileProgress(file, 'fsUploadProgress');
                      progress.setStatus("等待...");
                  });
              },
              'BeforeUpload': function(up, file) {
                  // 文件添加进队列后,处理相关的事情
                  var progress = new FileProgress(file, 'fsUploadProgress');
                  var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                  if (up.runtime === 'html5' && chunk_size) {
                      progress.setChunkProgess(chunk_size);
                  }
              },
              'UploadProgress': function(up, file) {
                  // 每个文件上传时,处理相关的事情
                  var progress = new FileProgress(file, 'fsUploadProgress');
                  var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                  progress.setProgress(file.percent + "%", up.total.bytesPerSec, chunk_size);
  
              },
              'UploadComplete': function(up, files) {
                  //队列文件处理完毕后,处理相关的事情
                  //window.location.reload();
                  var status          = $('#status').val();
                  //if(!status){return;}
  //console.log(files, up,status);
                  var files_items     = files.length;
                  var activity_id     = $('#activity_id').val();
                  var type            = $('#activity_type').val();
                  var event           = $('#activity_event').val();
                  var domain          = up.getOption('domain');//http://7xkn0f.com2.z0.glb.qiniucdn.com/
                  //console.log(domain); 
                  $.post(timeline_url,
                      {
                          files_items:files_items,
                          activity_id:activity_id,
                          type:type,
                          event:event,
                          domain:domain,
                          status:status,
                      }
                  );
  
                  $('#success').show();
              },
              'FileUploaded': function(up, file, info) {
                  // 每个文件上传成功后,处理相关的事情
                  // 其中 info 是文件上传成功后，服务端返回的json，形式如
                  // {
                  //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                  //    "key": "gogopher.jpg"
                  //  }
                  // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
  
                  // var domain = up.getOption('domain');
                  // var res = parseJSON(info);
                  // var sourceLink = domain + res.key; 获取上传成功后的文件的Url
  
                  var progress = new FileProgress(file, 'fsUploadProgress');
                  progress.setComplete(up, info);
                  var res = $.parseJSON(info);
                  // 每个文件上传成功后,处理相关的事情
                 // 其中 info 是文件上传成功后，服务端返回的json，形式如
                 // {
                 //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                 //    "key": "gogopher.jpg"
                 //  }
                 // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
                 //是否公开
                 var ispublic = $('#status').val();
                 var activity_id = $('#activity_id').val(); 
                 var domain = up.getOption('domain');
                 //console.log(res);
                 //console.log(domain,activity_id);
                 $.post(upload_url,
                  {
                      activity_id:activity_id,
                      hash:res.hash,
                      type:res.type,
                      size:res.size,
                      file_name:res.name,
                      url:res.key,
                      ispublic:ispublic
                  });
              },
              'Error': function(up, err, errTip) {
                  //上传出错时,处理相关的事情
                  $('table').show();
                  var progress = new FileProgress(err.file, 'fsUploadProgress');
                  progress.setError();
                  progress.setStatus(errTip);
              },
              'generateMixed' : function () {
                  var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','i','s','t','u','v','w','x','y','z'];
                  var len = chars.length;
                  var res = "";
                  for(var i = 0; i < n ; i ++) {
                   var id = Math.ceil(Math.random()*len);
                   res += chars[id];
                  }
                  return res;
              },   
              //'Key': function(up, file) {
              //     return this.generateMixed();
              //}
          }
      });
  
      uploader.bind('FileUploaded', function() {
          console.log('hello man,a file is uploaded');
      });
      $('#container').on(
          'dragenter',
          function(e) {
              e.preventDefault();
              $('#container').addClass('draging');
              e.stopPropagation();
          }
      ).on('drop', function(e) {
          e.preventDefault();
          $('#container').removeClass('draging');
          e.stopPropagation();
      }).on('dragleave', function(e) {
          e.preventDefault();
          $('#container').removeClass('draging');
          e.stopPropagation();
      }).on('dragover', function(e) {
          e.preventDefault();
          $('#container').addClass('draging');
          e.stopPropagation();
      });
  
  
  
      $('#show_code').on('click', function() {
          $('#myModal-code').modal();
          $('pre code').each(function(i, e) {
              hljs.highlightBlock(e);
          });
      });
  
  
      $('body').on('click', 'table button.btn', function() {
          $(this).parents('tr').next().toggle();
      });
  
  
      var getRotate = function(url) {
          if (!url) {
              return 0;
          }
          var arr = url.split('/');
          for (var i = 0, len = arr.length; i < len; i++) {
              if (arr[i] === 'rotate') {
                  return parseInt(arr[i + 1], 10);
              }
          }
          return 0;
      };
  
      $('#myModal-img .modal-body-footer').find('a').on('click', function() {
          var img = $('#myModal-img').find('.modal-body img');
          var key = img.data('key');
          var oldUrl = img.attr('src');
          var originHeight = parseInt(img.data('h'), 10);
          var fopArr = [];
          var rotate = getRotate(oldUrl);
          if (!$(this).hasClass('no-disable-click')) {
              $(this).addClass('disabled').siblings().removeClass('disabled');
              if ($(this).data('imagemogr') !== 'no-rotate') {
                  fopArr.push({
                      'fop': 'imageMogr2',
                      'auto-orient': true,
                      'strip': true,
                      'rotate': rotate,
                      'format': 'png'
                  });
              }
          } else {
              $(this).siblings().removeClass('disabled');
              var imageMogr = $(this).data('imagemogr');
              if (imageMogr === 'left') {
                  rotate = rotate - 90 < 0 ? rotate + 270 : rotate - 90;
              } else if (imageMogr === 'right') {
                  rotate = rotate + 90 > 360 ? rotate - 270 : rotate + 90;
              }
              fopArr.push({
                  'fop': 'imageMogr2',
                  'auto-orient': true,
                  'strip': true,
                  'rotate': rotate,
                  'format': 'png'
              });
          }
  
          $('#myModal-img .modal-body-footer').find('a.disabled').each(function() {
  
              var watermark = $(this).data('watermark');
              var imageView = $(this).data('imageview');
              var imageMogr = $(this).data('imagemogr');
  
              if (watermark) {
                  fopArr.push({
                      fop: 'watermark',
                      mode: 1,
                      image: 'http://www.b1.qiniudn.com/images/logo-2.png',
                      dissolve: 100,
                      gravity: watermark,
                      dx: 100,
                      dy: 100
                  });
              }
  
              if (imageView) {
                  var height;
                  switch (imageView) {
                      case 'large':
                          height = originHeight;
                          break;
                      case 'middle':
                          height = originHeight * 0.5;
                          break;
                      case 'small':
                          height = originHeight * 0.1;
                          break;
                      default:
                          height = originHeight;
                          break;
                  }
                  fopArr.push({
                      fop: 'imageView2',
                      mode: 3,
                      h: parseInt(height, 10),
                      q: 100,
                      format: 'png'
                  });
              }
  
              if (imageMogr === 'no-rotate') {
                  fopArr.push({
                      'fop': 'imageMogr2',
                      'auto-orient': true,
                      'strip': true,
                      'rotate': 0,
                      'format': 'png'
                  });
              }
          });
  
          var newUrl = Qiniu.pipeline(fopArr, key);
  
          var newImg = new Image();
          img.attr('src', './img/loading.gif');
          newImg.onload = function() {
              img.attr('src', newUrl);
              img.parent('a').attr('href', newUrl);
          };
          newImg.src = newUrl;
          return false;
      });
  
  });
  