// ==UserScript==
// @name           Replace Wangwang Link
// @namespace      http://by-igotit.com
// @include        htt*://*.taobao.com/*
// @include        htt*://*.alipay.com/*
// @include        http://*.taojapan.com/*
// ==/UserScript==

/* last updated: 2010/07/20 */

hasModified = false;

document.addEventListener('mouseover', function() {
  
  if(!hasModified){
    
    function modifyTag(args) {
      var s = document.evaluate(
          args.path,
          document,
          null,
          XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
          null);
      
      for(var i = 0; i < s.snapshotLength; i++){
        args.handler(i, s);
      }
    }
    
    // search/fav/logistics page
    modifyTag({
      path : "//span[@class='ww:token wwicon'] | //span[@class='ww:token']",
      handler : function(i, s) {
        var node = s.snapshotItem(i);
        var o = node.getAttribute('ww:params');
        var nick = '';
        var gid = '';
        
        var p = /nick=([^&]*)/;
        if( p.test(o) ){
          var match = p.exec(o);
          nick = match[1];
        }
        p = /item=([^&]*)/;
        if( p.test(o) ){
          var match = p.exec(o);
          gid = match[1];
        }
        
        var link = 'aliim:sendmsg?touid=cntaobao'+nick+'&siteid=cntaobao&gid='+gid;
        
        replaceLink(node, link)
      }
    });
    
    // item/store/bought page
    modifyTag({
      path : "//span[@data-nick]",
      handler : function(i, s) {
        var node = s.snapshotItem(i);
        var nick = node.getAttribute('data-nick');
        var href = node.firstChild.getAttribute('href');
        var gid = '';
        var p = /gid=([^&]*)/;
        if(p.test(href)){
          var match = p.exec(href);
          gid = match[1];
        } else if (node.hasAttribute('data-item')) {
          var item = node.getAttribute('data-item');
          gid = item.split(':')[0];
        }
        var link = 'aliim:sendmsg?touid=cntaobao'+nick+'&siteid=cntaobao&gid='+gid;
        
        replaceLink(node, link)
      }
    });
    
    // others
    modifyTag({
      path : "//a[@href]",
      handler : function(i, s) {
        var node = s.snapshotItem(i);
        var href = node.getAttribute('href');
        var p = /http:\/\/.*?im\.alisoft\.com\/.*?uid=([^&]+)&.*/;

        if( p.test(href) ) {
          var match = p.exec(href);
          var nick = match[1];
          var link = 'aliim:sendmsg?touid=cntaobao'+nick+'&siteid=cntaobao';
          node.removeAttribute('target');
          node.setAttribute('href', link);
        }
      }
    });
    
    hasModified = true;
  }
  
  function replaceLink(node, link) {
    var oldA = node.firstChild;
    while(oldA.tagName != 'A'){
      oldA = oldA.nextSibling;
    }
    var newA = document.createElement('a');
    newA.setAttribute('href', link);
    newA.setAttribute('Class', oldA.className);
    node.replaceChild(newA, oldA);
  }
  
}, false);