function create_account(name, pass, confirm) {
  namreq("post",'/create_user',
  function(result){
      respond("User "+result.name+" created.  Please login.");
  },{'name':name,'password':pass,'password_confirmation':confirm});
}
function login(nick,pass) {
  log("login",nick,pass); 
      namreq("post",'/login',
      function(result){
          checkSession();
      },{'nick':nick,'password':pass});
}
function logout() {
  namreq("post",'/logout',function(result) {
      showWelcome();
      checkSession();
  });
}
function upcomingRecords() {
    namreq("get", "/lists/upcoming", function(data){
         
         showUpcoming(data);
    });
}

function doShowList(name) {
    log("doShowList: address.value",name);
    $.address.value(name);
}
function addType(args,func) {
    log("addType: ");
    var data = {name:args[2]};

    var content = new ContentType(args[2]);
    new content.Column("Title","text");
    nam_data.content_types.push(content);
    nam_save(content);
   
}

function addList(args,func) {
    log("add list");
    var playlist = new Playlist(args[2], currentList.content_type_id);
    if (args[3]) {
        playlist.path = args[3];
    }
    nam_data.playlists.push(playlist);
    nam_save(playlist);
}

function addRecordToPlaylist(args) {
   var playlist = getPlaylistByName(args[1]);
   var rec = currentList.currentRecord();

   playlist.records.push(rec._id);
   rec.playlists.push(playlist._id);
   
   nam_save(playlist);
   nam_save(rec);  
}
function doCode(args) {
    currentList[args[1]] = args[2];
    nam_save(currentList);
    refreshList();
}

function addRecord(data) {
    var rec = createRecord(currentList);
    currentList.table().moveCell(-currentList.x,1);
    currentList.table().refresh();
    currentList.table().editCell();
}
function timer(args) {
   var time = parseInt(args[2])*(1000*60);
   setTimeout(function() {
       alert(args[1]);
       $('#timer').html("");
   },time);
   $('#timer').html("T: "+args[1]+" in "+args[2]);
   log("Set timeout for "+args[1]+" to "+time+" millis");
}
var currentCommandMap = null;
function autoCompleter(numWords, term) {
   var data = [];
   if (numWords == 1) {
        _.each(nam_data.content_types, function(list) {
            data.push(list.name);        
        });
   }
   else if (numWords == 2) {
        _.each(nam_data.playlists, function(list) {
            data.push(list.name);        
        });
   }
   //log(numWords +", "+term);

   /*var count = 0;
   if (currentCommandMap != undefined) {
       _.each(currentCommandMap, function(value,key){
           data[count] = key;
           count++;
       });
   }
   log("auto: "+data);
   */
   /*if (term.length > 0) {
       data = _.select(data, function(datum){
          return datum.lastIndexOf(term) == 0; 
       });
   }*/
   return data;
}

function setCurrentCommandMap(key) {
    if (currentCommandMap != undefined) {
        var data = [];
        _.each(currentCommandMap, function(key, value){
               data.push(value);
       });
    //   alert(data);
       currentCommandMap = currentCommandMap[key.trim()];
    }
    
}
function quickCommand(args) {
  if (nam_auth()) {
      var list =   getContentTypeByName(args[0]);
      if (list) {
	 
	  var record = new Record(list._id);
	  
	  var ordered_columns = _.sortBy(list.columns, function(column) {return column.order;});
	  _.each(ordered_columns,function(col, index) {
	      var val = args[index+1];
	      if (val != undefined) {
		 setFieldValue(record,col, val); 
	      }
	  });

	  nam_save(record);
      }
  }
}

function playContent() {
  //use the content type to find a matching field type.  THAT is the default display.
  var default_col = currentList.getDefaultColumn();
  if (default_col != null) {
      var type = default_col.type;
      if (type == "image") {
         namnav.doFullScreen(default_col);
      }
      else if (type == "audio") {
         nam_player.playCurrentRecord();
      }
  }
  else {
      openRecord();
  }
}

