// JavaScript Document

$(document).ready(function(){
	$('div [id*="p"][class*="post"]').each(function(i){
		
		var theid = $(this).attr("id");
		
		$(this).find('*[id="diceroll"]').each(function(ii){
			
			var therollstr = $(this).text();
			$(this).text("");
			var therolldescription = $(this).attr("title");
			var gui = theid.concat(i,ii);
			$(this).attr("id",gui);
                       
			// check if it already exists
			$.ajax({
				url: "/forum/dmtools/dmtools-code.php",
			//	async: false,
				data: {function : "doesrowexist", roll_id : gui},
				dataType: "text",
                                    error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown); },
				success: function(data) {
		
					if(data == "no")
					{
						var theroll = new DiceRoll(therollstr);
						theroll.Roll();
						var loggs = ""
						//construct log message
						loggs = loggs.concat("<b style=\"color:#330000;\">" + therolldescription + "</b> - <b>", theroll.diceroll, "</b> = ", theroll.result);
						// go through each dice result to display;
						loggs = loggs.concat(" (");
						for(i = 0; i < theroll.singleDiceResult.length; i++)
						{
							loggs = loggs.concat("d", theroll.singleDiceResult[i].high, " = ", theroll.singleDiceResult[i].res);
							if(i != theroll.singleDiceResult.length-1)
								loggs = loggs.concat(", ");
						}
						loggs = loggs.concat(")");
						$.ajax({
							url: "/forum/dmtools/dmtools-code.php",
					//		async: false,
							data: {function : "inlinelog", tolog : loggs, key : gui},
							dataType: "text",
							success: function (data) {

								$.ajax({
									url: "/forum/dmtools/dmtools-code.php",
							//		async: false,
									data: {function : "getinlineroll", roll_id : gui},
									success: function(data, textstatus,jqXHR) {
										$('#'+gui).append(data);
										
									}
								});
							
							}
						});
					}
					else
					{ 
						$.ajax({
							url: "/forum/dmtools/dmtools-code.php",
					//		async: false,
							data: {function : "getinlineroll", roll_id : gui},
							dataType: "text",
							success: function(data) {
								
								$('#'+gui).append(data);
								
							}
						});
					}
				}
			});
		});
	});
});
