var activityIdMap;
var requestIdMap;
var requestDocLocation;
var isReview = false;

$(function() {
	var userId = 5;
	var userIdMap = {"userId":userId};
	
	var urlvars = getUrlVars();
	var activityId = parseInt(urlvars['id'], 10);
	var requestId = parseInt(urlvars['rid'], 10);
	var reviewId = parseInt(urlvars['revid'], 10); // get the reviewId from the url param list
	
	isReview = getReviewValue( urlvars['rev'] );	//review or request (for navigation)
	
	var workflowId = parseInt(urlvars['wid'], 10); // get the workflowId from the url param list

	
	activityIdMap = {"activityId":activityId};
	requestIdMap = {"requestId":requestId};

	
	$("div.container a#history").click(function() {
		var docLocation = './history.html?id='+activityId+'&rid='+requestId+'&revid='+reviewId+'&wid='+workflowId;
		
		if( isReview )
			docLocation += '&rev=true';
		
		document.location = docLocation;
	});
	
	// grab setup info from server
	$.ajax({
		url:'../dart/setup.json',
		type:'GET',
		async:false,
		contentType:'application/json',
		dataType:'json',
		success:function(data,textStatus,three) {
			if(textStatus==="success"){
				$('header a.active').html(data.userFullName);
				userId = data.userId;
				userIdMap['userId'] = data.userId;
				
				//isDebug = data.debug;				
			}
		}
	});
	
	// populate the user request info
	$.ajax({
		url:'../dart/getActivityInfo.json',
		type:'POST',
		async:false,
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {
				
				$('div.tab-study-name div.study-name').html(data.officialName);
				
				//$('div.tab-study-name').attr('tracking-num-content',data.trackingNumber);
				$('div.well h6.tracking-number').html(data.trackingNumber);
				
				//remember the requestId (adding a new comment)
				data['requestId'] = requestId;				
				var anchorBody = Mustache.render($(".newCommentTemplate").html(),data);
				$('div.tab-study-name div.add-button').html(anchorBody);
				
				//set the "back" navigation value
				requestDocLocation = setRequestNavigation( data, activityId, requestId, reviewId, isReview, workflowId );
			}//end if
		}
	});

	
	//
	// populate the communication list (by request id)
	update();

});

//this will eventually store on to the json data full of comments and replies
var commentTableData;

var initRowKids = function(){
	//expand
	$('div.tab-study-name tbody').on('click','i.icon-caret-right', function(){
		var parent = $(this).parents('tr');
		var parentID = parent.attr("id");
		$(this).removeClass('icon-caret-right').addClass('icon-caret-down');
		
//		$(this).parents('tr').siblings(".child-"+parentID).fadeIn();	//show the children

		//show the children
		$.each(parent.siblings('tr'), function (i, val) {
			if( $(this).hasClass("child-"+parentID) ) {

				var immediateParentId = $(this).attr('data-parent');
				var immediateParent = $('tr#' + immediateParentId);

				//if the immediate parent is expanded and visible, this row should be visible
				if( immediateParent.is(':visible') ) {
					if( immediateParent.find('i').hasClass('icon-caret-down') ) {	//parent is expanded           			
						$(this).fadeIn();
					}
				}//end if
			}//end if
		});
	});
	
	//collapse
	$('div.tab-study-name tbody').on('click','i.icon-caret-down', function(){
		var parent = $(this).parents('tr');
		var parentID = parent.attr("id");
		$(this).removeClass('icon-caret-down').addClass('icon-caret-right');
		
//		$(this).parents('tr').siblings(".child-"+parentID).hide();	//hide the children
		
		//hide the children
		$.each(parent.siblings('tr'), function (i, val) {
        		if( $(this).hasClass("child-"+parentID) )
        			$(this).hide();	//hide the children
		});
	});	
};


//recursively builds the display for each comment body (including replies)
var populateBodyDisplay = function( node ) {
	
	if( node == null )
		return;

	
	//
	//build the display for this current comment
	var nodeHTML = Mustache.render($(".singleCommentBodyTemplate").html(),node);

	
	//
	//if this comment has replies, step through them
	if( node.replies != null && node.replies.length > 0 ) {
	    for( idx in node.replies ) {
	        
	        //move to the child comment	    	
	        var currChild = node.replies[idx];
	        var childCommentHTML = populateBodyDisplay( currChild );

	        //attach the child comment to the current comment (display)
	        nodeHTML += childCommentHTML;
	    }//end for
	}//end if

	
	//
	//return the display for the current node
	return nodeHTML;
}


//recursively builds the display for the comment rows (including replies)
var populateRowDisplay = function( node ) {
	
	if( node == null )
		return;


	//
	//build the display for this current comment
	var parentsClass = "";
	for( idx in node.parents ) {
		parentsClass += ("child-" + node.parents[idx] + " "); 
	}
	node['parentsClass'] = parentsClass;	//use the list of nodes so far	
	//alert("commentId = " + node.commentId + ", parentsClass = " + node.parentsClass);
	
	
	var nodeHTML;
	if( node.parentId == node.commentId ) {	//top-level node

		if( node.replies != null && node.replies.length > 0 ) {
			node["iconClass"]="icon-caret-right";	//can expand this row (affects the template)
		}
		nodeHTML = Mustache.render($(".singleCommentRowTemplate").html(),node);
		
	} else {	//reply node

		if( node.replies != null && node.replies.length > 0 ) {
			node["iconClass"] += " icon-caret-right";	//can expand this row (affects the template)
		} else {
			node["iconClass"]="icon-reply";	//is a reply			
		}
		
		nodeHTML = Mustache.render($(".singleReplyRowTemplate").html(),node);
	}//end else

	
	//
	//if this comment has replies, step through them
	if( node.replies != null && node.replies.length > 0 ) {
	    for( idx in node.replies ) {
	        
	        //move to the child comment	    	
	        var currChild = node.replies[idx];
	        var childCommentHTML = populateRowDisplay( currChild );
	
	        //attach the child comment to the current comment (display)
	        nodeHTML += childCommentHTML;
	    }//end for
	}//end if
  

	//
	//return the display for the current node
	return nodeHTML;
}