function DoSetBackground(args) {
   if (currentList.getContentType().name == "Image") {
      log("Images list:",args);
      var list = getPlaylistByName(args[2]);
      log("List: ",list); 
      list.setBackground(currentList.currentRecord());
      log("list.background: "+list.background);
      currentList.refresh();
   }
   else {
      currentList.background = args[2];
      nam_save(list);  
   }
}
function DoSetPublic(args) {
   if (args[2] == "true") {
      currentList.public = true;
   }
   else if (args[2] == "false") {
      currentList.public = false;
   }
   nam_save(currentList);
}
function DoSelectListItem(args) {

    if (currentList.getContentType() == nam_data.playlist_type || currentList.getContentType() == nam_data.master_type) {
        doShowList(currentList.currentRecord().getFieldValue(currentList.currentColumn()));
    }
    else {
        if (nam_state == 'state-nav') {
            namnav.doOpenRecord();
       }
        else if (nam_state == 'state-open-record') {
            editFullScreen();
        }
    }
}

function DoClickListItem(args) {
     if (currentList.getContentType() == nam_data.playlist_type || currentList.getContentType() == nam_data.master_type) {
        var name = currentList.currentRecord().getFieldValue(currentList.currentColumn());
        doShowList(name);
    }
    else {
        playContent();
    }
   
}
function doPopList(args) {
    if (currentList.isContentList) {
        doShowList("content");
    }
    else {
        doShowList("playlists");
    }
}

function doPriv(args, func) {
    if (nam_auth()) {
        func(args);
    }
}
function escQuickEdit() {
   currentList.table().currentNamCell().html(currentList.currentRecord().getFieldValue(currentList.currentColumn()));
   setState('state-nav');
}

function editCellComplete() {
   //log("editCellComplete");
   var value = $('#text-edit').attr('value');
   value = updateField(value);

   var div = $('#text-edit').parent();
   div.html(value);
   setState('state-nav');
  
}


var commandMap = new CommandMap();
function handleCommand(args) {
    try {
        var endFunction = {};
        $.extend(true, endFunction,commandMap.any);
        if (nam_auth()) {
            $.extend(true,endFunction, commandMap.priv);
        }
        else {
            $.extend(true,endFunction, commandMap.anon);
        }
        //log("command map"+endFunction["new"]["column"]);
        for (var i = 0; i < args.length; i++){
            var prevFunc = endFunction;
            endFunction = endFunction[args[i]];
            if (typeof endFunction == 'function') {
               endFunction(args)
               i= 10000;
            }
            if (endFunction == undefined) {
                prevFunc(args);
                i = 10000; 
            }
        }
    }
    catch (e) {
        try {
            //log("second try: "+e);
            endFunction(args);
        }
        catch (f) {
            //log("third try: "+f);
            if (endFunction == null) {
                if (args.length == 1) {
                    //log("ARGS ZERO: "+args[0].trim());
                    doShowList(args[0].trim());
                }else {
                    quickCommand(args);
                }
            }
        }finally {
            escCommandLine();
        }
    }
    finally {
       // escCommandLine();
    }
    escCommandLine();
}
function CommandMap() {
   this.anon = {
       "login":function(args) {
         login(args[1],args[2]);
       }

   }
   this.any = {
      "music":{
        "play":function(args){nam_player.play();},
        "stop":function(args){nam_player.stop();}
       },
       "timer":timer
   }

   this.priv = {
    "new":{
        "column":function(args){ addColumn(args[2], args[3]);},
        "record":addRecord,
        "list":  addList,
        "type":  addType
    },
    "add-to-list":addRecordToPlaylist,
    "code":doCode,
    "remove": {
        "column":function(args) {
                     removeColumn();
                 },
        "list":function(args) {
                   alert("doesn't work");
                   //removeList(args[2]);
               }
    },
    "set": {
        "background":DoSetBackground,
        "public":DoSetPublic
    },
    
    "logout":function(args) {
         logout();
    },
    "user":function(args) {
        create_account(args[1],args[2],args[3]);
    },
    "upcoming":upcomingRecords
    
  };
}


