// ==UserScript==
// @name           Ivine.uc.js
// @include        chrome://browser/content/browser.xul
// ==/UserScript==

var IrvineService = null;
(function(){
  var Cc = Components.classes;
  var Ci = Components.interfaces;
  var $A = function(a) Array.slice.call(a);

  IrvineService = {
    filename : "C:\\Program Files\\Irvine\\ircom.exe", //各自で修正してください。
    axfc : false, //わからない方はfalseで。

    // Items
    // [ id, label, oncommand]
    itemInfo : [
      ['irvine-axfcDownload','Axfc Download','IrvineService.axfcDownload();'],
      ['irvine-downloadLink','Download Link','IrvineService.downloadLink();'],
      ['irvine-downloadLinkNow','Download Link Now','IrvineService.downloadLinkNow();'],
      ['irvine-downloadLinkAs','Download Link As','IrvineService.downloadLinkAs();'],
      ['irvine-downloadLinkWithCueFolderSelect','Download Link with CueFolder Select','IrvineService.downloadLinkWithCueFolderSelect();'],
      ['irvine-downloadSelection','Download Selection Link','IrvineService.downloadSelection();'],
      ['irvine-downloadLinkWithSetting','Download Link with Setting','IrvineService.downloadLinkWithSetting();'],
      ['irvine-downloadAllLinks','Download All Links','IrvineService.downloadAllLinks();'],
      ['irvine-downloadAllLinksAndImages','Download All Links (and Images)','IrvineService.downloadAllLinksAndImages();'],
      ['irvine-importLinks','Import Link','IrvineService.importLinks();']
    ],

    get UConv(){
      if(!this._UConv){
        this._UConv = Cc['@mozilla.org/intl/scriptableunicodeconverter'].getService(Ci.nsIScriptableUnicodeConverter);
      }
      return this._UConv;
    },

    _UConv: null,

    get locationDocument() document.popupNode.ownerDocument,

    get onLink() gContextMenu.onSaveableLink || gContextMenu.onImage,

    get linkURI() (gContextMenu.onSaveableLink) ? gContextMenu.linkURL : (gContextMenu.onImage) ? gContextMenu.imageURL: null,

    get linkURIs() $A(this.locationDocument.links).map(function(link) link.href ),

    get imageURIs() $A(this.locationDocument.images).map(function(img) img.src ),

    get linkText(){
      if(gContextMenu.onSaveableLink){
        this.UConv.charset = 'Shift_JIS';
        var text = gContextMenu.linkText;
        text = this.UConv.ConvertFromUnicode(text);
        return text;
      } else return '';
    },

    get selectionText() this.locationDocument.defaultView.getSelection().toString(),

    get locationURI() this.locationDocument.location.href,


    downloadLink : function(){
      var url = this.linkURI;
      if(url) this.createObject('Download',[url,0]);
    },

    downloadLinkNow : function(){
      var url = this.linkURI;
      if(url) this.createObject('Download',[url,3]);
    },

    downloadLinkAs : function(){
      var url = this.linkURI;
      if(url) this.createObject('Download',[url,1]);
    },

    downloadLinkWithCueFolderSelect : function(){
      var url = this.linkURI;
      if(url) this.createObject('Download',[url,2]);
    },

    downloadSelection : function(){
      var text = this.selectionText;
      if(text) this.createObject('Download',[text,0])
    },

    downloadLinkWithSetting : function(){
      var url = this.linkURI;
      if(url){
        url = 'Url=' + url + "\n" +
          'Referer=' + this.locationURI + "\n" +
          'Comment=' + this.linkText + "\n";
        this.createObject('CreateQueueItem',[url,false]);
      }
    },

    downloadAllLinks : function(){
      var urls = this.linkURIs.join("\n");
      if(urls) this.createObject('AddUrlAndReferer',[urls,this.locationURI,1]);
    },

    downloadAllLinksAndImages : function(){
      var links = this.linkURIs;
      var images = this.imageURIs;
      var urls = links.concat(images).join("\n");
      if(urls) this.createObject('AddUrlAndReferer',[urls,this.locationURI,1]);
    },

    importLinks : function(){
      if(this.onLink){
        var url = this.linkURI;
        if(url) this.createObject('ImportLinks',[url,0]);
      } else{
        var urls = this.linkURIs.join("\n");
        if(urls) this.createObject('ImportLinks',[urls,0]);
      }
    },
    axfcDownload : function(){
      var doc = this.locationDocument;
      var url = this.locationURI;
      var p = $A(doc.forms[0].getElementsByTagName('input')).map(function(e) e.name + '=' + e.value ).join('&');
      this.UConv.charset = 'Shift_JIS';
      p = this.UConv.ConvertFromUnicode(p);
      this.createObject('Download',[url+'@'+p, 0]);
    },

    createObject : function(aMethodName, aParams){
      var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsILocalFile);
      var process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess);
      file.initWithPath(this.filename);
      process.init(file);
      var args = ['-object', 'Irvine.Api', '-method', aMethodName].concat(aParams);
      process.run(false, args, args.length, {});
    },

    run : function(){
      var m = document.createElement('menu');
      var mpopup = document.createElement('menupopup');
      m.setAttribute('id', 'irvine-menu');
      m.setAttribute('label', 'Irvine');
      mpopup.setAttribute('id', 'irvine-popup');
      mpopup.setAttribute('onpopupshowing', 'IrvineService.initItems();');
      var cacm = document.getElementById('contentAreaContextMenu');
      cacm.appendChild(m);
      m.appendChild(mpopup);
      this.itemInfo.forEach(function(info) mpopup.appendChild(createItem(info)) );

      function createItem([id, label, command]){
        var item = document.createElement('menuitem');
        item.setAttribute('id', id);
        item.setAttribute('label', label);
        item.setAttribute('oncommand', command);
        return item;
      }
    },

    initItems : function(){
      var show = this.onLink;
      var axfc = false;
      if(this.axfc) axfc = /axfc\.net/.test(this.locationURI);
      gContextMenu.showItem('irvine-axfcDownload', axfc);
      gContextMenu.showItem('irvine-downloadLink', show);
      gContextMenu.showItem('irvine-downloadLinkNow', show);
      gContextMenu.showItem('irvine-downloadLinkAs', show);
      gContextMenu.showItem('irvine-downloadLinkWithCueFolderSelect', show);
      gContextMenu.showItem('irvine-downloadLinkWithSetting', show);
      gContextMenu.showItem('irvine-downloadSelection', gContextMenu.isTextSelected);
    }
  };
  IrvineService.run();

})();
