var apikey = 'primary';
// var apikey = 'somekey'; // Testing



$(document).ready(function() { 
   $('#chat').attr('disabled', 'disabled');
   $('#name_input').bind('keydown', function( e ) { 
      if( e.which == 13 ) { 
         set_name( $('#name_input').val() );
      }
   });
   $('#chat').bind('keydown', function( e ) { 
      if( e.which == 13 ) { 
         var msg = $('#chat').val();
         $('#chat').attr('disabled', 'disabled').val('Thinking...');
         talk_to_hal( msg );
      }
   });

});

function talk_to_hal( message ) { 
   var url = '/api/chat';
   update_conversation( message );
   $.ajax({
      type: 'POST',
      url: url,
      data: { 
         key: apikey,
         message: message
      },
      success: function( data ) { 
         console.log( 'Got a data response: ', data );
         $('#chat').removeAttr('disabled').val('');
         if( data.ok == 1 ) { 
            update_conversation( '> ' + data.reply );
         } else { 
            update_conversation( 'An error occured.  This is real bad.');
         }
      },
      dataType: 'json'
   });
}

function update_conversation( message ) {
   var c = $('#conversation');
   $('<div>' + message + '</div>').css('display', 'none').prependTo(c).fadeIn();
   fade_out_extras();
   console.log( 'Message: ', message );
}


function fade_out_extras() { 
   var c = $('#conversation');
   var ch = parseInt(c.css('height'));
   var dh = parseInt( $('#conversation div:first-child').css('height') );
   var total_divs_possible = parseInt(ch / dh) - 2;
   console.log('ch, dh:', ch, dh, 'total divs: ', total_divs_possible );
   $('#conversation div:gt(' + total_divs_possible + ')').fadeOut();
}

function set_name( name ) { 
   var name_span = $('<div class="input">' + name + '</span>');
   $('#name_input').fadeOut(function() {
      $('#name div.input').remove();
      var h = $('div#name div.label').css('height');
      $(name_span).css({
         'display': 'none',
         'height': h,
      }).appendTo('div#name ');
      $(name_span).fadeIn();
      $('#chat').removeAttr('disabled').focus();
   });
}