function KeyMap(){
    this.map = {
    '58':{
             'state-nav':{'shift-mod':showCommandLine},
             'state-full-screen':{'shift-mod':showCommandLine},
             'state-open-record':{'shift-mod':showCommandLine},
             'state-edit-quick':{'shift-mod':showCommandLine}
         },
     '222':{
             'state-nav':{'shift-mod':showCommandLine},
             'state-full-screen':{'shift-mod':showCommandLine},
             'state-open-record':{'shift-mod':showCommandLine},
             'state-edit-quick':{'shift-mod':showCommandLine}
         },

    '37':{
         'state-nav':{
             'no-mod':function(){currentList.table().moveCell(-1,0);}
          },
         'state-full-screen': {
             'cntrl-mod':function() {namnav.fullScreenLeft();}
         },
         'state-open-record': {
             'cntrl-mod':namnav.editFullLeft
         }
     },
     '38':{
         'state-nav':{
             'no-mod':function(){currentList.table().moveCell(0,-1);},
             'cntrl-mod':function() {
                 //var list = getPlaylistByName("playlists 
             }
         },
         'state-full-screen': {
             'cntrl-mod':namnav.fullScreenLeft
         }, 
         'state-open-record': {
             'cntrl-mod':namnav.editFullLeft,
             'no-mod':function(){currentList.table().moveCell(-1,0);}
         },
         'state-command-line': {
             'no-mod':function(){getCommand(-1);}
         }
     },
     '39':{
         'state-nav': {
             'no-mod':function(){currentList.table().moveCell(1,0);}
         },
         'state-full-screen': {
             'cntrl-mod':namnav.fullScreenRight
         },
         'state-open-record': {
             'cntrl-mod':namnav.editFullRight
         }
     
     },
     '40':{
         'state-nav': {
             'no-mod':function(){currentList.table().moveCell(0,1);}
         },
         'state-full-screen': {
              'cntrl-mod':namnav.fullScreenRight
         },
         'state-open-record': {
              'cntrl-mod':namnav.editFullRight,
              'no-mod':function(){currentList.table().moveCell(1,0);}
         },
         'state-command-line': {
             'no-mod':function(){getCommand(1);}
         }
         
     },
     '27': {
         'state-nav': {'no-mod':doPopList},
         'state-full-screen': {'no-mod':function(){doShowList(currentList.name);}},
         'state-edit-quick':{'no-mod':escQuickEdit},
         'state-open-record':{'no-mod':function(){doShowList(currentList.name);}}
     },
     '13': {
         'state-nav': {
             'no-mod':DoSelectListItem,
             'shift-mod':function(args) {doPriv(args, currentList.table().editCell);}
         },
         'state-edit-quick': {
             'no-mod':editCellComplete
         },
         'state-open-record': {
             'no-mod':function() {namnav.doFullScreen(currentList.currentColumn());}
         }
         
     },
    '78': {
          'state-nav': {
              'cntrl-mod':function(args) {doPriv(args,addRecord);}
          }
     },
     '88':{
         'state-nav': {'cntrl-mod':function(args) {doPriv(args,removeSelectedData);}}
     },
     '79':{
         'state-nav': {'cntrl-mod':openRecord}
     },
     '70':{'state-nav':{'cntrl-mod':function() { namnav.doFullScreen(currentList.currentColumn());}},
           'state-edit-quick':{'cntrl-mod':function() { namnav.doFullScreen(currentList.currentColumn());}},
           'state-open-record':{'cntrl-mod':function() { namnav.doFullScreen(currentList.currentColumn());}}
     },
     '83':{'state-full-screen':{'cntrl-mod':function(args) {doPriv(args,namnav.fullScreenSave);}}},
     '80' :{'state-nav':{'cntrl-mod':playContent}},
     '32' :{'state-nav':{'no-mod':playContent}}
}

}
