$(function() {
	var userId = 5;
	var userIdMap = {"userId":userId};
	
	var urlvars = getUrlVars();
	var commentId = parseInt(urlvars['id'], 10);
	var commentIdMap = {"commentId":commentId};

	// populate the comment body
	$.ajax({
		url:'../dart/getComment.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(commentIdMap),
		success:function(data,textStatus,three) {
			if (textStatus==="success") {
			var body = Mustache.render($(".commentBodyTemplate").html(),data);
			$('div.comment-body').html(body);
			
			// have to set the click handler on the new button in the dom in memory
			$('div.modal-footer').on('click', 'button#submit', function(e) {
				
				var aiMap = {"commentId":commentId};
				
				aiMap['userId'] = userId;
				aiMap['text'] = $('textarea#inputMessage').val();
				
				// actually, I want this to be synchronous
				$.ajax({
					url:'../dart/saveReplyComment.json',
					type:'POST',
					async:false,
					contentType:'application/json',
					dataType:'json',
					data:JSON.stringify(aiMap),
					success:function(data,textStatus,three) {
						if (textStatus === 'success') {
							try {
								
								var loc = window.opener.location.href.lastIndexOf('communication.html');
								
								if (loc != -1) {
									window.opener.update();							
								}						
							} catch (err) {
								//alert("Could not refresh the screen - error is: " + err.message);
							}
							window.close();
						}
					}
				});
			});
			}
		}
	});

});

//Read a page's GET URL variables and return them as an associative array.
getUrlVars = function()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}