/*
 * Bugmenot.js: For Ubiquity Parser 2
 *
 * Thank you all for using bugmenot.js.
 * Thank you Heater Kofke-Egger for notifying me about parser 2.0 changes.
 * Also thank you Brandon Goldsworthy for updating this command.
 *
 *
 * This file has been modified from Onur Yalazi's original distribution
 * by Brandon Goldsworthy.
 *
 * Changes:
 *   Added a preview. The preview shows all of bugmenot's results,
 *     though execute will still only insert the highest rated one.
 *   Use current window location as default url for both preview and execute
 *   Add error callback to jQuery call to bugmenot's page.
 *   If not in editable field, opens bugmenot in new tab
 *
 * Onur's original attribution info is left in-tact below.
 * You can get his original file there.
 *
 *
 * Changelog:
 * 2009-07-16 Onur YALAZI <yalazi@mobilada.com> 
 * 	bugmenot-p2.js:  modified for parser 2.0
 *            		 added new synonym bmn
 */

CmdUtils.CreateCommand({
  names: [ "bugmenot", "bmn" ],
  arguments: [ { role: 'object', nountype: noun_type_url, label: 'url'} ],
  homepage: "http://www.yalazi.org/ubiquity",
  author: { name: "Onur YALAZI", email: "yalazi@mobilada.com"},
  contributors: [ "Brandon Goldsworthy" ],
  license: "MPL",
  description: "modified by Brandon Goldsworthy. Get password for current page or entry from bugmenot.com. Command from Onur YALAZI",
  help: "If you're in an editable text area, inserts username:password double",

  _decodeIt: function(data,key) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o11 = "";var o21 = ""; var o31 = "";
    var h11 = "";var h21 = ""; var h31 = "";var h41 = "";
    var bits1 = ""; var i1 = 0; var enc1 = "";

    do {
      h11 = b64.indexOf(data.charAt(i1++));
      h21 = b64.indexOf(data.charAt(i1++));
      h31 = b64.indexOf(data.charAt(i1++));
      h41 = b64.indexOf(data.charAt(i1++));
      bits1 = h11 << 18 | h21 << 12 | h31 << 6 | h41;
      o11 = bits1 >> 16 & 255;
      o21 = bits1 >> 8 & 255;
      o31 = bits1 & 255;
      if (h31 == 64) {
        enc1 += String.fromCharCode(o11);
      } else if (h41 == 64) {
        enc1 += String.fromCharCode(o11, o21);
      } else {
        enc1 += String.fromCharCode(o11, o21, o31);
      }
    } while (i1 < data.length);


    strInput = enc1;
    strOutput = "";
    intOffset = (key + 112) / 12;
    for (i1 = 4; i1 < strInput.length; i1++) {
      thisLetter = strInput.charAt(i1);
      thisCharCode = strInput.charCodeAt(i1);
      newCharCode = thisCharCode - intOffset;
      strOutput += String.fromCharCode(newCharCode);
    }
    return strOutput;
  },
  _inField: function(){
      //gleaned from CmdUtils.setSelection
      return context.focusedWindow.document.designMode == "on" ||
             (context.focusedElement && context.focusedElement.selectionStart >= 0);
  },
  _getPassword: function(urlAddress, parent, pblock) {

    var baseUrl = "http://www.bugmenot.com/view/" + urlAddress.text;

    if (!pblock && !this._inField()){
        Utils.openUrlInBrowser(baseUrl);

    }else{
      jQuery.ajax({
        url:baseUrl,
        error:function(){
          if (pblock){
            pblock.innerHTML += _("Passwords not found.") + "<br />";
          }else{
            displayMessage(_("Passwords not found."));
            CmdUtils.setSelection(_("Passwords not found."));
          }
        },
        success:function( passwords ) {
          key = parseInt(passwords.match(/key.=.([0-9]*)/)[1]);
          var result = "";

          arrayToWork = passwords.split("<div class=\"account\"");
          if (arrayToWork.length && arrayToWork.length > 1) {
            o_password = "";
            o_username = "";
            o_rate = 0;

            for (i=0;i<arrayToWork.length; i++) {
              if (pair = arrayToWork[i].match(/d\('(.*)'\)/g)) {

                rate = parseInt(arrayToWork[i].match(/[0-9]{1,3}%/));

                username = pair[0].match(/'(.*)'/)[1];
                username = parent._decodeIt( username, key );

                password = pair[1].match(/'(.*)'/)[1];
                password = parent._decodeIt( password, key);

                if (pblock){
                    pblock.innerHTML += rate + "%   " + username + ":" + password + "<br />";
                }

                if (rate > o_rate) {
                  o_password = password;
                  o_username = username;
                  o_rate = rate;
                }
              }
            }
            if (o_rate > 0) {
              result = o_username + ':' + o_password;
            } else {
              result = 'Passwords not found.';
              if (pblock){
                 pblock.innerHTML += _("Passwords not found.<br />");
              }
            }
          } else {
            result = 'Passwords not found.';
            if (pblock){
                pblock.innerHTML += _("Passwords not found.<br />");
            }
          }

          if (!pblock){
             displayMessage(result);
             CmdUtils.setSelection(result);
          }
        }
      });
    }
  },
  

  preview: function( pblock, args ) {
    urlAddress = args.object;
    pblock.innerHTML = "";
    if (urlAddress.text.length < 1){
       urlAddress.text = String(Application.activeWindow.activeTab.document.location);
    }
    pblock.innerHTML = "Passwords for: " + urlAddress.text + "<br />";
    this._getPassword(urlAddress, this, pblock);

  },
  execute: function( args ) {
    urlAddress = args.object;
    if (urlAddress.text.length < 1){
      urlAddress.text = String(Application.activeWindow.activeTab.document.location);
    }
    this._getPassword(urlAddress, this, false);
  }
});


