(function($) {
    $.fn.onEnter = function(func) {
        this.bind('keypress', function(e) {
            if (e.keyCode == 13) func.apply(this, [e]);    
        });               
        return this; 
     };
})(jQuery);

$(function() {
	var userId = 5;
	var userIdMap = {"userId":userId};
	
	$('#third-div input#eleven').onEnter(function(){
		var key = $('#third-div input#eleven').val();
		var keyMap = {"key":key};
		keyMap['userId'] = userId;

		$.ajax({
			url:'../dart/searchRequests.json',
			type:'POST',
			contentType:'application/json',
			dataType:'json',
			data:JSON.stringify(keyMap),
			success:function(data,textStatus,three) {
				populateRequestArray(data, textStatus);			}
		});
	});
	
	$('#third-div').on('click','#twelve',function(e){
		var key = $('#third-div input#eleven').val();
		var keyMap = {"key":key};
		keyMap['userId'] = userId;
		
		$.ajax({
			url:'../dart/searchRequests.json',
			type:'POST',
			contentType:'application/json',
			dataType:'json',
			data:JSON.stringify(keyMap),
			success:function(data,textStatus,three) {
				populateRequestArray(data, textStatus);
			}
		});
	});

	// populate the user request list
	$.ajax({
		url:'../dart/getAllUserRequests.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(userIdMap),
		success:function(data,textStatus,three) {
			populateRequestArray(data, textStatus);
		}
	});
});

populateRequestArray = function(data, textStatus) {
	if(textStatus==="success" ){
		var rlist = data.requests;
		if (rlist.length > 0) {
			var tableBody = Mustache.render($(".requestRowTemplate").html(),data);
			$('#third-div table tbody').html(tableBody);
			
			$('#third-div').on('click','table button.close',function(e){
				var rid = $(this).attr('name');
				var requestIdMap = {"requestId":rid};
				requestIdMap['userId'] = userId;
				
				$.ajax({
					url:'../dart/closeRequest.json',
					type:'POST',
					contentType:'application/json',
					dataType:'json',
					data:JSON.stringify(requestIdMap),
					success:function(data,textStatus,three) {
						populateRequestArray(data, textStatus);
					}
				});
			});
			
			$('#third-div').on('click','table button.amend',function(e){
				var rid = $(this).attr('name');
				// goto another page
				alert("amend!");
				document.location='./request-amendment.html?id='+rid;
			});
		}
		else {
			$('#third-div table tbody').html('');
		}
	}
	else {
		$('#third-div table tbody').html('');
	}
};