$(document).ready(function(){
	var valueArray = new Array();
	var step = 0;
	
	$("#widg_ID").val('0');
	
	$('#widg_ID').change(function(){
		step = 0;
		widg_ID = $("#widg_ID option:selected").val();
		valueArray = [];
		
		// reset the debugger changing the bot and resetting the step
		resetDebugger(widg_ID,step);
	});
	
	$('#sendBTN').click(function(){
	
		widg_ID = $("#widg_ID").val();
		theUserkey = $("#menu_UserKey").val();
		values = "";
		msg = $('#msg').val();
		botName = $("#widg_ID option:selected").html();
		
		if (msg != ''){
			
			valueArray.push(msg);
			
			for (var i=0; i<valueArray.length; i++) { 
			
				values = values + "," + valueArray[i]
				
			}
			
			$('.chatbox').append('<span class="you">You: </span>'+msg+'<br/>');
			$('#msg').val('');
			$('#sendBTN').attr("disabled","disabled");
			
			//send a msg to the selected bot
			$.post("/account/ajax/debugger", 
			{ "widg_ID": widg_ID,"userKey": theUserkey, "step": step, "values": values, "msg": msg},
  			function(data){
  				if (data.STATUS == 3){
			    	window.locaton.href = "/login";
			    } else
			    if (data.STATUS == 0){
			        alert(data.ERROR);
			    } else{
			        $('.chatbox').append('<span class="bot">'+botName+': </span>'+data.REPLY+'<br/><br/>');
			        
			        if(data.RESETME == 1){
			        	valueArray = [];
			        	step = 0;	
			        }
			        
			        if(data.STEP != step){

			        	step = data.STEP;
			        	
			        }
			        
			        $('.valueList').html('<strong>Name/Value pairs posted:</strong><br/><strong>userkey:</strong> '+theUserkey+'<br/><strong>network:</strong> debugger<br/><strong>msg:</strong> '+msg+'<br/>'+data.VALUES+'<strong>step:</strong> ' + step);

			        
			    }
			    
			    $('#step').val(step);
				$('.stepOut').html('<strong>Step:</strong> ' + step);
			    
			    $(".chatbox").attr({ scrollTop: $(".chatbox").attr("scrollHeight") });
			    $(".valueList").attr({ scrollTop: $(".valueList").attr("scrollHeight") });
			    
			    $('#msg').focus();
  			},"json");
			
			
			$('#sendBTN').removeAttr("disabled");
		
		}else {
			alert('Enter a message first');
		}
	
	});
	
	$('#msg').focus();
	
});

function resetDebugger(widg_ID,step){
	$('.stepOut').html('<strong>Step:</strong> 0');
	$('.chatbox').empty();
	$('.valueList').empty();
	$('#msg').focus();
}
