(function($){
    $.fn.setCursorToTextEnd = function() {
        $initialVal = this.val();
        this.val($initialVal + ' ');
        this.val($initialVal);
    };
})(jQuery);

function regisHistory(id, page)
{
	$.ajax({
		url: '/frontend/user/regis_history/'+id +'/page/'+page,
		type: 'POST',
		success: function(data)
		{
			results = jQuery.parseJSON(data);
			paging = results.paging;
			result = results.packagelogs;
			content = "";
			if(result.length>0){
				for (var i in result)
				{
					content += '<tr><td class="center">'+result[i].source+'</td><td class="center">'+result[i].p_name+'</td><td>'+result[i].created_time+'</td></tr>';
					
				}
			}else
			{
				content += '<tr><td class="center" colspan=3>Chưa đăng kí gói dịch vụ nào!</td></tr>';
			}
			$("#user-history").find("#content-regis-histoty").html(content);
			$("#user-history").find("#regis-pagination").html(paging);
			$("#regis-pagination .ajax_paging").click(function ()
			{
				$.ajax({
					url: $(this).attr("href"),
					type: "POST",
					success: function (data, textStatus, jqXHR)
					{
						results = jQuery.parseJSON(data);
						regisHistory(id, results.current_page);
					},
					error: function ()
					{
						$(".ajaxloading").hide();
					}
				});
				return false;
			});
			
		}
	});
}

function tradeHistory(id, page)
{
	$.ajax({
		url: '/frontend/user/trade_history/'+id +'/page/'+page,
		type: 'POST',
		success: function(data)
		{
			results = jQuery.parseJSON(data);
			paging = results.paging;
			result = results.paidlogs;
			content = "";
			if(result.length>0){
				for (var i in result)
				{
					content += '<tr><td class="center">'+result[i].source+'</td><td class="center">'+result[i].amount+'</td><td>'+result[i].paid_time+'</td></tr>';
					
				}
			}else
			{
				content += '<tr><td class="center" colspan=3>Chưa có giao dịch nào!</td></tr>';
			}
			$("#user-history").find("#content-trade-histoty").html(content);
			$("#user-history").find("#trade-pagination").html(paging);
			$("#trade-pagination .ajax_paging").click(function ()
			 {
				$.ajax({
					url: $(this).attr("href"),
					type: "POST",
					success: function (data, textStatus, jqXHR)
					{
						results = jQuery.parseJSON(data);
						tradeHistory(id, results.current_page);
					},
					error: function ()
					{
						$(".ajaxloading").hide();
					}
				});
				return false;
			 });
			
		}
	});	
}

function getUserHistory(id, page)
{
	regisHistory(id, page);
	tradeHistory(id, page);
	$("#user-history").modal('show');
}