//NEED TO SET UP A LAST USED FIELD
//Add another note id field so users notes always start at 1
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
var breakAfter = 32;
        input = Base64._utf8_encode(input);
myy = 0;
        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
myy = myy +4;
if(myy%breakAfter == 0)
output = output + "\n";
        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        var breakAfter=10;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

var gmtUtils = {
    
    save_to_clipboard: function(input) {
        var copied = false;
        try {
          if(input) {
            Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper).copyString(input);
            copied =true;
          }
          else {
              displayMessage(input);
          }
        }
        catch(e) {
          displayMessage("There was a problem trying to copy the note to your clipboard.");
          displayMessage(e);
        }
        return copied;
      }
}

var noun_type_mynotesaccount = {
    _name: "username and password",
    
    getName: function() {
    	if(Application.prefs.has("mynotes_user"))
         {
            return Application.prefs.get("mynotes_user").value;
         }
         else
         {
           return false;
         }
    },
    hasKey: function(key) {
      return Application.prefs.has(key);
    },
    getKey: function(key) {
         if(Application.prefs.has(key))
         {
            return Application.prefs.get(key).value;
         }
         else
         {
           return "Account not set";
         }
    },
    setKey: function(key, val) {
    
    	//var url = "http://localhost/Dropbox/WP/ubiquity/mynotes/notes.php";//?op=check&u="+key+"&p="+val;
    	var url="http://colddish.gmtaz.com/ubiquity/mynotes/notes.php";
    	jQuery.post(url, {op:"check",u: key, p:val}, function(data){
    		if(data.validation == "true")
    		{
		        if (!Application.prefs.has(key)) 
		        {
		            Application.prefs.setValue(key, val);
		            Application.prefs.setValue("mynotes_user", key);
		            displayMessage("New account created for \""+key+"\".");
		        } 
		        else 
		        {
		            var new_key = Application.prefs.get(key);
		            Application.prefs.setValue("mynotes_user", key);
		            new_key.value = val;
		            displayMessage("Ubiquity MyNotes configured for \""+key+"\".");
		        }
		    } 
		    else
		        displayMessage("Invalid username or password. Please try again or register using the 'mynotes-register' command.");
    	}, "json");
    

    },
    register: function(key,val) {
    //register
    	//var url = "http://localhost/Dropbox/WP/ubiquity/mynotes/notes.php";  // ?op=register&u="+key+"&p="+val;
    	var url="http://colddish.gmtaz.com/ubiquity/mynotes/notes.php";
    	jQuery.post(url, {op:"register",u: key, p:val}, function(data){
    		if(data.registerResponse == key)
    		{
		        if (!Application.prefs.has(key)) 
		        {
		            Application.prefs.setValue(key, val);
		            Application.prefs.setValue("mynotes_user", key);
		            displayMessage("New account created for \""+key+"\".");
		        } 
		        else 
		        {
		            var new_key = Application.prefs.get(key);
		            Application.prefs.setValue("mynotes_user", key);
		            new_key.value = val;
		            displayMessage("Password set for \""+key+"\".");
		        }
		    } 
		    else
		        displayMessage("Username is already in use.  Please try again.");
    	}, "json");
    
    },
    suggest: function(text, html) {
        var suggestions = [];
        var key = Application.prefs.get("mynotes_account");
        return key.value;
    }
}



