jeffrey4l
8/6/2013 - 5:12 AM

Yooli_Enhance.js

// ==UserScript==
// @name       Yooli Enhance
// @namespace  http://xcodest.me/
// @version    0.2
// @description  Yooli Enhance
// @match      http://www.yooli.com/*
// @match      https://www.yooli.com/*
// @require    http://www.yooli.com/v2/local/js/common/jquery-1.8.3.min.js
// @updateURL  https://gist.github.com/jeffrey4l/6162185/raw/de803a96bca9988cb10e2e9bef3b395c5cf55bdb/Yooli_Enhance.js
// @copyright  2012+, You
// ==/UserScript==

function addStyle(style) {
	var head = document.getElementsByTagName("HEAD")[0];
	var ele = head.appendChild(window.document.createElement( 'style' ));
	ele.innerHTML = style;
	return ele;
}

function addJavascript(js){
    var head = document.getElementsByTagName("HEAD")[0];
	var ele = head.appendChild(window.document.createElement( 'script' ));
	ele.type = "text/javascript";
    ele.src = js;
	return ele;
}

global_timeout = undefined;
// :NOTE(jeffrey4l) Dirty Hack. This will work when Jquery is not loaded.
if (location.href == 'http://www.yooli.com/yuexitong/' ){
  global_timeout = window.setTimeout(function(){location.reload();}, 300*1000);
}



//addStyle('@import "//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css";');
//addJavascript('//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js');
YE = {
  DEBUG: true,

  logging :{
    _log: function(level, msg){
      console.log([YE.date(), level, msg].join(' '));
    },
    debug:function(msg){
      if (YE.DEBUG)
        YE.logging._log('DEBUG',msg);
    },
    info: function(msg){
      YE.logging._log('INFO', msg);
    }
  },

  date:function(){
    var d = new Date();
    var tarr = [d.getHours(), d.getMinutes(), d.getSeconds()];
    var new_t = tarr.map(function(val, index){
      val += "";
      if (val.length < 2)
        return "0"+val;
      return val;
    });
    return new_t.join(':');
  },

  count:function(start, step){var _cur = start -1 || 0, _step = step || 1;function _(){return _cur += _step;}return {next:_, cur:function(){return _cur;}};},
  // init
  init:function(){
    if (global_timeout !== undefined ){
      window.clearTimeout(global_timeout);
    }
    $('body').prepend('<div id="ye_window" style="position:fixed;margin:20px 2px;z-index:10000;"></div>');
    $('body').prepend('<div id="ye_right" style="position:fixed;right:0px;margin:40px 10px;z-index:10000; width:160px; text-align:left; font-size:30px;"></div>');

    var links = []; 
    $('#ye_right').html("<ul>"+links.join("")+'</ul>');

    var clazz_dingcunbao='', clazz_yuexitong='';
    if (location.href == 'http://www.yooli.com/dingcunbao/'){
      clazz_dingcunbao = 'current';
    }
    if (location.href == "http://www.yooli.com/yuexitong/"){
      clazz_yuexitong = 'current';
    }
    $('.use').prepend('<a class="' + clazz_yuexitong + '" href="/yuexitong/">月息通</a>');
    $('.use').prepend('<a class="' + clazz_dingcunbao + '" href="/dingcunbao/">定存宝</a>');
    $('.use>a[href="/invest/"]').remove();

    $('.yCheckbox>span').prop('class', 'ico selected');

    var investment_a = $('.apply-menu a[href*="investment"]');
    if (investment_a){
      investment_a.prop('href', investment_a.prop('href') + '#yuexitong');
    }
  },
  timer:function(title, last, callback){
    var span_id = "_timer_counter"+YE.ID.next();
    var p_id = '_timer_p' + YE.ID.next();
    YE.msg_show('<p id="'+p_id+'">'+title+'<span id="'+span_id+'"></span>秒<a href="">X</a></p>');

    var start_time  = new Date();
    var interval = window.setInterval(function(){
      var cur_time = new Date();
      var dur = start_time - cur_time + last;
      if (dur < 0 ) 
        {
          callback();
          dur = 0;
          window.clearInterval(interval);
        }
        $('#'+span_id).text((dur/1000).toFixed(1 ));
    },250);

    $('#'+p_id+">a").click(function(){
      window.clearInterval(interval);
      $('#'+p_id).remove();
      return false;
    });
  }, 
  show_log:function(){
    var notification = GM_getValue('notification') || [];

    while(notification.length > 20){
      console.log(notification.shift());
    }
    GM_setValue('notification', notification);
    var msg = notification.join('<br/>');
    msg += "<p><a href='#' onclick='YE.clean_log()'>clear all</a><p>";
    YE.msg_show(msg);
  },
  clean_log:function(){
    GM_setValue('notification', []);
    location.reload();
    return false;
  },
  msg_show:function(msg){
    var ye_window = $('#ye_window');
    ye_window.html(ye_window.html()+msg);
  },
  msg_toggle:function(){

    //TODO
  },
  reload_page:function(){
    location.reload();
    //$.get(location.href, function(data){$('body').html($(data).find('body'))})
  },
  log:function(msg){
    var notification = GM_getValue('notification') || [];
    notification.push( YE.date() +"&nbsp;&nbsp;" + msg);
    GM_setValue('notification', notification);
  },
  list_interest: function(){
    var now = new Date();
    var cache_key = 'all_loans:' + now.getFullYear()+now.getMonth()+now.getDate();
    var all_loans = GM_getValue(cache_key) || [];
    var _count_sum = 0;
    var _principal_sum = 0;
    var _interest_sum = 0;
    var fixed_num = 1;
    var print_table = function(loans){
    var html = '<table border="1" style="text-align:center;font-size:.89em;color:black;">';
    var weekend_start = false;
      for(var index in loans){
        var repayDate = new Date(loans[index].repayDate);
        var repayTotal = 0;
        var day = repayDate.getDay();
        html += '<tr><td>' + loans[index].repayDate.slice(8) + '</td><td>' + loans[index].loanCount + '</td><td>' + 
          loans[index].repayPrincipal.toFixed(fixed_num) + '</td><td>' + loans[index].repayInterest.toFixed(fixed_num) + '</td>';
        if ([5,6,0].indexOf(day) != -1 && weekend_start === false){
          weekend_start  = true;
          var _index = parseInt(index);
          var _loans = loans.slice(_index, _index+3);
          _loans = _loans.filter(function(value){
            var day = new Date(value.repayDate).getDay();
            if ([0, 5, 6].indexOf(day) != -1){
              return true;
            }
          });
          for(var i in _loans){
            repayTotal += _loans[i].repayPrincipal;
            repayTotal += _loans[i].repayInterest;
          }
          html += '<td rowspan="' + _loans.length +  '">' + repayTotal.toFixed(fixed_num) +'</td>';
        } else if ([1,2,3,4].indexOf(day) != -1) {
          weekend_start = false;
          html += '<td>' + (loans[index].repayPrincipal + loans[index].repayInterest).toFixed(fixed_num) +'</td>';
        }
        html += '</tr>';
        _count_sum += loans[index].loanCount ;
        _principal_sum += loans[index].repayPrincipal;
        _interest_sum += loans[index].repayInterest;
      }
      html += '<tr><td>&nbsp;</td><td>'+_count_sum+'</td><td>'+_principal_sum.toFixed(fixed_num)+'</td><td>'+
        _interest_sum.toFixed(fixed_num)+'</td><td>' + (_principal_sum + _interest_sum).toFixed(fixed_num) +'</td></tr>';
      html += '<tr><td colspan="5"><a href="#" id="force_reload">force_reload</a></td></tr>';
      html += '</table>';
      YE.msg_show(html);
      $('#force_reload').click(function(){
        $.each(GM_listValues(), function(index, value){
          if (value.indexOf('all_loans') === 0)
            GM_deleteValue(value);
        });
        location.reload();
        return false;
      });
    };
    if (all_loans.length === 0){
      console.log('get all the load');
      var now = new Date();
      var next_month = new Date(now.getFullYear(), now.getMonth()+1, 1);
      $.when(
        $.post('http://www.yooli.com/rest/repayload/'+ environment.userId +'/monthly/' + (now.getMonth()+1) + '/'),
        $.post('http://www.yooli.com/rest/repayload/'+ environment.userId +'/monthly/' + (next_month.getMonth()+1) + '/')
      ).done(function(v1,v2){
        all_loans = all_loans.concat(v1[0].loans).concat(v2[0].loans);
        print_table(all_loans);
        GM_setValue(cache_key, all_loans);
      });
    }else{
      YE.logging.debug('Using cached date');
      print_table(all_loans);
    }
  },
  check_right:function(){
    var exist = 0, moneys = [], price = 0, can_buy = false;
    $('.items').each(function(i,v){
      if ($(v).find('li:first>.zhuan').length !== 0 && $(v).find('.col_7').text().indexOf('购买') != -1){
        exist +=1;
        price = $(v).find('.col_3').text();
        price = price.slice(price.search(/\d/));
        price = price.replace(',','');
        price = parseFloat(price);
        moneys.push(price);

        if (parseFloat(environment.userCash) >= price){
          can_buy = true;
        }
      }
    });

    if (can_buy || exist !== 0){
      YE.log('有债权. ' + moneys.length +':['+ moneys+']');
      GM_notification('exist! Pls quickly. There are ' + exist);
      YE.timer("页面刷新倒计时",20*1000, function(){YE.reload_page();});
    }else if (exist !== 0){
      YE.log('有债权. ' + moneys.length +':['+ moneys+']');
      YE.timer("页面刷新倒计时",5*1000, function(){YE.reload_page();});
    }else{
      YE.timer("页面刷新倒计时",5*1000, function(){YE.reload_page();});
    }
  },
};

