/*
  * V1.0.1 2008/09/01
  * V1.0.2 2008/09/26 加入plurk指令
  * V1.0.3 2008/09/27 改進plurk, 在開頭加入qualifier動詞
  * V1.0.4 2008/09/28 改進plurk, qualifier動詞-語系, 如loves-cn, loves-en
  * V1.0.5 2008/10/07 改進plurk, 簡訊裡用%l則自動替換當頁網址
  * V1.0.6 2008/10/17 fix: "dict"命令傳遞中文時之錯誤
  * V1.0.7 2008/10/17 加入books指令，執行博客來關鍵字搜尋
  * V1.0.8 2008/10/25 Keyscape: 把Google的搜尋結果項目加上1-10的數字, 用按鍵取代Click
  */
CmdUtils.CreateCommand({
  names: ["funp"],
  author: {name: "emisjerry", email: "emisjerry@gmail.com"},
  license: "GPL",
  description: "選取好描述文字，把本篇文章貼上推推王",
  //takes: {"輸入標籤名稱": noun_arb_text},
  arguments: [ {role: 'object', nountype: noun_arb_text, label: "輸入標籤名稱: "} ],
  icon: "http://funp.com/favicon.ico",
  execute: function({modifier}) {
    var _sSelection = CmdUtils.getSelection();
    //window.alert(_sSelection + ':' + context.focusedWindow.location.href);
    var _aTags = modifier.text.split(" ");  // 把輸入字串分成陣列
    var _sTags = "";
    for (var ele in _aTags) {
      _sTags += "&tags[]=" + encodeURIComponent(_aTags[ele]);
    }
    if (_sTags == "") _sTags = "&tags[]=科技";  // 未輸入標籤則預設為科技
    else _sTags = _sTags.replace(/tech/, '科技');  // 把tech標籤換成科技, 加快輸入速度
    Utils.openUrlInBrowser("http://funp.com/push/submit/?popup&url=" +
      encodeURIComponent(context.focusedWindow.location.href) +
      "&t="+encodeURIComponent(_sSelection)+_sTags);
  }
});

/*
# CmdUtils.CreateCommand({  
#   names: ["findbook"],  
#   contributors: ["elleryq"],  
#   license: "MPL",  
#   description: "讓買書變成更簡單的決定！",  
#   arguments: [ {role: 'object', nountype: noun_arb_text, label: '書名關鍵字'} ],  
#   icon: "http://findbook.tw/favicon.ico",  
#   execute: function(args) {  
#     Utils.openUrlInBrowser( "http://findbook.tw/search?keyword_type=keyword&q=" + encodeURIComponent(args.object.text) );  
#   }  
# }) 
*/
CmdUtils.CreateCommand({
  names: ["dict"],
  author: { name: "emisjerry", email:"emisjerry@gmail.com"},
  contributors: ["emisjerry"],
  license: "GPL",
  description: "Yahoo!奇摩字典",
  //takes: {"要翻譯的字彙": noun_arb_text},
  arguments: [ {role: 'object', nountype: noun_arb_text, label: "Words: "} ],
  icon: "http://tw.dictionary.yahoo.com/favicon.ico",
  execute: function(args) {
    Utils.openUrlInBrowser("http://tw.dictionary.yahoo.com/search?ei=UTF-8&p=" + 
      encodeURIComponent(args.object.text));
  }
});

CmdUtils.CreateCommand({
  names: ["cdic"],
  author: { name: "emisjerry", email: "emisjerry@gmail.com"},
  contributors: ["emisjerry"],
  license: "GPL",
  description: "教育部國語辭典",
  //takes: {"要翻譯的字彙": noun_arb_text},
  arguments: [ {role: 'object', nountype: noun_arb_text, label: "要翻譯的字彙: "} ],
  //icon: "http://tw.dictionary.yahoo.com/favicon.ico",
  execute: function(args) {
    Utils.openUrlInBrowser( "http://140.111.34.46/cgi-bin/newDict/dict.sh?idx=dict.idx&pieceLen=50&fld=1&imgFont=1&cond=" +
 (args.object.text));
  }
});

/*
 * Original author: http://theunfocused.net/moz/ubiquity/verbs/, Blair McBride
 * Copied from http://www.plurk.com/user/fortelin
 * sample: plurk loves Plurking test.
 *               plurk loves-cn This is a link %l (Test page).
 */
