// ==UserScript==
// @name 			Զд롾ǿ桿ֹͣά
// @description		Զдȡ롾ǿ桿+̳ȡںϡ\nýűֹͣάƼʹЧõġǿ桿https://greasyfork.org/zh-CN/scripts/29762 \nűǿһ°汾ѡ˲ֻͣҪǲˣ
// @author			ƷСè
// @namespace   	http://www.cnblogs.com/hkmhd/
// @homepage		https://greasyfork.org/scripts/13463
// @supportURL		https://greasyfork.org/scripts/13463/feedback
// @version			2.5.7
// @date			  2015.10.30
// @modified		2018.02.25
// 
// ֵ֧
// @include     	http://*
// @include			https://*
// @include			http://pan.baidu.com/s/*
// @include			http://eyun.baidu.com/s/*
// 
// 
// @exclude			http*://*.pcs.baidu.com/*
// @exclude			http*://*.baidupcs.com/*
// @exclude			http*://*:8666/file/*
// @exclude			http*://*.baidu.com/file/*
// @exclude			http*://index.baidu.com/*
// 
// @exclude			http*://*.gov/*
// @exclude			http*://*.gov.cn/*
// @exclude			http*://*.taobao.com/*
// @exclude			http*://*.tmall.com/*
// @exclude			http*://*.alimama.com/*
// @exclude			http*://*.jd.com/*
// @exclude			http://*.ctrip.com/*
// @exclude			https://*.evernote.com/*
// @exclude			https://*.yinxiang.com/*
// @exclude			/^https?://(localhost|10\.|192\.|127\.)/
// @exclude			/https?://www.baidu.com/(?:s|baidu)\?/
// @exclude			http*://www.zhihu.com/question/*/answers/created
//
// require			http://code.jquery.com/jquery-2.1.4.min.js
// @require			http://cdn.staticfile.org/jquery/2.1.4/jquery.min.js
// @grant			unsafeWindow
// @grant			  GM_setValue
// @grant       GM_getValue
// @grant       GM_openInTab
// @encoding		utf-8
// @run-at			document-idle
// ==/UserScript==

var urls=location.href;
var hash=location.hash;
var host=location.hostname.replace(/^www\./i,'').toLowerCase();
var paths=location.pathname.toLowerCase();
unsafeWindow.eve = Event;

var CatPW_Manage_old;
if(GM_getValue('CatPW_Manage_old')=='undefined'||GM_getValue('CatPW_Manage_old')==undefined) {
  CatPW_Manage_old={'updataTips':false,'dontPush':false,'Date':Dates()};
  GM_setValue('CatPW_Manage_old', CatPW_Manage_old);
} else {
  CatPW_Manage_old=GM_getValue('CatPW_Manage_old');
}

if(!CatPW_Manage_old.updataTips) {
    var updata=confirm('лԡԶд롾ǿ桿֧\nڸð汾Ѿֹͣά㰲װЧõġԶд롾ǿ桿ȷǰװ°汾');
    CatPW_Manage_old.updataTips=true;

    if(updata) {
      CatPW_Manage_old.dontPush=true;
      GM_setValue('CatPW_Manage_old', CatPW_Manage_old);
      GM_openInTab('https://greasyfork.org/zh-CN/scripts/29762',{'active':true});
    } else {
      var DontPushTips=confirm('㲻Ըи£ȷԺ󡱽ʾ°汾͡ݣ');
      if(DontPushTips) {
        CatPW_Manage_old.dontPush=true;
        GM_setValue('CatPW_Manage_old', CatPW_Manage_old);
      }
    }
}