var run = function(){
  YE.ID = YE.count();
  YE.init();
  // handle 500 error page
  var pageContent = $('#pageContent02');
  var text = pageContent.text();
  if (text.indexOf('本网站正在维护中') != -1 || text.indexOf('资源不存在') != -1){
    location.href='http://www.yooli.com/loan/invest/credit.html';
    return;
  }
  YE.list_interest();
  if (location.href == 'http://www.yooli.com/transactionRecords.session.action'){
    var RE = /(.*?\|.*?\()(\d+?)(\).*\()(\d+?)(\).*)/;
    $('a[data-text]').each(function(index, value){
      var data_text = $(value).attr('data-text');
      if (data_text.indexOf('买入债权') === 0){
        data_text = data_text.replace(RE, '$1<a href="http://www.yooli.com/yuexitong/detail/$2.html">$2</a>$3<a href="http://www.yooli.com/yuexitong/zhuan/$4.html">$4</a>$5');
        $(value).attr('data-text', data_text);
      }
    });
  }
};
if (YE.DEBUG){
  YE.GM_getValue = GM_getValue;
  YE.GM_setValue = GM_setValue;
  YE.GM_listValues = GM_listValues;
  YE.GM_deleteValue = GM_deleteValue;
}

function checkJquery($window){
  if (typeof $window.jQuery == 'undefined'){
    console.log("JQuery isn't exist, wait for 1s");
    window.setTimeout(run, 1000)
  }else{
    console.log("Jquery is loaded, let's rock");
    run()
  }
}

checkJquery(window)