CmdUtils.CreateCommand({
  names: ["plurk"],
  //takes: {status: noun_arb_text},
  homepage: "http://theunfocused.net/moz/ubiquity/verbs/",
  //author: {name: "Blair McBride", homepage: "http://theunfocused.net/"},
  //modifier: {name: "Jerry Chien"},
  license: "MPL",
  preview: function(previewBlock, {modifier}) {
    var previewTemplate = "將要發佈的內容如下: <br/>" +       
                          "<b>${status}</b><br /><br />" + 
                          " 總字數為: <b>${chars}</b>";
    var truncateTemplate = "<br />後面 <b>${truncate}</b> " + 
                           "個字將予以刪除!";
    var previewData = {
      status: modifier.text,
      chars: modifier.text.length
    };
      
    var previewHTML = CmdUtils.renderTemplate(previewTemplate,
                                                    previewData);
    
    if(previewData.chars > 140) {
      var truncateData = {
        truncate: previewData.chars - 140
      };
      
      previewHTML += CmdUtils.renderTemplate(truncateTemplate,
                                                   truncateData);
    }
    
    previewBlock.innerHTML = previewHTML;
  },
  
  execute: function({modifier}) {
  	var _sText = modifier.text;
    if(_sText.length < 1) {
      displayMessage("Plurk 內容不可空白");
      return;
    }
    var _sQualifier = "says";
    var _sLang = "tr_ch";  // 預設為繁體中文
    var _iIndex = _sText.indexOf(" ");
    var found = false;
    if (_iIndex > 0) {
      var _aQualifiers = ["loves","likes","shares","gives","hates","wants",
        "wishes","has","will","wonders","asks","was","feels","thinks","says","is"];
      var _sVerb = _sText.substring(0, _iIndex);  // 要使用的qualifier
      var _iIndex2 = _sVerb.indexOf("-");  // loves, loves-tw, loves-cn, loves-en, 減號後面加語系
      if (_iIndex2 > 0) {
        var _sVerbLang = _sVerb.substring(_iIndex2+1).toLowerCase();
        if (_sVerbLang=="tw") _sLang = "tr_ch";
        else _sLang = _sVerbLang;
        
        _sVerb = _sVerb.substring(0, _iIndex2);  // loves-cn ==> loves
      }
      for (var ele in _aQualifiers) {
        if (_sVerb==_aQualifiers[ele]) {
          found = true;
          _sQualifier = _sVerb;
          _sText = _sText.substring(_iIndex+1);
          break;
        }
      }
    }
    // 自動替換目前頁面的網址之處理
    var _aKeywords = ["%l", "%link", "%url"];  // 可使用的3種關鍵字串 
    var _sKeyword = "";
    for (var i in _aKeywords) {
      _iIndex = _sText.indexOf(_aKeywords[i]);
      if (_iIndex >= 0) {
        _sKeyword = _aKeywords[i];
        break;
      }
    }
    if (_sKeyword != "") {
      var _sURL = context.focusedWindow.location.href;
      _sText = _sText.replace(_sKeyword, _sURL);  // 關鍵字串換成網址
    }
    
    var updateUrl = "http://www.plurk.com/TimeLine/addPlurk";
    var updateParams = {
      uid: 3170067,
      qualifier:_sQualifier,
      lang:_sLang,  // en
      content: _sText
    };
    
    jQuery.ajax({
      type: "POST",
      url: updateUrl,
      data: updateParams,
      dataType: "json",
      error: function() {
        displayMessage("Plurk 發佈錯誤");
      },
      success: function() {
        displayMessage("Plurk 發佈成功");
      }
    });
  }
});

CmdUtils.CreateCommand({
  name: ["books"],
  author: { name: "emisjerry", email:"emisjerry@gmail.com"},
  license: "GPL",
  description: "博客來關鍵字搜尋\n",
  //takes: {"要查詢的商品": noun_arb_text},
  arguments: [ {role: 'object', nountype: noun_arb_text, label: "要查詢的商品"} ],
  icon: "http://www.books.com.tw/favicon.ico",
  execute: function(args) {
    Utils.openUrlInBrowser("http://search.books.com.tw/exep/prod_search.php?cat=all&key=" + 
      encodeURIComponent(args.object.text));
  }
});

CmdUtils.CreateCommand({
  name: ["k+"],
  author: { name: "emisjerry", email: "emisjerry@gmail.com"},
  license: "GPL",
  description: "Yahoo!知識+搜尋",
  //takes: {"要搜尋的內容": noun_arb_text},
  arguments: [ {role: 'object', nountype: noun_arb_text, label: "要搜尋的內容"} ],
  icon: "http://www.books.com.tw/favicon.ico",
  execute: function({modifier}) {
    Utils.openUrlInBrowser("http://tw.knowledge.yahoo.com/search/search_result?p=" + 
      encodeURIComponent(modifier.text));
  }
});

CmdUtils.CreateCommand({
  names: ["jmp"],
  arguments: noun_type_url,
  icon: "http://j.mp/favicon.ico",
  description: ("Replaces the selected URL with a " +
                "<a href=\"http://j.mp\">j.mp</a>."),
  preview: function(pblock, {object: {text}}){
    if (!text) {
      pblock.innerHTML = this.description;
      return;
    }
    var me = this;
    pblock.innerHTML = _("Replaces the selected URL with...");
    CmdUtils.previewGet(pblock, this._api(text), function(j.mp) {
      if(j.mp !== "Error")
        pblock.innerHTML = _("Replaces the selected URL with <b>${j.mp}</b>.",
                             {j.mp:me._link(j.mp)});
    });
  },
  execute: function(args) {
    var me = this;
    jQuery.get(this._api(args.object.text), function(j.mp) {
      CmdUtils.setSelection(me._link(j.mp), {text: j.mp});
      Utils.clipboard.text = j.mp;
    });
  },
  _api: function(url)("http://j.mp?url=" +
                      encodeURIComponent(url)),
  _link: function(url) {
    var eu = Utils.escapeHtml(url);
    return eu.link(eu);
  },
});


makeSearchCommand({
  name: ["google-tw"],
  author: { name: "emisjerry", email: "emisjerry@gmail.com"},
  url: "http://www.google.com.tw/search?hl=zh-TW&q={QUERY}",
  icon: "http://www.google.com.tw/favicon.ico",
  homepage: "http://blog.xuite.net/emisjerry/tech",
  license: "GPL",
  description: "Google Taiwan"
}); 

CmdUtils.CreateCommand({
  name: ["en2zh"],
  icon: "http://www.google.com/favicon.ico",
  description: "將目前網頁翻譯為中文",
  execute: function() {
    var word = context.focusedWindow.document.location;
      Utils.openUrlInBrowser( "http://translate.google.com/translate?sl=en&tl=zh-TW&hl=zh-TW&ie=UTF-8&u=" + 
        escape(word) );
  },
  preview : function(obj){
    obj.innerHTML = "將目前網頁翻譯為中文";
  }
});