//Allow the wizard panel headings to be clickable (move the page within the wizard, calls the wizardValidating function)
$('#wizard').on('click', 'li#Information', function(e){
	
	if(	requestDocLocation != null && requestDocLocation != undefined ) {
		
		var tabLocation = requestDocLocation;
		if( isReview )
			tabLocation += '#info';

		document.location = tabLocation;	//go back to the request or review
	}
});
$('#wizard').on('click', 'li#Participants', function(e){
		
	if(	requestDocLocation != null && requestDocLocation != undefined ) {
		
		var tabLocation = requestDocLocation;
		if( isReview )
			tabLocation += '#participant';

		document.location = tabLocation;	//go back to the request or review
	}
});
$('#wizard').on('click', 'li#Data', function(e){
	
	if(	requestDocLocation != null && requestDocLocation != undefined ) {
		
		var tabLocation = requestDocLocation;
		if( isReview )
			tabLocation += '#data';

		document.location = tabLocation;	//go back to the request or review
	}
});
$('#wizard').on('click', 'li#Documents', function(e){
	
	if(	requestDocLocation != null && requestDocLocation != undefined ) {
		
		var tabLocation = requestDocLocation;
		if( isReview )
			tabLocation += '#document';

		document.location = tabLocation;	//go back to the request or review
	}
});
$('#wizard').on('click', 'li#Submit', function(e){
	
	if(	requestDocLocation != null && requestDocLocation != undefined ) {
		
		var tabLocation = requestDocLocation;
		if( isReview )
			tabLocation += '#decision';

		document.location = tabLocation;	//go back to the request or review
	}
});


//set the "back" button navigation value (return to the request or review to which this communication belongs)
var setRequestNavigation = function( data, activityId, requestId, reviewId, isReview, workflowId ) {

	var docLocation;	
	
	if( data != null && data != undefined ) {

		if(data.type === "Research Data Access") {	//Note: if we change this activity type (in the Controller), we should update this test
			data.researchRequest = true;
			data.operationsRequest = false;	
			data.preparatoryRequest = false;
		} else if (data.type === "Preparatory to Research Access"){
			data.researchRequest = false;
			data.operationsRequest = false;
			data.preparatoryRequest = true;
		}else {		
			data.researchRequest = false;
			data.operationsRequest = true;
			data.preparatoryRequest = false;
		}
		
		data.review = isReview;
		data.activityId = activityId;
		data.requestId = requestId;
		data.reviewId = reviewId;
		data.workflowId = workflowId;
	
//		var backButtonHTML = Mustache.render($(".backToTemplate").html(),data);
//		//alert("backButtonHTML = " + backButtonHTML);
//		$('div#backDiv').html(backButtonHTML);
		
		
		if( data.review ) {
			$('#wizard li#Submit').text("Decision");	//for review, update the label of the last tab
			
			if( data.researchRequest ) {
				docLocation = './review/review-project.html';
			} else if( data.preparatoryRequest ) {
				docLocation = './review/review-preparatory-project.html';
			} else {
				docLocation = './review/review-non-research-request.html';
			}
		} else {
			if( data.researchRequest ) {
				docLocation = './create-new-project.html';
			} else if( data.preparatoryRequest ) {
				docLocation = './create-new-preparatory.html';
			} else {
				docLocation = './non-research-request.html';
			}
		}
		docLocation += '?id='+activityId+'&rid='+requestId+'&revid='+reviewId+'&wid='+workflowId;
	}//end if
	
	return docLocation;
};


var getReviewValue = function( urlVarReview ) {
	
	var isReview = true;
	
	if( urlVarReview == null || urlVarReview == undefined || urlVarReview == false )
		isReview = false;
	
	return isReview;
};


//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;
}


update = function() {
	
	// populate the communication list (by request id)
	$.ajax({
		url:'../dart/listCommentsByRequest.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {

				//
				//display the comment bodies and subject lines
				var tableBody1 = "";	//comment body
				var tableRows = "";	//rows
				if( data != undefined && data != null ) {
					
					if( data.comments != undefined && data.comments != null ) {
						
						commentTableData = data.comments;
				        for (idx in commentTableData) {
				            var currComment = commentTableData[idx];

				            var currentBodyHTML = populateBodyDisplay( currComment );
				            var currentRowHTML = populateRowDisplay( currComment );
				            
				            
			            	tableBody1 += currentBodyHTML;	//add the HTML for the current comment chain
			            	tableRows += currentRowHTML;
				        }//end for
					}//end if
				}//end if
				
				//alert("tableRows = " + tableRows);
				
				$('div.comment-body-table').html(tableBody1);	//comment body
				$('div.tab-study-name tbody').html(tableRows).fadeIn();	//rows
				
				$('div.tab-study-name tfoot').hide();	//hide the progress bar
				initRowKids();	//add the expand/collapse actions
			}
		}
	});
	
}