$(function() {

	var urlvars = getUrlVars();
	var activityId = parseInt(urlvars['id'], 10);
	var activityIdMap = {"activityId":activityId};
	var primaryInfo;
	
	// populate location options
	$.ajax({
		url:'../dart/getAllLocations.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(activityIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success"){
				var locationOptions = Mustache.render($(".locationOptionsTemplate").html(),data);
				$("#div-four .displayTable .location").append(locationOptions).chosen({no_results_text: "No locations matched"});
			}
		}
	});
		
	// populate participant information
	$.ajax({
		url:'../dart/getPrimaryInfo.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(activityIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success"){
				primaryInfo = data;
				if(primaryInfo.locations.length>0){
					populatePrimaryInfoTable(primaryInfo);
				}
			}
		}
	});

	// populate the user request info
	$.ajax({
		url:'../dart/getActivityInfo.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(activityIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success"){
				var projectName = Mustache.render($(".projectNameTemplate").html(),data);
				$('div#div-zero').html(projectName);
			}
		}
	});
	
	//Add new data row to table
	$('.displayTable').on('click','.add',function(e){
		e.preventDefault();

		//Add row
		var name = $('.displayTable').find('.name').val();
		var location = $('.displayTable').find('.location').val();
		var checked;
//TODO: name validation!!!!
		($('.displayTable').find('.notify').is(":checked")) ? checked = "checked" : checked = "";
		var data = {
			"name":name,
			"location":location,
			"checked":checked
		};
		var newRow = Mustache.render($(".newRowTempate").html(),data);
		$('.displayTable .controls').before(newRow);
		$('.displayTable tr.hide').fadeIn().removeClass('hide');
		//clear old data
		$('.displayTable').find('.name').val("");
		$('.displayTable').find('.location').val("").trigger('liszt:updated');

//TODO: might want to store the notifications checkbox value (checked) in participants
		//send the new row to primaryInfo object
		if(getLocInfo(location)===undefined){	//new location
			primaryInfo.locations.push({"primary":false,"location":location,"primaryInvestigator":name});
			primaryInfo.investigators[location] = {"participants":[name]};
//			primaryInfo.investigators[location] = {"participants":[{"name":name,"checked":checked}]};
			populatePrimaryInfoTable(primaryInfo);
		} else {
			//assumed that if it is not a new location then it can only be a new person
			primaryInfo.investigators[location].participants.push(name);
//			primaryInfo.investigators[location].participants.push({"name":name,"checked":checked});
		}
	});

	//Remove data row from table
	$('.displayTable').on('click','.delete',function(e){
		e.preventDefault();
		var thisRow = $(this).parents('tr');
		var location = thisRow.find('.location-name').text();
		var participant = thisRow.find('.participant').text();
		var locationData = getLocInfo(location);
		//remove name from investigator's list
		primaryInfo.investigators[location].participants = removeFromArray(participant,primaryInfo.investigators[location].participants);
		//check if we should also remove a primary location
		if(primaryInfo.investigators[location].participants.length===0){
			delete primaryInfo.investigators[location];
			primaryInfo.locations.splice(locationData.i,1);
			populatePrimaryInfoTable(primaryInfo);
			if(primaryInfo.locations.length===0){
				$('.primary-info').css('opacity',.3);
				$('.primary-info .alert').hide();
			}
		} else {
			if(participant===locationData.primaryInvestigator){
				primaryInfo.locations[locationData.i].primaryInvestigator = primaryInfo.investigators[location].participants[0];
				populatePrimaryInfoTable(primaryInfo);
			}
		}
		thisRow.fadeOut('fast',function(){$(this).remove();});
//TODO: remove from the database
	});

	//Change Primary Location
	$('.primary-info').on('click','td.primary-location i',function(e){
		var location = $(this).parents('tr').find('td.location-name').text();
		$('td.primary-location i').removeClass('icon-star').addClass('icon-star-empty');
		$(this).removeClass('icon-star-empty').addClass('icon-star');
		$.each(primaryInfo.locations,function(i,val){
			if(location === val.location){
				primaryInfo.locations[i].primary = true;
			} else {
				primaryInfo.locations[i].primary = false;
			}
		});
	});

	//Change Primary Investigator
	$('.primary-info').on('click','.edit-primary-investigator',function(e){
		e.preventDefault();
		var selected = $(this);
		var location = selected.parents('tr').find('td.location-name').text();
		var locationData = getLocInfo(location);
		var participants = primaryInfo.investigators[location];
		var piOptions = Mustache.render($('.piOptionsTemplate').html(),participants);
		var curPI = 'option[value="'+locationData.primaryInvestigator+'"]';
		piOptions = $(piOptions).find(curPI).attr("selected",true).end();
		selected.parents('tr').find('.primary-investigator').html(piOptions).find('select').on('change',function(e){
			locationData.primaryInvestigator = $(e.target).val();
			populatePrimaryInfoTable(primaryInfo);
		});
		$('.primary-info').on('click','.primary-investigator button.close',function(e){
			populatePrimaryInfoTable(primaryInfo);
		});
	});

	var applyPrimaryInvestigator = function(e,pi){
	};

	var getLocInfo = function(location){
		var locationData;
		$.each(primaryInfo.locations, function(i,val){
			if(location === val.location){
				locationData = primaryInfo.locations[i];
//TODO: commenting this out for now? (was causing "i" to show up in the JSON.stringify() and it doesn't match the View class)
//				locationData["i"] = i;
			}
		});
		return locationData;
	};
	
	$('#div-two').on('click','button#back',function(e){
		document.location='./project-information.html?id='+urlvars['id'];
	});
	
	$('#div-two').on('click','button#next',function(e){
		// TODO- save participant info
		var piMap = {"requestId":requestId};
		piMap['primaryInfo'] = primaryInfo;
	
		$.ajax({
			url:'../dart/savePrimaryInfo.json',
			type:'POST',
			contentType:'application/json',
			dataType:'json',
			data:JSON.stringify(piMap),
			success:function(data,textStatus,three) {
				if(textStatus==="success"){
//					document.location='./data-sources.html?id='+activityId;
				}
				else {
					alert('error');
				}
			}
		});
	});
});

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

populatePrimaryInfoTable = function(primaryInfo){
	var newPrimary = Mustache.render($(".newPrimaryTemplate").html(),primaryInfo);
	$('.primary-info table tbody').html(newPrimary);
	if(primaryInfo.locations.length>0){
		$('.primary-info :checked').siblings().first().removeClass('icon-star-empty').addClass('icon-star');
		$('.primary-info').css('opacity',1);
		$('.primary-info .alert').fadeIn();
	}
};

removeFromArray = function(value, arr) {
	return $.grep(arr, function(elem, index) {
		return elem !== value;
	});
};