var requestDocLocation;
var isReview = false;
var requestType; 

$(function() {
	var userId = 5;
	var userIdMap = {"userId":userId};
	
	var urlvars = getUrlVars();
	var activityId = parseInt(urlvars['id'], 10);
	var activityIdMap = {"activityId":activityId};
	var requestId = parseInt(urlvars['rid'], 10);
	var requestIdMap = {"requestId":requestId};
	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
	
		
	$("div.container a#communication").click(function() {
		var docLocation = './communication.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;
							
			}
		}
	});
	
	// 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);
	
				//set the "back" navigation value
				requestType = data.type;
				requestDocLocation = setRequestNavigation( data, requestType, activityId, requestId, reviewId, isReview, workflowId );
			}
		}
	});
	
	
	// populate the history list
	var activityEventMap = {"activityId":activityId};

	
	$.ajax({
		url:'../dart/listEventsByActivity.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(activityEventMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {
				
				if( data != undefined && data != null ) {
					if( data.requests != undefined && data.requests != null ) {
				        for (idx in data.requests) {
				            var currRequest = data.requests[idx];

				            var reqButtonNavLocation = setRequestNavigation( data, requestType, activityId, currRequest.requestId, currRequest.reviewId, isReview, currRequest.workflowId );	//create a navigation URL for the current request

				            currRequest['reqButtonNavLocation'] = reqButtonNavLocation;	//add the path to the JSON for the current request
				        }
					}
				}
				
				var tableBody = Mustache.render($(".requestRowTemplate").html(),data);
				$('div.request-table').html(tableBody);
				
				//
				//on expand/collapse, update the caret icon
				initExpandCollapseIconActions();
			}
		}
	});
});


//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){
	//alert("clicked the Information heading");
	
	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){
	//alert("clicked the Participants heading");
		
	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){
	//alert("clicked the Data heading");
	
	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){
	//alert("clicked the Documents heading");
	
	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){
	//alert("clicked the Submit heading");
	
	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 history belongs)
var setRequestNavigation = function( data, requestType, activityId, requestId, reviewId, isReview, workflowId ) {

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

		if(requestType === "Research Data Access") {	//Note: if we change this activity type (in the Controller), we should update this test
			data.researchRequest = true;
			data.preparatoryRequest = false;
			data.operationsRequest = false;	
		} else if (requestType === "Preparatory to Research Access") {
			data.researchRequest = false;
			data.preparatoryRequest = true;
			data.operationsRequest = false;	
		}
		else {
			data.researchRequest = false;
			data.preparatoryRequest = false;
			data.operationsRequest = true;				
		}
		
		data.review = isReview;
		data.activityId = activityId;
		data.requestId = requestId;
		data.reviewId = reviewId;
		data.workflowId = workflowId;

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