$(function() {

	$('textarea#inputMessage').focus();
	
	$('div.modal-footer').on('click', 'button#submit', function(e) {
		e.preventDefault();
		//require a message
		var message = $('textarea#inputMessage').val();
		var topic = $('textarea#inputTopic').val();
		
		if( message == null || message === "" ) {
			alert("Please enter a message describing the reason for change of review groups on this request.");
		} else if( topic == null || topic === "" ) {
			alert("Please enter a topic describing the reason for change of review groups on this request.");
		} else {
			
			submitModifyReviewGroups();		
		}
	});
});

submitModifyReviewGroups = function(){
	
	var ajaxUrl = '../../dart/modifyReviewGroups.json';
	var aiMap = getAiMap();

	$.ajax({
		url:ajaxUrl,
		type:'POST',
		async:false,
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(aiMap),
		success:function(data,textStatus,three) {
			if (textStatus === 'success') {
				window.opener.location.href="../dashboard.html";
				
				window.close();
			} else {
				alert("Review Group modifications have failed.");
			}
		}
	});
};

getAiMap = function(){
	
	var urlvars = getUrlVars();
	var requestId = parseInt(urlvars['rid'], 10);
	var userId = parseInt(urlvars['userId'], 10);
	var workflowId = parseInt(urlvars['wid'], 10);
	
	var aiMap = {"requestId":requestId};
	aiMap['userId'] = userId;
	aiMap['workflowId'] = workflowId; 
	aiMap['inputMessage'] = $('textarea#inputMessage').val();
	aiMap['inputTopic'] = $('textarea#inputTopic').val();
	
	var toRemoveArray = JSON.parse(window.localStorage.getItem("reviewsToBeRemoved")); // Retrieving
	console.log("toRemoveArray " + toRemoveArray);
	aiMap['reviewsToBeRemoved'] = toRemoveArray;
	
	var toAddArray = JSON.parse(window.localStorage.getItem("reviewsToBeAdded")); // Retrieving
	console.log("toAddArray " + toAddArray);
	aiMap['reviewsToBeAdded'] = toAddArray;
	return aiMap;
	
};
	
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;
}