/* This is a template command */
CmdUtils.CreateCommand({
  name: "mynotes",
  icon: "http://example.com/example.png",
  homepage: "http://colddish.gmtaz.com/ubiquity/mynotes/",
  author: { name: "Gustavo", email: "gmt@gmtaz.com"},
  license: "GPL",
  description: "personal notes system",
  help: "mynotes, mynotes delete {id}: delete note of ID {id}, mynotes add {note text}: adds new note.",
  takes: {" delete or add ": noun_arb_text },
  preview: function( pblock, input ) {
    // var host = "http://localhost/Dropbox/WP/ubiquity/mynotes/"
    var host = "http://colddish.gmtaz.com/ubiquity/mynotes/";
    var username = noun_type_mynotesaccount.getName();
    if(!username)
    {
   		pblock.innerHTML = CmdUtils.renderTemplate("You must run mynotes-setup-account first.");
   		displayMessage("You must run mynotes-setup-account first.");
    }
    else
    {
    var user = "&u="+username;
    var url = host + "notes.php";//?op=get"+user;
    var isplit = input.text.split(" ", 2);
    var sc=isplit[0];
    if(input.text.indexOf(" ")>0)
      isplit[1] = input.text.substring(input.text.indexOf(" ")+1,input.text.length);
    var html="<div style=\"color:#999;padding-bottom:10px;\">Commands: <i>delete {id}</i>, <i>add {text}</i></div>";
    //get list
    jQuery.post(url,{op:"get",u: username}, function( data ) {
          if(sc=="add")
              {
                  if(isplit[1])
                      html+="<div style=\"padding-bottom:10px;\">Add \""+ isplit[1] +"\" to notes?</div>";  
              }
	      else if(sc=="delete")
	      {
	          url= host + "notes.php";//?op=delPreview&id="+isplit[1]+user;
	          if(isplit[1])
	          {
	              jQuery.post(url,{op:"delPreview",id: isplit[1], u:username }, function( data ) {
		            if(data.items.length>0)
		            {
		              jQuery.each(data.items, function(i,item){
		              html+="<div style=\"padding-top:10px;\">Delete \""+Base64.decode(item.note)+"\"?</div>";
		              });
		            }
		            else
		            {
		              html+="<div>Invalid note ID entered.  The ID is the number listed inside the parenthesis.<div>";
		              html+="<div> (<span style=\"color:red;\">ID</span>) This is my note text. </div>" ;
		            } 
		            pblock.innerHTML = CmdUtils.renderTemplate(html);		            
	            }, "json");
	          }
	      }
			//show notes (decode b64)
	      jQuery.each(data.items, function(i,item){
	        var note64="";
	        note64 = Base64.decode(item.note);
	        html+= '<div style="padding-bottom:5px;">('+
	            item.id+')<span style="padding-left:5px;">'+
	          note64+'</span></div>';
	      });
	      pblock.innerHTML = html;
    }, "json");
   	pblock.innerHTML = CmdUtils.renderTemplate(html);
   }
  },
  execute: function(input) {
    var isplit = input.text.split(" ", 2);
    var sc=isplit[0];
    if(input.text.indexOf(" ")>0)
      isplit[1] = input.text.substring(input.text.indexOf(" ")+1,input.text.length);
      //var host = "http://localhost/Dropbox/WP/ubiquity/mynotes/"
    var host = "http://colddish.gmtaz.com/ubiquity/mynotes/";
    var username = noun_type_mynotesaccount.getName();
    if(!username)
    {
    	pblock.innerHTML = "<div>Ubiquity MyNotes is not configured on this computer yet.</div><div>Please run 'mynotes-register' for a new account or mynotes-setup to add an already registered account to this machine.</div>"
    }
    else
    {	    
	    var user = "&u="+username;
	    var url = host + "notes.php"//?op=get"+user;
	    var prevListLength = 0;
	    jQuery.post(url, {op:"get",u:username} ,function( data ) {
	        prevListLength = data.items.length;
	    }, "json");
	    if(isplit[1].length>0)
	    {
	        url=host+"notes.php";//?op="+sc+user;
	        if(sc=="delete")
	        {
	            //var urlPrev = host + "notes.php"//?op=delPreview&id=" + isplit[1]+user;
	            var noteText="";
	            jQuery.post(url, {op:"delPreview",id:isplit[1], u:username} ,function( data ) {
	                noteText = Base64.decode(data.items[0].note);
		            jQuery.post(url,{op:sc,id:isplit[1], u:username},function( data ) {
		              if(gmtUtils.save_to_clipboard(noteText))
		                  displayMessage('Note deleted from MyNotes and copied to clipboard.');
		              else
		                  displayMessage('Note deleted from MyNotes but there was an error copying it to the clipboard.');
		            }, "json");
	            }, "json");
	          //delete note of id = isplit[1]
	              //url+="&id="+isplit[1]+user;
	            
	        }
	        if(sc=="add")
	        {
	          //add new note
	          //encode base64
	          var note64 = Base64.encode(isplit[1]);          
	          //url+= "&note="+note64;
	          jQuery.post(url,{op:sc, note:note64 , u:username} ,function( data ) {
	          });
	          displayMessage('Saved successfully!');
	        }
	    }
    }
  }
});