var site = {
  'baidu.com':{
    chk:	/^[a-z0-9]{4}$/,
    code:	'.pickpw input, #accessCode',
    btn:	'.g-button, #submitBtn, #getfileBtn',
    PreProcess: function() {	//Ѵ
      if(host=='eyun.baidu.com'){	//Ϊٶҵ̣ҵ̵ķʽ
        conf=site['baidu.com']=site['eyun.baidu.com'];
        site['baidu.com'].PreProcess();
      }
    }
  },
  'eyun.baidu.com': {
    chk:	/^[a-z0-9]{4}$/,
    code:	'.share-access-code',
    btn:	'.g-button-right',
    PreProcess: function() {
      if((hash&&!/sharelink|path/i.test(hash))&&!/enterprise/.test(paths)) {
        console.log('test');
        location.href=location.href.replace(location.hash,'');
      }
    }
  },
  'weiyun.com': {
    chk: /^[a-z0-9]{4}$/i,
    code: '#outlink_pwd',
    btn:  '#outlink_pwd_ok'
  },
  'pwdRule' : /(?:ȡ|)[a]?\s*[: ]?\s*([a-z\d]{4})/,			//
  'codeRule' : /(?:(?:ȡ||[a]||Extracted-code)[a]?)\s*[: ]?\s*([a-z\d]{4})/i,	//͵
  //תԤ
  'JumpUrl' : {
    'sijihuisuo.club': {
      href: $('.down-tip A[href^="https://www.sijihuisuo.club/go/?url="]'),
      url: 'https://www.sijihuisuo.club/go/?url='
    }
  },
  //ںҪֵ֧վ
  'Support' : {
    'madsck.com':{
      path: /\/resource\/\d+/,
      callback:function(){
        var ID=$('.btn-download').data('id');
          $.ajax({
            "url":"http://www.madsck.com/ajax/login/download-link?id="+ID,
            method: "GET",
            dataType: "json",
            success:function(e){
              var res=e.resource;
              $('.btn-download').css('display','none');
              $('<a>').attr({'href':res.resource_link+'#'+res.fetch_code,'target':'blank','class':'btn-download'}).css({'line-height':'60px','text-align':'center','font-size':'24px'}).text('').insertBefore('.btn-download');
              console.log(e);
            }
          })
      }
    },
    'idanmu.co': {
      path : /storage\-download/i,
      callback : function(){
        $('.input-group').each(function(){
          $(this).text($(this).text()+$(this).find('input').val());
        });
      }
    },
    'shaoit.com': {
      path : /.*/i,
      callback : function(){
        var LinkParent=$('A[href*="pan.baidu.com"],A[href*="eyun.baidu.com"]').parent();
        var ParentHTML=LinkParent.html();
        site['codeRule']=/\s*(shaoit|[a-z\d]{4})((?:\s*|<br>)$)/i;
          var HtmlArr=ParentHTML.match(/.*(?: \/|\s*$|<br>)/ig);
          for(i=0;i<HtmlArr.length;i++){
            if(/<\/a>\s*([a-z\d]{4}|shaoit) \//i.test(HtmlArr[i])){
              HtmlArr[i]=HtmlArr[i].replace(/(href="[^"]+)("[^>]*?>(?!<\/a>).+?<\/a>\s*(shaoit|[a-z\d]{4}))/ig,'$1#$3$2');
            } else if(site['codeRule'].test(HtmlArr[i])){
              var PWcode=HtmlArr[i].match(site['codeRule'])[1];
              HtmlArr[i]=HtmlArr[i].replace(/(href="[^"]+?)"/ig,'$1#'+PWcode+'"');
            }
          }
          LinkParent.html(HtmlArr.join(''));
        
      }
    },
    'xunyingwang.com':{
      path:/movie/i,
      callback:function(){
        $(window).load(function(){
          $('A[href*="pan.baidu.com"],A[href*="eyun.baidu.com"]').each(function(){
            $(this).attr('href',$(this).attr('href')+'#'+$(this).next("strong").text())
          })
        })
      }
    },
    'huhupan.com':{
      path:/e\/extend\/down/i,
      callback:function(){
        var _Linktmp=$('A[href*="pan.baidu.com"],A[href*="eyun.baidu.com"]');
        var _PWtmp=$('input[id^="bdypas"]');
        for(i=0;i<_Linktmp.length;i++){
          _Linktmp[i].href+="#"+_PWtmp[i].value;
        }
      }
    },
    'reimu.net': {
      path: /archives/i,
      callback: function(){
        site['codeRule']=/(?:(?:ȡ||[a])[a]?)\s*[: ]?\s*([a-z\d]{4}|8)/i
      }
    }
  }
};

var hostName = location.host.match(/\w+\.\w+$/)[0].toLowerCase();	//ȡǰվã
var conf = site[hostName];											//

var HostArr = [];									//
for(var i in site) HostArr.push(i);					//
var HostExp = new RegExp(HostArr.join("|"),'i');	//У鳬ӵ

//console.log(site.JumpUrl[host]);

/* -----===== ǷҪת Start =====----- */

if(site['JumpUrl'][host]){
  console.log(site['JumpUrl'][host]['href'])
  site['JumpUrl'][host]['href'].each(function(){
    console.log(site['JumpUrl'][host]['rep'])
    $(this).attr({'href':decodeURIComponent($(this).attr('href').replace(site['JumpUrl'][host]['url'],'')),'target':'blank'});
  });
}
/* -----===== ǷҪת End =====----- */


if(conf&&!/zhidao.baidu.com/i.test(host)){	//ҳ¼
  // ץȡȡ
  if(conf.PreProcess) conf.PreProcess();		//Ԥٶҵƣ
  var sCode = hash.slice(1).trim();

  // ãǷΪϷʽ
  if (!conf.chk.test(sCode)) {
    console.log('û Key ʽ');
  } else {
    console.log ('ץȡȡ: %s', sCode);
  }

  // ӸСʱ
  setTimeout (function () {
    // ȡ벢ύť
    var codeBox = $(conf.code),
        btnOk = $(conf.btn);
    if(codeBox.length>0) {		//ʱŽύ
      codeBox.val(sCode);		//д֤
      if (conf.preSubmit)
        if (conf.preSubmit (codeBox, btnOk))
          return ;
      btnOk.click();
    }
  }, 10);
} else {
  //ں رֵ֧վ
  if(site['Support'][hostName]&&site['Support'][hostName]['path'].test(paths)) {
    site['Support'][hostName].callback();
  }
  // A ǩ¼
  $('body').on('click', 'a', function () {
    var target=this;
    // hash 
    if(this.hash) return;
    //ĿΪٶҵ̣ƥ䷶ΧԼݰٶҵ
    if(/eyun.baidu.com/i.test(this.href)) {
  		site['pwdRule']=/(?:ȡ|)[a]?\s*[: ]?\s*([a-z\d]{4,14})/;
  		site['codeRule']=/(?:(?:ȡ||[a]|Extracted-code)[a]?)\s*[: ]?\s*([a-z\d]{4,14})/i;
    }
    //var target=event.target.tagName==='A'?event.target:event.target.parentNode;
   	
    //У鳬ƥ
    if(HostExp.test(this.href)&&!/(?:tieba)\.baidu\.com/i.test(this.href)){
      
      
      if(site['codeRule'].test(target.textContent)){
        console.log('ڵǰӵĶв');
        target.href+='#'+extCode(target);
      } else if(target.nextSibling&&site['codeRule'].test(target.nextSibling.textContent)){
        console.log('ڳӺֵԪ',target.nextSibling.textContent);
        if(!/#/i.test(target.href)) target.href+='#'+extCode(target.nextSibling);
      } else if(site['pwdRule'].test(target.parentNode.textContent)){
        console.log('Ӹв');
        if(!/#/i.test(target.href)) target.href+='#'+extCode(target.parentNode);
      } else {
        var i = 0,
            maxParent = 5,	//ϱĲ㼶
            parent = target;
        while(i<maxParent) {
          i++;									//
          parent = parent.parentNode;			//ȡø
          console.log('ϼĿ¼룺'+ i,parent);
          if(parent.tagName=="TR") {				//Ǳӱȡ
            if(site['codeRule'].test(parent.nextElementSibling.textContent)) {
              parent=parent.nextElementSibling;
              //console.log('вɹ',parent);
              target.href+='#'+extCode(parent);
              break;
            }
          } else if(site['codeRule'].test(pw=parent.nextSibling.textContent)){
            console.log('ϱңڳӺֵԪУ',parent.nextSibling);
            target.href+='#'+extCode(parent.nextSibling);
            break;
          } else if(site['codeRule'].test(parent.textContent)) {		//ճ淽ʽȡ
            console.log('ϱɹ');
            target.href+='#'+extCode(parent);
            break;
          }
          if(parent==document.body) break;								//Ѿ
        }
      }
      //console.log(site['codeRule']);
            //ɵĴӸбʽ
            //console.log(' document.body в');
            //if(!/#/i.test(target.href)) target.href+='#'+extCode(document.body);
    }
  });
}

function extCode(obj){
  text=obj.textContent.trim();
  return site['pwdRule'].test(text)?text.match(site['pwdRule'])[1]:text.match(site['codeRule'])[1];	//ȳʹ ȡ| ΪƥĹؼ֣Чʱʹøƥ
}

function Dates(){
  var sDate=new Date();         ///ϵͳ
  var sYear=sDate.getFullYear();	//
  var sMonth=sDate.getMonth()+1;  //·
  var sDay=sDate.getDate();     //
  return sYear+'/'+sMonth+'/'+sDay;
}