<commit_before>$(function(){

	//demo campaigns
	var democampaigns = {
		"Snack.xml" : "Snack",
		"Nutrition.xml" : "Nutrition",
		"StressChill.xml" : "Stress and Chill",
		"Trash.xml" : "Trash",
		"Media.xml" : "Advertisement"
	};

	//globals
	var userdata;
	var table;

	//initiate the client
	var oh = Ohmage("/app", "campaign-manager")

	//global error handler. In ohmage 200 means unauthenticated
	oh.callback("error", function(msg, code, req){
		(code == 200) ? window.location.replace("/#login") : message("<strong>Error! </strong>" + msg);
	});

	//prevent timeout
	oh.keepalive();

	function td(x){
		return($("<td>").text(x).attr("data-value", x || 0));
	}

	function toTitleCase(str) {
		return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}

	function first(obj) {
		for (var a in obj) return a;
	}

	function addrow(urn, classdata){
		var name = classdata.name;
		var role = classdata.role;
		var users = classdata.users
		var count = Object.keys(users).length;

		var mytr = $("<tr />").data("classdata", classdata).appendTo("#classtable tbody");
		td(name).appendTo(mytr);
		td(urn).appendTo(mytr);
		td(count).appendTo(mytr);
		td(role || "-").appendTo(mytr);

		var mybtn = $('<a class="btn btn-sm btn-default"><i class="glyphicon glyphicon-edit"></i> Manage</a>')
		.attr("href", "editclass.html?" + urn).appendTo($("<td>").addClass("buttontd").appendTo(mytr));

		if(!(role == "privileged" || userdata.permissions.admin)){
			mybtn.attr("disabled", "disabled");
			mybtn.click(function(e){
				e.preventDefault();
			})
		}

		td(Object.keys(users).join(", ")).appendTo(mytr);
	}

	function expand(rowdata, classdata) {
		var row = $('<div/>').addClass('row').addClass("response-row");
		var col1 = $("<div />").addClass("col-md-6").appendTo(row).append($("<h4 />").text("privileged"));
		var col2 = $("<div />").addClass("col-md-6").appendTo(row).append($("<h4 />").text("restricted"));
		var ul1 = $("<ul />").appendTo(col1)
		var ul2 = $("<ul />").appendTo(col2)

		$.each(classdata.users, function(name, role){
			$("<li/>").text(name).appendTo(role == "privileged" ? ul1 : ul2)
		});
		return row;
	}

	//data tables widget
	function initTable(){
		table = $('#classtable').DataTable( {
			"dom" : '<"pull-right"l><"pull-left"f>tip',
			"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
			"aoColumnDefs": [
			{ 'bSortable': false, 'aTargets': [ 4, 5 ] },
			{ 'bSearchable': false, 'aTargets': [ 4 ] },
			{ 'bVisible' : false, 'aTargets' : [ 5 ] } 				
			]
		});
	}

	function message(msg, type){
		// type must be one of success, info, warning, danger
		type = type || "danger"
		$("#errordiv").append('<div class="alert alert-' + type + '"><a href="#" class="close" data-dismiss="alert">&times;</a>' + msg + '</div>');
		$('html, body').animate({
			scrollTop: 100
		}, 200);
	}

	function generateURN(name){
		"urn:class:" + utf2ascii(name.toLowerCase().replace(/\W/g, ''));
	}

	function urnify(str){
		return str.toLowerCase().replace(/\s/g, "_").replace(/[^a-z0-9:_]/gi,'');
	}

	function idify(str){
		return str.toLowerCase().replace(/[^a-z0-9]/gi,'');
	}

	//suggest URN
	$("#inputClassName").on("keyup", function(){
		var x = $(this).val();
		var org = userdata.organization ? urnify(userdata.organization + ":") : "";
		var lastname = userdata.last_name ? urnify(userdata.last_name + ":") : "";
		var year = (new Date).getFullYear() + ":";
		$("#inputClassUrn").val("urn:class:" + org + year + lastname + urnify(x));
	});

	//validator
	$("#inputClassUrn").on("keyup", function(){
		var urn = urnify($(this).val());
		$(this).val(urn);
	});

	$("#createbutton").on("click", function createclass(e){
		var btn = $(this)
		e.preventDefault();
		var class_name = $("#inputClassName").val();
		var class_urn = $("#inputClassUrn").val();
		var campaigns = $.map($("#inputDemoCampaigns input:checked"), function(x){ return $(x).val()});

		//try to create the new class
		btn.attr("disabled", "disabled")
		oh.class.create({
			class_urn : class_urn, 
			class_name : class_name
		}).done(function(){
			//adding campaigns
			createCampaigns(class_urn, campaigns)
		}).always(function(){
			$('#myModal').modal('hide');
			btn.removeAttr("disabled")
		});
	});

	//downloads a campaign.xml file
	function download_file(url){
		return $.ajax({
			url: url,
			data: {},
			dataType: "text"
		}).fail(function() {
			message("Failed to download: " + url);
		});
	}

	function createCampaigns(class_urn, campaigns){
		//download the xml files
		var requests = $.map(campaigns, function(xmlfile){
			return download_file("xml/" + xmlfile);
		});

		//after all xml files are in
		$.when.apply($, requests).done(function() {
			var xmlstrings = $.map(requests, function(x){
				return x.responseText;
			});
			var requests2 = $.map(campaigns, function(val, i){
				var prettyname = democampaigns[val];
				var xmlstr = xmlstrings[i];
				var campaign_urn = class_urn.replace("urn:class", "urn:campaign") + ":" + urnify(val.replace(".xml", ""))
				return oh.campaign.create({
					privacy_state : "shared",
					running_state : "running",
					class_urn_list : class_urn,
					campaign_urn : campaign_urn,
					campaign_name : prettyname,
					xml : xmlstr
				});
			});
			$.when.apply($, requests2).always(function() {
				window.location.href = 'editclass.html?' + class_urn;
			});
		});
	}

	//add the democampaigns
	$.each(democampaigns, function(xml, name){
		var input = $("<input>").attr("type", "checkbox").attr("value", xml)
		var label = $("<label />").addClass("checkbox-inline").append(input).append(name).appendTo("#inputDemoCampaigns");
	});

	//init page
	oh.user.whoami().done(function(username){

		//get the users name and organization
		oh.user.read({user:username}).done(function(data){
			userdata = data[username];
			$("#subtitle").text(userdata.first_name + " " + userdata.last_name)
			if(!(userdata.permissions.admin || userdata.permissions.can_setup_users)){
				message("You do not have user/setup privileges!")
			}
			if(!(userdata.permissions.admin || userdata.permissions.can_create_classes)){
				message("You do not have class/create privileges!")
			}			

			//get the classes that the user has access to
			$("#classtable tbody").empty();
			oh.class.read({}).done(function(classdata){
				$.each(classdata, function(urn, value){<commit_msg>port the existing campaign case<commit_after>$(function(){

	//demo campaigns
	var democampaigns = {
		"Snack.xml" : "Snack",
		"Nutrition.xml" : "Nutrition",
		"StressChill.xml" : "Stress and Chill",
		"Trash.xml" : "Trash",
		"Media.xml" : "Advertisement"
	};

	//globals
	var userdata;
	var table;
	var user_campaigns;

	//initiate the client
	var oh = Ohmage("/app", "campaign-manager")

	//global error handler. In ohmage 200 means unauthenticated
	oh.callback("error", function(msg, code, req){
		(code == 200) ? window.location.replace("/#login") : message("<strong>Error! </strong>" + msg);
	});

	//prevent timeout
	oh.keepalive();

	function td(x){
		return($("<td>").text(x).attr("data-value", x || 0));
	}

	function toTitleCase(str) {
		return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}

	function first(obj) {
		for (var a in obj) return a;
	}

	function addrow(urn, classdata){
		var name = classdata.name;
		var role = classdata.role;
		var users = classdata.users
		var count = Object.keys(users).length;

		var mytr = $("<tr />").data("classdata", classdata).appendTo("#classtable tbody");
		td(name).appendTo(mytr);
		td(urn).appendTo(mytr);
		td(count).appendTo(mytr);
		td(role || "-").appendTo(mytr);

		var mybtn = $('<a class="btn btn-sm btn-default"><i class="glyphicon glyphicon-edit"></i> Manage</a>')
		.attr("href", "editclass.html?" + urn).appendTo($("<td>").addClass("buttontd").appendTo(mytr));

		if(!(role == "privileged" || userdata.permissions.admin)){
			mybtn.attr("disabled", "disabled");
			mybtn.click(function(e){
				e.preventDefault();
			})
		}

		td(Object.keys(users).join(", ")).appendTo(mytr);
	}

	function expand(rowdata, classdata) {
		var row = $('<div/>').addClass('row').addClass("response-row");
		var col1 = $("<div />").addClass("col-md-6").appendTo(row).append($("<h4 />").text("privileged"));
		var col2 = $("<div />").addClass("col-md-6").appendTo(row).append($("<h4 />").text("restricted"));
		var ul1 = $("<ul />").appendTo(col1)
		var ul2 = $("<ul />").appendTo(col2)

		$.each(classdata.users, function(name, role){
			$("<li/>").text(name).appendTo(role == "privileged" ? ul1 : ul2)
		});
		return row;
	}

	//data tables widget
	function initTable(){
		table = $('#classtable').DataTable( {
			"dom" : '<"pull-right"l><"pull-left"f>tip',
			"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
			"aoColumnDefs": [
			{ 'bSortable': false, 'aTargets': [ 4, 5 ] },
			{ 'bSearchable': false, 'aTargets': [ 4 ] },
			{ 'bVisible' : false, 'aTargets' : [ 5 ] } 				
			]
		});
	}

	function message(msg, type){
		// type must be one of success, info, warning, danger
		type = type || "danger"
		$("#errordiv").append('<div class="alert alert-' + type + '"><a href="#" class="close" data-dismiss="alert">&times;</a>' + msg + '</div>');
		$('html, body').animate({
			scrollTop: 100
		}, 200);
	}

	function generateURN(name){
		"urn:class:" + utf2ascii(name.toLowerCase().replace(/\W/g, ''));
	}

	function urnify(str){
		return str.toLowerCase().replace(/\s/g, "_").replace(/[^a-z0-9:_]/gi,'');
	}

	function idify(str){
		return str.toLowerCase().replace(/[^a-z0-9]/gi,'');
	}

	//suggest URN
	$("#inputClassName").on("keyup", function(){
		var x = $(this).val();
		var org = userdata.organization ? urnify(userdata.organization + ":") : "";
		var lastname = userdata.last_name ? urnify(userdata.last_name + ":") : "";
		var year = (new Date).getFullYear() + ":";
		$("#inputClassUrn").val("urn:class:" + org + year + lastname + urnify(x));
	});

	//validator
	$("#inputClassUrn").on("keyup", function(){
		var urn = urnify($(this).val());
		$(this).val(urn);
	});

	$("#createbutton").on("click", function createclass(e){
		var btn = $(this)
		e.preventDefault();
		var class_name = $("#inputClassName").val();
		var class_urn = $("#inputClassUrn").val();
		var campaigns = $.map($("#inputDemoCampaigns input:checked"), function(x){ return $(x).val()});

		//try to create the new class
		btn.attr("disabled", "disabled")
		oh.class.create({
			class_urn : class_urn, 
			class_name : class_name
		}).done(function(){
			//adding campaigns
			createCampaigns(class_urn, campaigns)
		}).always(function(){
			$('#myModal').modal('hide');
			btn.removeAttr("disabled")
		});
	});

	//downloads a campaign.xml file
	function download_file(url){
		return $.ajax({
			url: url,
			data: {},
			dataType: "text"
		}).fail(function() {
			message("Failed to download: " + url);
		});
	}

	function createCampaigns(class_urn, campaigns){
		//download the xml files
		var requests = $.map(campaigns, function(xmlfile){
			return download_file("xml/" + xmlfile);
		});

		//after all xml files are in
		$.when.apply($, requests).done(function() {
			var xmlstrings = $.map(requests, function(x){
				return x.responseText;
			});
			var requests2 = $.map(campaigns, function(val, i){
				var prettyname = democampaigns[val];
				var xmlstr = xmlstrings[i];
				var campaign_urn = class_urn.replace("urn:class", "urn:campaign") + ":" + urnify(val.replace(".xml", ""));

				//create new capaign unless it exists
				if(user_campaigns.indexOf(campaign_urn) < 0){
					return oh.campaign.create({
						privacy_state : "shared",
						running_state : "running",
						class_urn_list : class_urn,
						campaign_urn : campaign_urn,
						campaign_name : prettyname,
						xml : xmlstr
					});
				} else {
					return oh.campaign.addClass(campaign_urn, class_urn).done(function(){
						message("Campaign already exists. Adding class " + class_urn + " to campaign " + campaign_urn, "warning");
					});
				}
			});
			$.when.apply($, requests2).always(function() {
				window.location.href = 'editclass.html?' + class_urn;
			});
		});
	}

	//add the democampaigns
	$.each(democampaigns, function(xml, name){
		var input = $("<input>").attr("type", "checkbox").attr("value", xml)
		var label = $("<label />").addClass("checkbox-inline").append(input).append(name).appendTo("#inputDemoCampaigns");
	});

	//init page
	oh.user.whoami().done(function(username){

		//get the users name and organization
		oh.user.read({user:username}).done(function(data){
			userdata = data[username];
			$("#subtitle").text(userdata.first_name + " " + userdata.last_name)
			if(!(userdata.permissions.admin || userdata.permissions.can_setup_users)){
				message("You do not have user/setup privileges!")
			}
			if(!(userdata.permissions.admin || userdata.permissions.can_create_classes)){
				message("You do not have class/create privileges!")
			}			

			//get the classes that the user has access to
			$("#classtable tbody").empty();
			oh.class.read({}).done(function(classdata){
				$.each(classdata, function(urn, value){
{'fraction_non_alphanumeric': 0.21134924872244681, 'fraction_numerical': 0.008161086110899244, 'mean_word_length': 4.0605943651099965, 'pattern_counts': {'":': 12, '<': 54, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 38}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5839358', 'n_tokens_mistral': 5155, 'n_tokens_neox': 4543, 'n_words': 905}