var request_type;

$(document).ready(
	function(){
		console.log("INIT JQUERY");
		var $this = jQuery(".todo_plugin");
		
		$this.addClass('to-do-list-container');
		$this.wrap('<div class="plugin_wrapper"></div>');
		
		$('<h2>My to do list</h2>' +
		'<textarea class="todo_textarea"></textarea>' +
		'<input type="submit" value="add to do" class="to_do_submit" />')
		.insertBefore($this);
		
		var $submitButton = $(".to_do_submit", $this.parent());
		
		$submitButton.on("click", function(){
			console.log("click");
			sendToDo($this);
		});
	}
);


function sendToDo($el){
	var $this = $el;
	request_type = "insert";
	
	var $todoText = $this.parent().find('.todo_textarea');
	var todoText = $todoText.val();
	console.log("text: " + todoText);
	
	$todoText.val("");
	
	if (todoText.length > 2) {
		var request = $.ajax({
			url: "server/actionsObj.php",
			type: "POST",
			data: {
				"text" : todoText,
				"action" : request_type
			},
			dataType : "json"
		});
		
		request.done(function(data){
			console.log("Request done: " + data);
		});
		
		request.fail(function(xhr, textStatus){
			console.log("Request failed: " + textStatus);
		});
	}
	
}