CmdUtils.CreateCommand({
  name: "mynotes-setup",
  takes: {"username password": noun_arb_text, "user_api_key": noun_type_mynotesaccount},
  homepage: "http://colddish.gmtaz.com/ubiquity/mynotes/",
  author: {name: "Gustavo Tandeciarz", homepage: "http://gmtaz.com"},
  license: "MPL",
  description: "Give another computer access to your MyNotes notes.",
  help: "Type username and password to set up your account info for ubiquity.  MyNotes will always use this account for the mynotes command.",
  
  preview: function(pblock, input) {
   
    var username = input.text.split(" ")[0];
    var preview="";
    if(username.length>0)
    {
	    var password = noun_type_mynotesaccount.getKey(username);
	    preview = "<div>Ubiquity MyNotes will be set up for "+
	    username+ "</div><div>Please enter a password.</div>";
	    if(input.text.split(" ",2).length == 2) {
	      preview = "<div>Configure Ubiquity MyNotes to use username: "+username+"</div>";
	      
	    }
    }
	else
	{
		preview = "<div>This is the setup command for Ubiquity MyNotes.  This command is only used to give another computer access to your notes. If you don't have an account created yet, please run 'mynotes-register' to create an account.  You DO NOT need to run 'mynotes-setup after running 'mynotes-register'.</div>";
	}

    pblock.innerHTML = preview;


  },
  
  execute: function(input) {
    if(input.text.split(" ").length < 2) {
      displayMessage("This command requires a username AND password.");
      return;
    }
    var username = input.text.substr(0, input.text.indexOf(" "));
    var password = input.text.substring(input.text.indexOf(" ")+1,input.text.length);
    noun_type_mynotesaccount.setKey(username, Base64.encode(password));
    
  }
});

CmdUtils.CreateCommand({
  name: "mynotes-register",
  takes: {"username password": noun_arb_text, "user_api_key": noun_type_mynotesaccount},
  homepage: "http://colddish.gmtaz.com/ubiquity/mynotes/",
  author: {name: "Gustavo Tandeciarz", homepage: "http://gmtaz.com"},
  license: "MPL",
  description: "Register a new MyNotes account.",
  help: "Type username and password to set up your account info for MyNotes.  MyNotes will always use this account for the 'mynotes' command.",
  
  preview: function(pblock, input) {
   
    var username = input.text.split(" ")[0];
    var password = input.text.substring(input.text.indexOf(" ")+1,input.text.length);
    var preview = "<div>This will register you with a new account for Ubiquity MyNotes.  Please note that after this completes, you DO NOT need to run 'mynotes-setup' on this computer unless you want to change the account.  <br />To set up Ubiquity MyNotes on another computer with access to notes added under this account, you must run 'mynotes-setup <i>username password</i> on that computer.";
    
    if(input.text.split(" ",2).length == 2) {
      preview = "<div>Set up a MyNotes account using<div>username: "+username+"</div><div>password: "+input.text.split(" ",2)[1]+"</div></div>";
      
    }


    pblock.innerHTML = preview;


  },
  
  execute: function(input) {
    if(input.text.split(" ").length < 2) {
      displayMessage("This command requires a username AND password.");
      return;
    }
    var username = input.text.substr(0, input.text.indexOf(" "));
    var password = input.text.substring(input.text.indexOf(" ")+1,input.text.length);
    noun_type_mynotesaccount.register(username, Base64.encode(password));
    //displayMessage is handled by the register function
  }
});

