extractor support for I18n as a module

this makes scoped block detection a bit more strict now, so several
js files need their indentation fixed

test plan: confirm that i18n:extract works and that the result is the
same

Change-Id: If23768dfd3626b46d798560bb3b843595295444b
Reviewed-on: https://gerrit.instructure.com/6736
Tested-by: Hudson <hudson@instructure.com>
Reviewed-by: Ryan Shaw <ryan@instructure.com>
This commit is contained in:
Jon Jensen 2011-11-07 10:15:13 -07:00
parent 047842784f
commit 902bcec07c
17 changed files with 8521 additions and 8496 deletions

View File

@ -46,8 +46,8 @@ module I18nExtraction
<%\s*(end|\})\s*%>
/mx
SCOPED_BLOCK_START = /I18n\.scoped/
SCOPED_BLOCK = /^([ \t]*)#{SCOPED_BLOCK_START}\(#{I18N_KEY},\s*function\s*\(I18n\)\s*\{(.*?)\n\1\}\)(;|$)/m
SCOPED_BLOCK_START = /((require|define)\([^\n]+I18n.*?I18n\s*=\s*|())I18n\.scoped/m
SCOPED_BLOCK = /^([ \t]*)#{SCOPED_BLOCK_START}\(#{I18N_KEY}(,\s*function\s*\(I18n\)\s*\{|\);)\s?\n((\1[^ ].*?\n)?( *\n|\1( |\t)[^\n]+\n)+)/m
I18N_ANY = /(I18n)/
@ -88,12 +88,13 @@ module I18nExtraction
matches = []
source.scan(full_pattern){ |args| matches << [$&] + args }
expected.each_index do |i|
expected_string = expected[i].first.strip
unless matches[i]
raise "unable to \"parse\" #{expression_type} on line #{expected[i].last} (#{expected[i].first}...)"
raise "unable to \"parse\" #{expression_type} on line #{expected[i].last} (#{expected_string}...)"
end
len = [expected[i].first.size, matches[i].first.size].min
if expected[i].first[0, len] != matches[i].first[0, len]
raise "unable to \"parse\" #{expression_type} on line #{expected[i].last} (#{expected[i].first[0, len]}...)"
matched_string = matches[i].first.strip
unless matched_string.include?(expected_string)
raise "unable to \"parse\" #{expression_type} on line #{expected[i].last} (#{expected_string}...)"
end
matches[i] << expected[i].last
if block_given?
@ -108,16 +109,19 @@ module I18nExtraction
def process_js(source, options = {})
line_offset = options[:line_offset] || 1
scopes = find_matches(source, SCOPED_BLOCK_START, SCOPED_BLOCK, :start_prefix => /\s*/, :line_offset => line_offset, :expression => "I18n scope")
scopes.each do |(_, _, scope, scope_source, _, offset)|
process_block scope_source, scope.sub(/\A#/, ''), options.merge(:line_offset => offset)
scopes.each do |scope|
scope_name = scope[5]
scope_source = scope[7]
offset = scope.pop
process_block scope_source, scope_name.sub(/\A#/, ''), options.merge(:line_offset => offset)
end
# see if any other I18n calls happen outside of a scope
chunks = source.split(/(#{SCOPED_BLOCK.to_s.gsub(/\\1/, '\\\\2')})/m) # captures subpatterns too, so we need to pick and choose what we want
while chunk = chunks.shift
if chunk =~ /^([ \t]*)#{SCOPED_BLOCK_START}/
chunks.slice!(0, 4)
chunks.slice!(0, 7).inspect
else
find_matches chunk, I18N_ANY do |match|
find_matches chunk, /#{I18N_ANY}.*$/ do |match|
raise "possibly unscoped I18n call on line #{line_offset + match.last} (hint: check your indentation)"
end
end
@ -129,7 +133,7 @@ module I18nExtraction
line_offset = options[:line_offset] || 1
extract_from_erb(source, :line_offset => line_offset).each do |scope, block_source, offset|
offset = line_offset + offset
find_matches block_source, /(#{SCOPED_BLOCK_START})/ do |match|
find_matches block_source, /#{SCOPED_BLOCK_START}.*/ do |match|
raise "scoped blocks are no longer supported in js_blocks, use :i18n_scope instead (line #{offset + match.last})"
end
if scope && (scope = process_literal(scope))

View File

@ -17,296 +17,296 @@
*/
I18n.scoped('attendance', function(I18n) {
var attendance = {
saveKeyIndex: 0,
toggleState: function(cell, forceState, skipSave) {
if(cell.hasClass('false_submission')) { return; }
var vals = cell.attr('id').split("_");
var user_id = vals[1];
var assignment_id = vals[2];
cell.addClass('saving');
var grade = "";
if(forceState) {
if(forceState == 'fail') {
cell.removeClass('pass').addClass('fail');
grade = "fail";
} else if(forceState == 'pass') {
cell.removeClass('fail').addClass('pass');
grade = "pass";
} else {
cell.removeClass('fail').removeClass('pass');
grade = "";
}
} else {
if(cell.hasClass('pass')) {
cell.removeClass('pass').addClass('fail');
grade = "fail";
} else if(cell.hasClass('fail')) {
cell.removeClass('fail').removeClass('pass');
grade = "";
} else {
cell.removeClass('fail').addClass('pass');
grade = "pass";
}
}
var key = attendance.saveKeyIndex++
if(!skipSave) {
setTimeout(function() {
if(cell.data('save_key') == key) {
var url = $.replaceTags($.replaceTags($(".grade_submission_url").attr('href'), "user_id", user_id), "assignment_id", assignment_id);
var data = {
'submission[assignment_id]': assignment_id,
'submission[user_id]': user_id,
'submission[grade]': grade
};
$.ajaxJSON(url, "POST", data, function(data) {
cell.removeClass('saving');
for(var idx in data) {
var submission = data[idx].submission;
var $cell = $("#submission_" + submission.user_id + "_" + submission.assignment_id);
var key = attendance.toggleState($cell, submission.grade || "clear", true);
attendance.clearSavingState($cell, key);
}
}, function(data) {
cell.removeClass('saving');
});
var attendance = {
saveKeyIndex: 0,
toggleState: function(cell, forceState, skipSave) {
if(cell.hasClass('false_submission')) { return; }
var vals = cell.attr('id').split("_");
var user_id = vals[1];
var assignment_id = vals[2];
cell.addClass('saving');
var grade = "";
if(forceState) {
if(forceState == 'fail') {
cell.removeClass('pass').addClass('fail');
grade = "fail";
} else if(forceState == 'pass') {
cell.removeClass('fail').addClass('pass');
grade = "pass";
} else {
cell.removeClass('fail').removeClass('pass');
grade = "";
}
}, 1000);
}
cell.data('save_key', key);
return key;
},
clearSavingState: function($cell, key) {
if($cell.data('save_key') == key) {
$cell.removeClass('saving');
$cell.data('save_key', null);
}
},
toggleColumnState: function(column, forceState) {
var assignment_id = datagrid.cells[0 + ',' + column].attr('id').split("_")[1];
var keys = {};
for(var idx = 1; idx < datagrid.rows.length; idx++) {
var key = attendance.toggleState(datagrid.cells[idx + ',' + column], forceState, true);
keys[idx] = key;
}
var clearSaving = function() {
} else {
if(cell.hasClass('pass')) {
cell.removeClass('pass').addClass('fail');
grade = "fail";
} else if(cell.hasClass('fail')) {
cell.removeClass('fail').removeClass('pass');
grade = "";
} else {
cell.removeClass('fail').addClass('pass');
grade = "pass";
}
}
var key = attendance.saveKeyIndex++
if(!skipSave) {
setTimeout(function() {
if(cell.data('save_key') == key) {
var url = $.replaceTags($.replaceTags($(".grade_submission_url").attr('href'), "user_id", user_id), "assignment_id", assignment_id);
var data = {
'submission[assignment_id]': assignment_id,
'submission[user_id]': user_id,
'submission[grade]': grade
};
$.ajaxJSON(url, "POST", data, function(data) {
cell.removeClass('saving');
for(var idx in data) {
var submission = data[idx].submission;
var $cell = $("#submission_" + submission.user_id + "_" + submission.assignment_id);
var key = attendance.toggleState($cell, submission.grade || "clear", true);
attendance.clearSavingState($cell, key);
}
}, function(data) {
cell.removeClass('saving');
});
}
}, 1000);
}
cell.data('save_key', key);
return key;
},
clearSavingState: function($cell, key) {
if($cell.data('save_key') == key) {
$cell.removeClass('saving');
$cell.data('save_key', null);
}
},
toggleColumnState: function(column, forceState) {
var assignment_id = datagrid.cells[0 + ',' + column].attr('id').split("_")[1];
var keys = {};
for(var idx = 1; idx < datagrid.rows.length; idx++) {
var key = keys[idx];
attendance.clearSavingState(datagrid.cells[idx + ',' + column], keys[idx]);
var key = attendance.toggleState(datagrid.cells[idx + ',' + column], forceState, true);
keys[idx] = key;
}
};
var url = $.replaceTags($(".set_default_grade_url").attr('href'), "assignment_id", assignment_id);
var grade = forceState;
if(grade != "pass" && grade != "fail") { grade = ""; }
var data = {
'assignment[default_grade]': grade,
'assignment[overwrite_existing_grades]': '1'
};
$.ajaxJSON(url, "PUT", data, function(data) {
clearSaving();
}, function(data) {
clearSaving();
});
}
};
var attachAddAssignmentGroup;
$(document).ready(function() {
var $blank = $(".blank_attendance:first");
var $pass = $(".pass_attendance:first");
var $fail = $(".fail_attendance:first");
var errorCount = 0;
if(attachAddAssignmentGroup) {
attachAddAssignmentGroup($("#new_assignment_dialog select.assignment_group_select"));
}
$(".add_assignment_link").click(function(event) {
event.preventDefault();
$("#new_assignment_dialog :text:not(.points_possible)").each(function() {
$(this).val("");
});
$("#new_assignment_dialog").dialog('close').dialog({
autoOpen: false,
title: I18n.t('titles.new_attendance_column', "New Attendance Column")
}).dialog('open');
});
$("#new_assignment_dialog .cancel_button").click(function(event) {
$("#new_assignment_dialog").dialog('close');
});
$("#add_assignment_form").formSubmit({
beforeSubmit: function(data) {
$(this).find(".submit_button").text(I18n.t('status.adding_assignment', "Adding Assignment..."));
$(this).find("button").attr('disabled', true);
},
success: function(data) {
$(this).find(".submit_button").text(I18n.t('status.added_assignment', "Added Assignment"));
$(this).find("button").attr('disabled', false);
var assignment = data.assignment;
location.href = "#assignment_" + assignment.id;
location.reload();
},
error: function(data) {
$(this).formErrors(data);
$(this).find(".submit_button").text(I18n.t('errors.could_not_add_assignment', "Add Assignment Failed"));
$(this).find("button").attr('disabled', false);
}
});
$("#new_assignment_dialog .title").change(function() {
var val = $(this).val();
if (val && val != defaultTitle()) {
$(this).attr('edited', true);
} else {
$(this).removeAttr('edited');
}
});
function defaultTitle() {
var date = $("#new_assignment_dialog .datetime_field").data('date');
if (date) {
return I18n.t('default_attendance_title', 'Attendance %{date}', {date: I18n.l('#date.formats.default', date)});
} else {
return '';
}
}
$("#new_assignment_dialog .datetime_field").change(function() {
var val = $("#new_assignment_dialog .title").val();
var titleEdited = $("#new_assignment_dialog .title").attr('edited');
if(!val || !titleEdited) {
var date = $(this).data('date');
if(date) {
$("#new_assignment_dialog .title").val(defaultTitle());
}
}
});
$(".datetime_field").datetime_field();
$(".help_link").click(function(event) {
event.preventDefault();
$("#attendance_how_to_dialog").dialog('close').dialog({
autoOpen: false,
width: 400,
title: I18n.t('titles.attendance_help', "Attendance Help")
}).dialog('open');
});
$(".submission").addClass('loading');
var getClump = function(url, assignment_ids, user_ids) {
$.ajaxJSON(url, "GET", {}, function(data) {
for(var idx in assignment_ids) {
for(var jdx in user_ids) {
$("#submission_" + user_ids[jdx] + "_" + assignment_ids[idx]).removeClass('loading');
var clearSaving = function() {
for(var idx = 1; idx < datagrid.rows.length; idx++) {
var key = keys[idx];
attendance.clearSavingState(datagrid.cells[idx + ',' + column], keys[idx]);
}
}
for(var idx in data) {
if(data[idx] && data[idx].submission) {
var grade = data[idx].submission.grade;
var $submission = $("#submission_" + data[idx].submission.user_id + "_" + data[idx].submission.assignment_id);
$submission.removeClass('loading');
if(grade != "pass" && grade != "fail") { grade = "clear"; }
var key = attendance.toggleState($submission, grade, true);
attendance.clearSavingState($submission, key);
}
}
}, function() {
if(errorCount < 5) {
errorCount++;
getClump(url);
}
});
};
var url = $.replaceTags($(".set_default_grade_url").attr('href'), "assignment_id", assignment_id);
var grade = forceState;
if(grade != "pass" && grade != "fail") { grade = ""; }
var data = {
'assignment[default_grade]': grade,
'assignment[overwrite_existing_grades]': '1'
};
$.ajaxJSON(url, "PUT", data, function(data) {
clearSaving();
}, function(data) {
clearSaving();
});
}
};
var clump_size = Math.round(200 / ($("#attendance .student").length || 1));
var clump = [];
var pre = $(".gradebook_url").attr('href');
setTimeout(function() {
var assignment_ids = [];
$("#attendance .assignment").each(function() {
var id = ($(this).attr('id') || "").split("_").pop(); //.substring(11);
assignment_ids.push(id);
var attachAddAssignmentGroup;
$(document).ready(function() {
var $blank = $(".blank_attendance:first");
var $pass = $(".pass_attendance:first");
var $fail = $(".fail_attendance:first");
var errorCount = 0;
if(attachAddAssignmentGroup) {
attachAddAssignmentGroup($("#new_assignment_dialog select.assignment_group_select"));
}
$(".add_assignment_link").click(function(event) {
event.preventDefault();
$("#new_assignment_dialog :text:not(.points_possible)").each(function() {
$(this).val("");
});
$("#new_assignment_dialog").dialog('close').dialog({
autoOpen: false,
title: I18n.t('titles.new_attendance_column', "New Attendance Column")
}).dialog('open');
});
$("#attendance .student").each(function() {
var id = ($(this).attr('id') || "").split("_").pop(); //.substring(8);
if(id) {
clump.push(id);
}
if(clump.length > clump_size) {
getClump(pre + "?init=1&submissions=1&user_ids=" + clump.join(",") + "&assignment_ids=" + assignment_ids.join(","), assignment_ids, clump);
clump = [];
$("#new_assignment_dialog .cancel_button").click(function(event) {
$("#new_assignment_dialog").dialog('close');
});
$("#add_assignment_form").formSubmit({
beforeSubmit: function(data) {
$(this).find(".submit_button").text(I18n.t('status.adding_assignment', "Adding Assignment..."));
$(this).find("button").attr('disabled', true);
},
success: function(data) {
$(this).find(".submit_button").text(I18n.t('status.added_assignment', "Added Assignment"));
$(this).find("button").attr('disabled', false);
var assignment = data.assignment;
location.href = "#assignment_" + assignment.id;
location.reload();
},
error: function(data) {
$(this).formErrors(data);
$(this).find(".submit_button").text(I18n.t('errors.could_not_add_assignment', "Add Assignment Failed"));
$(this).find("button").attr('disabled', false);
}
});
if(clump.length > 0) {
getClump(pre + "?init=1&submissions=1&user_ids=" + clump.join(",") + "&assignment_ids=" + assignment_ids.join(","), assignment_ids, clump);
}
}, 500);
$("#comment_link").click(function(event) {
event.preventDefault();
event.stopPropagation();
});
$(".options_dropdown").click(function(event) {
event.preventDefault();
});
$("#attendance").bind('entry_over', function(event, grid) {
var keys = grid.cell.attr('id').split("_");
var user_id = keys[1];
var assignment_id = keys[2];
}).bind('entry_out', function(event, grid) {
}).bind('entry_click', function(event, grid) {
grid.trueEvent.preventDefault();
datagrid.focus(grid.cell.row, grid.cell.column);
}).bind('entry_focus', function(event, grid) {
if(grid.cell.row == 0) {
var options = {};
options['<span class="ui-icon ui-icon-pencil">&nbsp;</span> ' + $.htmlEscape(I18n.t('options.edit_assignment', 'Edit Assignment'))] = function() {
location.href = "/";
};
options['<span class="ui-icon ui-icon-check">&nbsp;</span> ' + $.htmlEscape(I18n.t('options.mark_all_as_present', 'Mark Everyone Present'))] = function() {
attendance.toggleColumnState(grid.cell.column, 'pass');
};
options['<span class="ui-icon ui-icon-close">&nbsp;</span> ' + $.htmlEscape(I18n.t('options.mark_all_as_absent', 'Mark Everyone Absent'))] = function() {
attendance.toggleColumnState(grid.cell.column, 'fail');
};
options['<span class="ui-icon ui-icon-minus">&nbsp;</span> ' + $.htmlEscape(I18n.t('options.clear_attendance_marks', 'Clear Attendance Marks'))] = function() {
attendance.toggleColumnState(grid.cell.column, 'clear');
$("#new_assignment_dialog .title").change(function() {
var val = $(this).val();
if (val && val != defaultTitle()) {
$(this).attr('edited', true);
} else {
$(this).removeAttr('edited');
}
grid.cell.find(".options_dropdown").dropdownList({options: options});
} else {
attendance.toggleState(grid.cell);
}
datagrid.blur();
}).bind('entry_blur', function(event, grid) {
});
$(document).keycodes('return p f del', function(event) {
if(datagrid.currentFocus || !datagrid.currentHover) {
return;
}
if($(event.target).closest(".ui-dialog").length > 0) { return; }
var $current = datagrid.currentHover;
if(event.keyString == "return") {
if($current.hasClass('submission')) {
datagrid.focus($current.row, $current.column);
});
function defaultTitle() {
var date = $("#new_assignment_dialog .datetime_field").data('date');
if (date) {
return I18n.t('default_attendance_title', 'Attendance %{date}', {date: I18n.l('#date.formats.default', date)});
} else {
return '';
}
} else if(event.keyString == "p") {
} else if(event.keyString == "f") {
} else if(event.keyString == "del") {
}
});
datagrid.init($("#attendance"), {
borderSize: 2,
onViewable: function() {
$("#attendance_loading_message").hide();
$(document).fragmentChange(function(event, hash) {
if(hash.length > 1) {
hash = hash.substring(1);
$("#new_assignment_dialog .datetime_field").change(function() {
var val = $("#new_assignment_dialog .title").val();
var titleEdited = $("#new_assignment_dialog .title").attr('edited');
if(!val || !titleEdited) {
var date = $(this).data('date');
if(date) {
$("#new_assignment_dialog .title").val(defaultTitle());
}
hash = hash.replace(/\/|%2F/g, "_");
if(hash.indexOf("student") == 0 || hash.indexOf("assignment") == 0 || hash.indexOf("submission") == 0) {
var $div = $("#" + hash),
position = datagrid.position($div),
row = position.row,
col = position.column;
datagrid.scrollTo(row, col);
$div.trigger('mouseover');
}
});
$(".datetime_field").datetime_field();
$(".help_link").click(function(event) {
event.preventDefault();
$("#attendance_how_to_dialog").dialog('close').dialog({
autoOpen: false,
width: 400,
title: I18n.t('titles.attendance_help', "Attendance Help")
}).dialog('open');
});
$(".submission").addClass('loading');
var getClump = function(url, assignment_ids, user_ids) {
$.ajaxJSON(url, "GET", {}, function(data) {
for(var idx in assignment_ids) {
for(var jdx in user_ids) {
$("#submission_" + user_ids[jdx] + "_" + assignment_ids[idx]).removeClass('loading');
}
}
for(var idx in data) {
if(data[idx] && data[idx].submission) {
var grade = data[idx].submission.grade;
var $submission = $("#submission_" + data[idx].submission.user_id + "_" + data[idx].submission.assignment_id);
$submission.removeClass('loading');
if(grade != "pass" && grade != "fail") { grade = "clear"; }
var key = attendance.toggleState($submission, grade, true);
attendance.clearSavingState($submission, key);
}
}
}, function() {
if(errorCount < 5) {
errorCount++;
getClump(url);
}
});
},
onReady: function() {
}
};
var clump_size = Math.round(200 / ($("#attendance .student").length || 1));
var clump = [];
var pre = $(".gradebook_url").attr('href');
setTimeout(function() {
var assignment_ids = [];
$("#attendance .assignment").each(function() {
var id = ($(this).attr('id') || "").split("_").pop(); //.substring(11);
assignment_ids.push(id);
});
$("#attendance .student").each(function() {
var id = ($(this).attr('id') || "").split("_").pop(); //.substring(8);
if(id) {
clump.push(id);
}
if(clump.length > clump_size) {
getClump(pre + "?init=1&submissions=1&user_ids=" + clump.join(",") + "&assignment_ids=" + assignment_ids.join(","), assignment_ids, clump);
clump = [];
}
});
if(clump.length > 0) {
getClump(pre + "?init=1&submissions=1&user_ids=" + clump.join(",") + "&assignment_ids=" + assignment_ids.join(","), assignment_ids, clump);
}
}, 500);
$("#comment_link").click(function(event) {
event.preventDefault();
event.stopPropagation();
});
$(".options_dropdown").click(function(event) {
event.preventDefault();
});
$("#attendance").bind('entry_over', function(event, grid) {
var keys = grid.cell.attr('id').split("_");
var user_id = keys[1];
var assignment_id = keys[2];
}).bind('entry_out', function(event, grid) {
}).bind('entry_click', function(event, grid) {
grid.trueEvent.preventDefault();
datagrid.focus(grid.cell.row, grid.cell.column);
}).bind('entry_focus', function(event, grid) {
if(grid.cell.row == 0) {
var options = {};
options['<span class="ui-icon ui-icon-pencil">&nbsp;</span> ' + $.htmlEscape(I18n.t('options.edit_assignment', 'Edit Assignment'))] = function() {
location.href = "/";
};
options['<span class="ui-icon ui-icon-check">&nbsp;</span> ' + $.htmlEscape(I18n.t('options.mark_all_as_present', 'Mark Everyone Present'))] = function() {
attendance.toggleColumnState(grid.cell.column, 'pass');
};
options['<span class="ui-icon ui-icon-close">&nbsp;</span> ' + $.htmlEscape(I18n.t('options.mark_all_as_absent', 'Mark Everyone Absent'))] = function() {
attendance.toggleColumnState(grid.cell.column, 'fail');
};
options['<span class="ui-icon ui-icon-minus">&nbsp;</span> ' + $.htmlEscape(I18n.t('options.clear_attendance_marks', 'Clear Attendance Marks'))] = function() {
attendance.toggleColumnState(grid.cell.column, 'clear');
}
grid.cell.find(".options_dropdown").dropdownList({options: options});
} else {
attendance.toggleState(grid.cell);
}
datagrid.blur();
}).bind('entry_blur', function(event, grid) {
});
$(document).keycodes('return p f del', function(event) {
if(datagrid.currentFocus || !datagrid.currentHover) {
return;
}
if($(event.target).closest(".ui-dialog").length > 0) { return; }
var $current = datagrid.currentHover;
if(event.keyString == "return") {
if($current.hasClass('submission')) {
datagrid.focus($current.row, $current.column);
}
} else if(event.keyString == "p") {
} else if(event.keyString == "f") {
} else if(event.keyString == "del") {
}
});
datagrid.init($("#attendance"), {
borderSize: 2,
onViewable: function() {
$("#attendance_loading_message").hide();
$(document).fragmentChange(function(event, hash) {
if(hash.length > 1) {
hash = hash.substring(1);
}
hash = hash.replace(/\/|%2F/g, "_");
if(hash.indexOf("student") == 0 || hash.indexOf("assignment") == 0 || hash.indexOf("submission") == 0) {
var $div = $("#" + hash),
position = datagrid.position($div),
row = position.row,
col = position.column;
datagrid.scrollTo(row, col);
$div.trigger('mouseover');
}
});
},
onReady: function() {
}
});
});
});
});

View File

@ -28,137 +28,137 @@ I18n.scoped('collaborations', function(I18n) {
});
}
$(document).ready(function() {
$("#add_collaboration_form").submit(function(event) {
var data = $(this).getFormData();
if(!data['collaboration[title]']) {
$(document).ready(function() {
$("#add_collaboration_form").submit(function(event) {
var data = $(this).getFormData();
if(!data['collaboration[title]']) {
event.preventDefault();
event.stopPropagation();
$(this).find("#collaboration_title").errorBox(I18n.t('errors.no_name', "Please enter a name for this document"));
$("html,body").scrollTo($(this));
return false;
}
setTimeout(function() {
//reload the page but get rid of anything in the hash so that it doesnt automatically
//open the Start a New Collaboration section when it reloads
window.location = window.location.href.replace(window.location.hash, "");
}, 2500);
});
$(".toggle_collaborators_link").live('click', function() {
$(this).parents(".collaboration").find(".collaborators").slideToggle();
});
$(".add_collaboration_link").click(function(event) {
event.preventDefault();
event.stopPropagation();
$(this).find("#collaboration_title").errorBox(I18n.t('errors.no_name', "Please enter a name for this document"));
$("html,body").scrollTo($(this));
return false;
}
setTimeout(function() {
//reload the page but get rid of anything in the hash so that it doesnt automatically
//open the Start a New Collaboration section when it reloads
window.location = window.location.href.replace(window.location.hash, "");
}, 2500);
});
$(".toggle_collaborators_link").live('click', function() {
$(this).parents(".collaboration").find(".collaborators").slideToggle();
});
$(".add_collaboration_link").click(function(event) {
event.preventDefault();
if($(this).is(":hidden")) return;
$(this).hide();
$("#add_collaboration_form").slideToggle(function() {
$("html,body").scrollTo($(this));
$(this).find(":text:visible:first").focus().select();
if($(this).is(":hidden")) return;
$(this).hide();
$("#add_collaboration_form").slideToggle(function() {
$("html,body").scrollTo($(this));
$(this).find(":text:visible:first").focus().select();
});
});
});
$("#add_collaboration_form .cancel_button").click(function(event) {
$(".add_collaboration_link").show();
$("#add_collaboration_form").slideToggle();
});
$("#delete_collaboration_dialog .cancel_button").click(function() {
$("#delete_collaboration_dialog").dialog('close');
});
$("#delete_collaboration_dialog .delete_button").click(function() {
var delete_document = $(this).hasClass('delete_document_button'),
data = {delete_doc: delete_document},
$collaboration = $("#delete_collaboration_dialog").data('collaboration'),
url = $collaboration.find(".delete_collaboration_link").attr('href');
$collaboration.dim();
$("#delete_collaboration_dialog").dialog('close');
$.ajaxJSON(url, 'DELETE', data, function(data) {
removeCollaborationDiv($collaboration);
}, function(data) {
$("#add_collaboration_form .cancel_button").click(function(event) {
$(".add_collaboration_link").show();
$("#add_collaboration_form").slideToggle();
});
});
$(".delete_collaboration_link").click(function(event) {
event.preventDefault();
var $collaboration = $(this).parents(".collaboration");
if($(this).parents(".collaboration").hasClass('google_docs')) {
$("#delete_collaboration_dialog").data('collaboration', $collaboration);
$("#delete_collaboration_dialog").dialog('close').dialog({
autoOpen: false,
title: "Delete Collaboration?",
width: 350
}).dialog('open');
} else {
$collaboration.confirmDelete({
message: "Are you sure you want to delete this collaboration?",
url: $(this).attr('href'),
success: function(data) {
removeCollaborationDiv($(this));
$("#delete_collaboration_dialog .cancel_button").click(function() {
$("#delete_collaboration_dialog").dialog('close');
});
$("#delete_collaboration_dialog .delete_button").click(function() {
var delete_document = $(this).hasClass('delete_document_button'),
data = {delete_doc: delete_document},
$collaboration = $("#delete_collaboration_dialog").data('collaboration'),
url = $collaboration.find(".delete_collaboration_link").attr('href');
$collaboration.dim();
$("#delete_collaboration_dialog").dialog('close');
$.ajaxJSON(url, 'DELETE', data, function(data) {
removeCollaborationDiv($collaboration);
}, function(data) {
});
});
$(".delete_collaboration_link").click(function(event) {
event.preventDefault();
var $collaboration = $(this).parents(".collaboration");
if($(this).parents(".collaboration").hasClass('google_docs')) {
$("#delete_collaboration_dialog").data('collaboration', $collaboration);
$("#delete_collaboration_dialog").dialog('close').dialog({
autoOpen: false,
title: "Delete Collaboration?",
width: 350
}).dialog('open');
} else {
$collaboration.confirmDelete({
message: "Are you sure you want to delete this collaboration?",
url: $(this).attr('href'),
success: function(data) {
removeCollaborationDiv($(this));
}
});
}
});
$(".edit_collaboration_link").click(function(event) {
event.preventDefault();
var $form = $("#edit_collaboration_form").clone(true);
$form.attr('action', $(this).attr('href'));
var $collaboration = $(this).parents(".collaboration");
$form.attr('class', $collaboration.attr('class'));
var ids = [];
var data = $collaboration.getTemplateData({textValues: ['title', 'description']});
$form.fillFormData(data, {object_name: 'collaboration'});
var collaborators = $collaboration.find(".collaborators li").each(function() {
var id = $(this).getTemplateData({textValues: ['id']}).id;
if(id) {
ids.push(id);
}
});
}
});
$(".edit_collaboration_link").click(function(event) {
event.preventDefault();
var $form = $("#edit_collaboration_form").clone(true);
$form.attr('action', $(this).attr('href'));
var $collaboration = $(this).parents(".collaboration");
$form.attr('class', $collaboration.attr('class'));
var ids = [];
var data = $collaboration.getTemplateData({textValues: ['title', 'description']});
$form.fillFormData(data, {object_name: 'collaboration'});
var collaborators = $collaboration.find(".collaborators li").each(function() {
var id = $(this).getTemplateData({textValues: ['id']}).id;
if(id) {
ids.push(id);
$form.find(":checkbox").each(function() {
$(this).attr('checked', false);
});
for(var idx in ids) {
var id = ids[idx];
$form.find(".collaborator_" + id + " :checkbox").attr('checked', true);
}
$collaboration.hide().after($form.show());
});
$("#edit_collaboration_form .cancel_button").click(function() {
var $form = $(this).parents("form");
$form.hide().prev(".collaboration").show();
$form.remove();
});
$(document).fragmentChange(function(event, hash) {
if(hash == "#add_collaboration") {
$(".add_collaboration_link").click();
}
});
$form.find(":checkbox").each(function() {
$(this).attr('checked', false);
$(".collaboration .show_participants_link.verbose_footer_link").click(function(event) {
event.preventDefault();
$(this).parents(".collaboration").find(".collaborators").slideToggle();
});
for(var idx in ids) {
var id = ids[idx];
$form.find(".collaborator_" + id + " :checkbox").attr('checked', true);
}
$collaboration.hide().after($form.show());
});
$("#edit_collaboration_form .cancel_button").click(function() {
var $form = $(this).parents("form");
$form.hide().prev(".collaboration").show();
$form.remove();
});
$(document).fragmentChange(function(event, hash) {
if(hash == "#add_collaboration") {
$(".add_collaboration_link").click();
}
});
$(".collaboration .show_participants_link.verbose_footer_link").click(function(event) {
event.preventDefault();
$(this).parents(".collaboration").find(".collaborators").slideToggle();
});
$("#collaboration_collaboration_type").change(function(event) {
var name = $(this).val();
var type = name;
if(INST.collaboration_types) {
for(var idx in INST.collaboration_types) {
var collab = INST.collaboration_types[idx];
if(collab.name == name) {
type = collab.type;
$("#collaboration_collaboration_type").change(function(event) {
var name = $(this).val();
var type = name;
if(INST.collaboration_types) {
for(var idx in INST.collaboration_types) {
var collab = INST.collaboration_types[idx];
if(collab.name == name) {
type = collab.type;
}
}
}
}
$("#add_collaboration_form .collaboration_type").hide();
var $description = $("#add_collaboration_form #" + type + "_description");
$description.show();
$(".collaborate_data").showIf(!$description.hasClass('unauthorized'));
$(".collaboration_authorization").hide();
$("#collaborate_authorize_" + type).showIf($description.hasClass('unauthorized'));
}).change();
$(".select_all_link,.deselect_all_link").click(function(event) {
event.preventDefault();
var checked = $(this).hasClass('select_all_link');
$(this).parents("form").find(":checkbox").each(function() {
$(this).attr('checked', checked);
$("#add_collaboration_form .collaboration_type").hide();
var $description = $("#add_collaboration_form #" + type + "_description");
$description.show();
$(".collaborate_data").showIf(!$description.hasClass('unauthorized'));
$(".collaboration_authorization").hide();
$("#collaborate_authorize_" + type).showIf($description.hasClass('unauthorized'));
}).change();
$(".select_all_link,.deselect_all_link").click(function(event) {
event.preventDefault();
var checked = $(this).hasClass('select_all_link');
$(this).parents("form").find(":checkbox").each(function() {
$(this).attr('checked', checked);
});
});
});
if($("#collaborations .collaboration:visible").length < 1)
if($("#collaborations .collaboration:visible").length < 1)
$(".add_collaboration_link").click();
});
});
});

View File

@ -17,111 +17,111 @@
*/
I18n.scoped('content_locks', function(I18n) {
INST.lockExplanation = function(data, type) {
// Any additions to this function should also be added to similar logic in ApplicationController.rb
if(data.lock_at) {
switch (type) {
case "quiz":
return I18n.t('messages.quiz_locked_at', "This quiz was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
case "assignment":
return I18n.t('messages.assignment_locked_at', "This assignment was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
case "topic":
return I18n.t('messages.topic_locked_at', "This topic was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
case "file":
return I18n.t('messages.file_locked_at', "This file was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
case "page":
return I18n.t('messages.page_locked_at', "This page was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
default:
return I18n.t('messages.content_locked_at', "This content was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
}
} else if(data.unlock_at) {
switch (type) {
case "quiz":
return I18n.t('messages.quiz_locked_until', "This quiz is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
case "assignment":
return I18n.t('messages.assignment_locked_until', "This assignment is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
case "topic":
return I18n.t('messages.topic_locked_until', "This topic is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
case "file":
return I18n.t('messages.file_locked_until', "This file is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
case "page":
return I18n.t('messages.page_locked_until', "This page is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
default:
return I18n.t('messages.content_locked_until', "This content is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
}
} else if(data.context_module) {
var html = '';
switch (type) {
case "quiz":
html += I18n.t('messages.quiz_locked_module', "This quiz is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
case "assignment":
html += I18n.t('messages.assignment_locked_module', "This assignment is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
case "topic":
html += I18n.t('messages.topic_locked_module', "This topic is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
case "file":
html += I18n.t('messages.file_locked_module', "This file is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
case "page":
html += I18n.t('messages.page_locked_module', "This page is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
default:
html += I18n.t('messages.content_locked_module', "This content is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
}
if ($("#context_modules_url").length > 0) {
html += "<br/>";
html += "<a href='" + $("#context_modules_url").attr('href') + "'>";
html += I18n.t('messages.visit_modules_page_for_details', "Visit the modules page for information on how to unlock this content.");
html += "</a>";
return html;
}
}
else {
switch(type) {
case "quiz":
return I18n.t('messages.quiz_locked_no_reason', "This quiz is locked. No other reason has been provided.");
case "assignment":
return I18n.t('messages.assignment_locked_no_reason', "This assignment is locked. No other reason has been provided.");
case "topic":
return I18n.t('messages.topic_locked_no_reason', "This topic is locked. No other reason has been provided.");
case "file":
return I18n.t('messages.file_locked_no_reason', "This file is locked. No other reason has been provided.");
case "page":
return I18n.t('messages.page_locked_no_reason', "This page is locked. No other reason has been provided.");
default:
return I18n.t('messages.content_locked_no_reason', "This content is locked. No other reason has been provided.");
}
}
}
$(document).ready(function() {
$(".content_lock_icon").live('click', function(event) {
if($(this).data('lock_reason')) {
event.preventDefault();
var data = $(this).data('lock_reason');
var type = data.type;
var $reason = $("<div/>");
$reason.html(INST.lockExplanation(data, type));
var $dialog = $("#lock_reason_dialog");
if($dialog.length === 0) {
$dialog = $("<div/>").attr('id', 'lock_reason_dialog');
$("body").append($dialog.hide());
var $div = ("<div class='lock_reason_content'></div><div class='button-container'><button type='button' class='button'>" +
$.h(I18n.t('buttons.ok_thanks', "Ok, Thanks")) + "</button></div>");
$dialog.append($div);
$dialog.find(".button-container .button").click(function() {
$dialog.dialog('close');
});
INST.lockExplanation = function(data, type) {
// Any additions to this function should also be added to similar logic in ApplicationController.rb
if(data.lock_at) {
switch (type) {
case "quiz":
return I18n.t('messages.quiz_locked_at', "This quiz was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
case "assignment":
return I18n.t('messages.assignment_locked_at', "This assignment was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
case "topic":
return I18n.t('messages.topic_locked_at', "This topic was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
case "file":
return I18n.t('messages.file_locked_at', "This file was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
case "page":
return I18n.t('messages.page_locked_at', "This page was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
default:
return I18n.t('messages.content_locked_at', "This content was locked %{at}.", {at: $.parseFromISO(data.lock_at).datetime_formatted});
}
} else if(data.unlock_at) {
switch (type) {
case "quiz":
return I18n.t('messages.quiz_locked_until', "This quiz is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
case "assignment":
return I18n.t('messages.assignment_locked_until', "This assignment is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
case "topic":
return I18n.t('messages.topic_locked_until', "This topic is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
case "file":
return I18n.t('messages.file_locked_until', "This file is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
case "page":
return I18n.t('messages.page_locked_until', "This page is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
default:
return I18n.t('messages.content_locked_until', "This content is locked until %{date}.", {date: $.parseFromISO(data.unlock_at).datetime_formatted});
}
} else if(data.context_module) {
var html = '';
switch (type) {
case "quiz":
html += I18n.t('messages.quiz_locked_module', "This quiz is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
case "assignment":
html += I18n.t('messages.assignment_locked_module', "This assignment is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
case "topic":
html += I18n.t('messages.topic_locked_module', "This topic is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
case "file":
html += I18n.t('messages.file_locked_module', "This file is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
case "page":
html += I18n.t('messages.page_locked_module', "This page is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
default:
html += I18n.t('messages.content_locked_module', "This content is part of the module *%{module}* and hasn't been unlocked yet.", {module: $.htmlEscape(data.context_module.name), wrapper: '<b>$1</b>'});
break;
}
if ($("#context_modules_url").length > 0) {
html += "<br/>";
html += "<a href='" + $("#context_modules_url").attr('href') + "'>";
html += I18n.t('messages.visit_modules_page_for_details', "Visit the modules page for information on how to unlock this content.");
html += "</a>";
return html;
}
$dialog.find(".lock_reason_content").empty().append($reason);
$dialog.dialog('close').dialog({
autoOpen: false,
title: I18n.t('titles.content_is_locked', "Content Is Locked")
}).dialog('open');
}
else {
switch(type) {
case "quiz":
return I18n.t('messages.quiz_locked_no_reason', "This quiz is locked. No other reason has been provided.");
case "assignment":
return I18n.t('messages.assignment_locked_no_reason', "This assignment is locked. No other reason has been provided.");
case "topic":
return I18n.t('messages.topic_locked_no_reason', "This topic is locked. No other reason has been provided.");
case "file":
return I18n.t('messages.file_locked_no_reason', "This file is locked. No other reason has been provided.");
case "page":
return I18n.t('messages.page_locked_no_reason', "This page is locked. No other reason has been provided.");
default:
return I18n.t('messages.content_locked_no_reason', "This content is locked. No other reason has been provided.");
}
}
}
$(document).ready(function() {
$(".content_lock_icon").live('click', function(event) {
if($(this).data('lock_reason')) {
event.preventDefault();
var data = $(this).data('lock_reason');
var type = data.type;
var $reason = $("<div/>");
$reason.html(INST.lockExplanation(data, type));
var $dialog = $("#lock_reason_dialog");
if($dialog.length === 0) {
$dialog = $("<div/>").attr('id', 'lock_reason_dialog');
$("body").append($dialog.hide());
var $div = ("<div class='lock_reason_content'></div><div class='button-container'><button type='button' class='button'>" +
$.h(I18n.t('buttons.ok_thanks', "Ok, Thanks")) + "</button></div>");
$dialog.append($div);
$dialog.find(".button-container .button").click(function() {
$dialog.dialog('close');
});
}
$dialog.find(".lock_reason_content").empty().append($reason);
$dialog.dialog('close').dialog({
autoOpen: false,
title: I18n.t('titles.content_is_locked', "Content Is Locked")
}).dialog('open');
}
});
});
});
});

View File

@ -17,166 +17,166 @@
*/
I18n.scoped('content_tags', function(I18n) {
var contentTags = {
currentHover: null,
hoverCount: -1,
checkForHover: function() {
if(contentTags.hoverCount >= 0) {
if(contentTags.currentHover == null) {
var contentTags = {
currentHover: null,
hoverCount: -1,
checkForHover: function() {
if(contentTags.hoverCount >= 0) {
if(contentTags.currentHover == null) {
contentTags.hoverCount = -1;
return;
}
contentTags.hoverCount++;
if(contentTags.hoverCount > 4) {
contentTags.currentHover.click();
}
}
}
};
$(document).ready(function() {
$("#tags .tag_name").click(function(event) {
$("#tags .tag_name.selected").removeClass('selected');
$(this).parents(".tag_list").scrollTo($(this));
$(this).addClass('selected');
event.preventDefault();
var name = $(this).getTemplateData({textValues: ['name']}).name.toLowerCase().replace(/\s/g, "_");
$("#pages_for_tags").find(".page").hide();
var $tags = $("#pages_for_tags").find(".page.tag_named_" + name);
var group_id = $(this).parents(".context_tags").attr('id');
if(group_id != "tags_for_all") {
$tags = $tags.filter("." + group_id.replace(/^tags_for/, "page_for"));
}
var found_urls = {};
$tags.each(function() {
found_urls[$(this).find(".title").attr('href') + "::" + $(this).find(".title").text()] = true;
$(this).show();
});
});
$("#tags").accordion({
header: ".header",
fillSpace: true,
alwaysOpen: true
}).bind('accordionchange', function(event, ui) {
$("#pages_for_tags .page").hide();
$(ui.newContent).filter(":first").click();
});
$("#tags_for_all .tag_list .tag_name:first").click();
$(".content_tags_description_link").click(function(event) {
event.preventDefault();
$("#content_tags_details_dialog").dialog({
title: "What Are Content Tags?"
});
});
$(".page").click(function(event) {
if($(this).hasClass('selected')) { return; }
if($(event.target).closest("a").length > 0) { return; }
event.preventDefault();
$("#pages_for_tags .page.selected").removeClass('selected')
.find(".comments").slideUp();
$(this).addClass('selected')
.find(".comments").slideDown();
});
$(".page").hover(function() {
contentTags.currentHover = $(this);
contentTags.hoverCount = 0;
}, function() {
if(contentTags.currentHover && contentTags.currentHover[0] == $(this)[0]) {
contentTags.currentHover = null;
contentTags.hoverCount = -1;
return;
}
contentTags.hoverCount++;
if(contentTags.hoverCount > 4) {
contentTags.currentHover.click();
}
}
}
};
$(document).ready(function() {
$("#tags .tag_name").click(function(event) {
$("#tags .tag_name.selected").removeClass('selected');
$(this).parents(".tag_list").scrollTo($(this));
$(this).addClass('selected');
event.preventDefault();
var name = $(this).getTemplateData({textValues: ['name']}).name.toLowerCase().replace(/\s/g, "_");
$("#pages_for_tags").find(".page").hide();
var $tags = $("#pages_for_tags").find(".page.tag_named_" + name);
var group_id = $(this).parents(".context_tags").attr('id');
if(group_id != "tags_for_all") {
$tags = $tags.filter("." + group_id.replace(/^tags_for/, "page_for"));
}
var found_urls = {};
$tags.each(function() {
found_urls[$(this).find(".title").attr('href') + "::" + $(this).find(".title").text()] = true;
$(this).show();
});
});
$("#tags").accordion({
header: ".header",
fillSpace: true,
alwaysOpen: true
}).bind('accordionchange', function(event, ui) {
$("#pages_for_tags .page").hide();
$(ui.newContent).filter(":first").click();
});
$("#tags_for_all .tag_list .tag_name:first").click();
$(".content_tags_description_link").click(function(event) {
event.preventDefault();
$("#content_tags_details_dialog").dialog({
title: "What Are Content Tags?"
});
});
$(".page").click(function(event) {
if($(this).hasClass('selected')) { return; }
if($(event.target).closest("a").length > 0) { return; }
event.preventDefault();
$("#pages_for_tags .page.selected").removeClass('selected')
.find(".comments").slideUp();
$(this).addClass('selected')
.find(".comments").slideDown();
});
$(".page").hover(function() {
contentTags.currentHover = $(this);
contentTags.hoverCount = 0;
}, function() {
if(contentTags.currentHover && contentTags.currentHover[0] == $(this)[0]) {
contentTags.currentHover = null;
contentTags.hoverCount = -1;
}
});
setInterval(contentTags.checkForHover, 200);
$(".page .delete_page_link").click(function(event) {
event.preventDefault();
$(this).parents(".page").confirmDelete({
message: I18n.t('prompts.delete_tag', "Are you sure you want to delete this tag?"),
url: $(this).attr('href'),
success: function() {
$(this).slideUp(function() {
$(this).remove();
});
}
});
});
$(".add_external_tag_link").click(function(event) {
event.preventDefault();
$("#external_tag_dialog").dialog({
title: I18n.t('titles.tag_external_web_page', "Tag External Web Page"),
width: 400,
open: function() {
var data = {
url: "http://",
title: I18n.t('defaults.page_title', "Page Title"),
comments: I18n.t('defaults.comments', "Comments")
};
$(this).fillFormData(data, {object_name: 'tag'});
$(this).find(":text:visible:first").focus().select();
setInterval(contentTags.checkForHover, 200);
$(".page .delete_page_link").click(function(event) {
event.preventDefault();
$(this).parents(".page").confirmDelete({
message: I18n.t('prompts.delete_tag', "Are you sure you want to delete this tag?"),
url: $(this).attr('href'),
success: function() {
$(this).slideUp(function() {
$(this).remove();
});
}
});
});
$(".add_external_tag_link").click(function(event) {
event.preventDefault();
$("#external_tag_dialog").dialog({
title: I18n.t('titles.tag_external_web_page', "Tag External Web Page"),
width: 400,
open: function() {
var data = {
url: "http://",
title: I18n.t('defaults.page_title', "Page Title"),
comments: I18n.t('defaults.comments', "Comments")
};
$(this).fillFormData(data, {object_name: 'tag'});
$(this).find(":text:visible:first").focus().select();
}
}).dialog('open');
});
$("#add_external_tag_form").formSubmit({
beforeSubmit: function(data) {
$(this).loadingImage();
},
success: function(data) {
$(this).loadingImage('remove');
$("#external_tag_dialog").dialog('close');
for(var idx in data) {
var tag = data[idx];
$(document).triggerHandler('tag_added', tag);
}
}
}).dialog('open');
});
$(document).bind('tag_added', function(event, tag) {
var $context = $("#tags_for_" + tag.context_type.toLowerCase() + "_" + tag.context_id);
var $match_context = addTagToContext($context, tag);
var $match_all = addTagToContext($("#tags_for_all"), tag);
var $page = $("#page_blank").clone(true).removeAttr('id');
$page.find(".title").attr('href', tag.url).text(tag.title);
$page.find(".comments").text(tag.comments);
$page.find(".delete_page_link").attr('href', $.replaceTags($page.find(".delete_page_link").attr('href'), 'id', tag.id));
$page.addClass('page_for_' + tag.context_type.toLowerCase() + "_" + tag.context_id)
.addClass('tag_named_' + tag.tag.toLowerCase().replace(/ /g, "_"));
$("#pages_for_tags").prepend($page);
$("#content_tags_description").hide();
$("#content_tags_table").show();
$("#personal_tags_message").hide();
$match_context.filter(":visible").click();
$match_all.filter(":visible").click();
$(window).triggerHandler('resize');
});
$(document).fragmentChange(function(event, hash) {
hash = hash || "";
var tag = hash.substring(1);
$(".ui-accordion-content-active").find(".tag_name." + tag).click();
});
$(window).resize(function() {
var windowHeight = $(window).height();
var tableTop = $("#tags").offset().top;
var tableHeight = Math.max(windowHeight - tableTop, 200) - 10;
$("#tags,#pages_for_tags").height(tableHeight);
if($.browser.msie && navigator.appVersion.match('MSIE 6.0')) { return; }
$("#tags").accordion('resize');
}).triggerHandler('resize');
});
$("#add_external_tag_form").formSubmit({
beforeSubmit: function(data) {
$(this).loadingImage();
},
success: function(data) {
$(this).loadingImage('remove');
$("#external_tag_dialog").dialog('close');
for(var idx in data) {
var tag = data[idx];
$(document).triggerHandler('tag_added', tag);
function addTagToContext($context, tag) {
var $match = null;
$context.find(".tag_list .tag_name").each(function() {
var name = $(this).find(".name").text();
if(name == tag.tag) {
$match = $(this);
} else if(tag.tag > name) {
$match = $("#tag_name_blank").clone(true).removeAttr('id');
$match.find(".name").text(tag.tag);
$(this).before($match);
}
}
});
$(document).bind('tag_added', function(event, tag) {
var $context = $("#tags_for_" + tag.context_type.toLowerCase() + "_" + tag.context_id);
var $match_context = addTagToContext($context, tag);
var $match_all = addTagToContext($("#tags_for_all"), tag);
var $page = $("#page_blank").clone(true).removeAttr('id');
$page.find(".title").attr('href', tag.url).text(tag.title);
$page.find(".comments").text(tag.comments);
$page.find(".delete_page_link").attr('href', $.replaceTags($page.find(".delete_page_link").attr('href'), 'id', tag.id));
$page.addClass('page_for_' + tag.context_type.toLowerCase() + "_" + tag.context_id)
.addClass('tag_named_' + tag.tag.toLowerCase().replace(/ /g, "_"));
$("#pages_for_tags").prepend($page);
$("#content_tags_description").hide();
$("#content_tags_table").show();
$("#personal_tags_message").hide();
$match_context.filter(":visible").click();
$match_all.filter(":visible").click();
$(window).triggerHandler('resize');
});
$(document).fragmentChange(function(event, hash) {
hash = hash || "";
var tag = hash.substring(1);
$(".ui-accordion-content-active").find(".tag_name." + tag).click();
});
$(window).resize(function() {
var windowHeight = $(window).height();
var tableTop = $("#tags").offset().top;
var tableHeight = Math.max(windowHeight - tableTop, 200) - 10;
$("#tags,#pages_for_tags").height(tableHeight);
if($.browser.msie && navigator.appVersion.match('MSIE 6.0')) { return; }
$("#tags").accordion('resize');
}).triggerHandler('resize');
});
function addTagToContext($context, tag) {
var $match = null;
$context.find(".tag_list .tag_name").each(function() {
var name = $(this).find(".name").text();
if(name == tag.tag) {
$match = $(this);
} else if(tag.tag > name) {
$match = $("#tag_name_blank").clone(true).removeAttr('id');
if($match) { return false; }
});
if($match == null) {
var $match = $("#tag_name_blank").clone(true).removeAttr('id');
$match.find(".name").text(tag.tag);
$(this).before($match);
$context.find(".tag_list").append($match);
}
if($match) { return false; }
});
if($match == null) {
var $match = $("#tag_name_blank").clone(true).removeAttr('id');
$match.find(".name").text(tag.tag);
$context.find(".tag_list").append($match);
return $match;
}
return $match;
}
});

File diff suppressed because it is too large Load Diff

View File

@ -19,294 +19,294 @@ var GradebookUploader;
I18n.scoped('gradebook', function(I18n) {
GradebookUploader = {
init:function(){
var gradebookGrid,
mergedGradebook = $.extend(true, {}, originalGradebook),
$gradebook_grid = $("#gradebook_grid"),
gridData = {
columns: [
{
id:"student",
name:I18n.t('student', "Student"),
field:"student",
width:250,
cssClass:"cell-title",
editor:StudentNameEditor,
validator:requiredFieldValidator,
formatter: StudentNameFormatter
}
],
options: {
enableAddRow: false,
enableColumnReorder: false,
asyncEditorLoading: true
},
data: []
};
GradebookUploader = {
init:function(){
var gradebookGrid,
mergedGradebook = $.extend(true, {}, originalGradebook),
$gradebook_grid = $("#gradebook_grid"),
gridData = {
columns: [
{
id:"student",
name:I18n.t('student', "Student"),
field:"student",
width:250,
cssClass:"cell-title",
editor:StudentNameEditor,
validator:requiredFieldValidator,
formatter: StudentNameFormatter
}
],
options: {
enableAddRow: false,
enableColumnReorder: false,
asyncEditorLoading: true
},
data: []
};
$.each(mergedGradebook.assignments, function(){
gridData.columns.push({
id: this.id,
name: $.htmlEscape(this.title),
field: this.id,
width:200,
editor: NullGradeEditor,
formatter: simpleGradeCellFormatter,
_original: this
});
});
$.each(mergedGradebook.students, function(){
var row = {
"student" : this,
"id" : this.id,
"_original" : this
};
$.each(this.submissions, function(){
row[this.assignment_id] = this;
row[this.assignment_id]._original = $.extend({}, this);
});
gridData.data.push(row);
});
$.each(uploadedGradebook.assignments, function(){
var col,
assignment = this;
if (this.original_id) {
col = _.detect(gridData.columns, function(column){
return (column._original && column._original.id == assignment.original_id);
});
col.cssClass = "active changed";
}
else {
col = {
id: assignment.id,
name: $.htmlEscape(assignment.title),
field: assignment.id,
$.each(mergedGradebook.assignments, function(){
gridData.columns.push({
id: this.id,
name: $.htmlEscape(this.title),
field: this.id,
width:200,
editor: NullGradeEditor,
formatter: simpleGradeCellFormatter,
cssClass: "active new"
_original: this
});
});
$.each(mergedGradebook.students, function(){
var row = {
"student" : this,
"id" : this.id,
"_original" : this
};
gridData.columns.push(col);
}
col.editor = GradeCellEditor;
col.active = true;
col._uploaded = assignment;
col.setValueHandler = function(value, assignment, student){
if (student[assignment.id]) {
student[assignment.id].grade = student[assignment.id]._uploaded.grade = value;
//there was already an uploaded submission for this assignment, update it
$.each(this.submissions, function(){
row[this.assignment_id] = this;
row[this.assignment_id]._original = $.extend({}, this);
});
gridData.data.push(row);
});
$.each(uploadedGradebook.assignments, function(){
var col,
assignment = this;
if (this.original_id) {
col = _.detect(gridData.columns, function(column){
return (column._original && column._original.id == assignment.original_id);
});
col.cssClass = "active changed";
}
else {
//they did not upload a score for this assignment. create a submission and link it.
var submission = {
grade: value,
assignment_id: assignment.id
col = {
id: assignment.id,
name: $.htmlEscape(assignment.title),
field: assignment.id,
formatter: simpleGradeCellFormatter,
cssClass: "active new"
};
submission._uploaded = submission;
var arrayLength = student._uploaded.submissions.push(submission);
student[assignment.id] = student._uploaded.submissions[arrayLength - 1];
gridData.columns.push(col);
}
};
col.editor = GradeCellEditor;
col.active = true;
col._uploaded = assignment;
col.setValueHandler = function(value, assignment, student){
if (student[assignment.id]) {
student[assignment.id].grade = student[assignment.id]._uploaded.grade = value;
//there was already an uploaded submission for this assignment, update it
}
else {
//they did not upload a score for this assignment. create a submission and link it.
var submission = {
grade: value,
assignment_id: assignment.id
};
submission._uploaded = submission;
var arrayLength = student._uploaded.submissions.push(submission);
student[assignment.id] = student._uploaded.submissions[arrayLength - 1];
}
};
});
});
$.each(uploadedGradebook.students, function(){
var row,
student = this;
if (student.original_id) {
row = _.detect(gridData.data, function(row){
return (row._original && row._original.id == student.original_id);
});
}
else {
row = {
id: student.id,
student: student
};
gridData.data.push(row);
}
$.each(student.submissions, function(){
// when we get to here, if the student didnt have a submission for this assignment in the originalGradebook, it wont have anything in row[this.assignment_id]
// so we check if row[this.assignment_id] is there, and if it is, extend it with this submission (so it gets a new grade).
row[this.assignment_id] = row[this.assignment_id] ? $.extend(row[this.assignment_id], this) : this;
if(!row[this.assignment_id]._original && this.grade) {
row[this.assignment_id]._original = {score: null};
}
row[this.assignment_id]._uploaded = this;
});
row.active = true;
row._uploaded = student;
});
// only show the columns where there were submissions that have grades that have changed.
var oldGridDataLength = gridData.columns.length;
gridData.columns = _.select(gridData.columns, function(col){
return col.id === "student" || _.detect(gridData.data, function(row){
return row[col.id] &&
row[col.id]._original &&
row[col.id]._uploaded &&
row[col.id]._original.score != row[col.id]._uploaded.grade;
});
});
// if there are still assignments with changes detected.
if (gridData.columns.length > 1) {
if (gridData.columns.length < oldGridDataLength) {
$("#assignments_without_changes_alert").show();
}
$("#gradebook_grid_form").submit(function(e){
//we use this function to get rid of the infinate nesting like
//uploadedGradebook.students[0]._original._original._original etc...
//so that when we convert it to json we dont get an infinate loop.
var flattenRecursiveObjects = function(i,o){
$.each(["_original", "_uploaded"], function(i, j){
if(o[j]){
var flattened = $.extend({}, o[j]);
delete o[j];
delete flattened[j];
o[j] = flattened;
}
});
};
$.each(uploadedGradebook.students, function(){
$.each(this.submissions, flattenRecursiveObjects);
});
$(this).find("input[name='json_data_to_submit']").val(JSON.stringify(uploadedGradebook));
}).show();
$(window).resize(function(){
$gradebook_grid.height( $(window).height() - $gradebook_grid.offset().top - 50 );
}).triggerHandler("resize");
gradebookGrid = new SlickGrid($gradebook_grid, gridData.data, gridData.columns, gridData.options);
gradebookGrid.onColumnHeaderClick = function(columnDef) { /*do nothing*/};
}
else {
$("#no_changes_detected").show();
}
},
handleThingsNeedingToBeResolved: function(){
var needingReview = {},
possibilitiesToMergeWith = {};
// do this because I had to use the active_assignments has many relationship because we dont want to see deleted assignments.
// but everthing else here expects there to be an originalGradebook.assignments array.
originalGradebook.assignments = originalGradebook.active_assignments;
// first, figure out if there is anything that needs to be resolved
$.each(["student", "assignment"], function(i, thing){
var $template = $("#" + thing + "_resolution_template").remove(),
$select = $template.find("select");
needingReview[thing] = [];
$.each(uploadedGradebook[thing+"s"], function(){
if (!this.original_id) {
needingReview[thing].push(this);
}
});
if (needingReview[thing].length) {
$select.change(function(){
$(this).next(".points_possible_section").css({opacity: 0});
if($(this).val() > 0) { //if the thing that was selected is an id( not ignore or add )
$("#" + thing + "_resolution_template select option").removeAttr("disabled");
$("#" + thing + "_resolution_template select").each(function(){
$("#" + thing + "_resolution_template select").not(this).find("option[value='" + $(this).val() + "']").attr("disabled", true);
});
}
else if ( $(this).val() === "new" ) {
$(this).next(".points_possible_section").css({opacity: 1});
}
});
possibilitiesToMergeWith[thing] = _.reject(originalGradebook[thing+"s"], function(thng){
return _.detect(uploadedGradebook[thing+"s"], function(newThng){
return newThng.original_id == thng.id;
});
});
$.each(possibilitiesToMergeWith[thing], function() {
$('<option value="' + this.id + '" >' + $.htmlEscape(this.name || this.title) + '</option>').appendTo($select);
});
$.each(needingReview[thing], function(i, record){
$template
.clone(true)
.fillTemplateData({
iterator: record.id,
data: {
name: record.name,
title: record.title,
points_possible: record.points_possible
}
})
.appendTo("#gradebook_importer_resolution_section ." + thing + "_section table tbody")
.show()
.find("input.points_possible")
.change(function(){
record.points_possible = $(this).val();
});
});
$("#gradebook_importer_resolution_section, #gradebook_importer_resolution_section ." + thing + "_section").show();
}
});
// end figuring out if thigs need to be resolved
if ( needingReview.student.length || needingReview.assignment.length ) {
// if there are things that need to be resolved, set up stuff for that form
$("#gradebook_importer_resolution_section").submit(function(e){
var returnFalse = false;
e.preventDefault();
$(this).find("select").each(function(){
if( !$(this).val() ) {
returnFalse = true;
$(this).errorBox(I18n.t('errors.select_an_option', "Please select an option"));
return false;
}
});
if(returnFalse) return false;
$(this).find("select").each(function(){
var $select = $(this),
parts = $select.attr("name").split("_"),
thing = parts[0],
id = parts[1],
val = $select.val();
switch(val){
case "new":
//do nothing
break;
case "ignore":
//remove the entry from the uploaded gradebook
for (var i in uploadedGradebook[thing+"s"]) {
if (id == uploadedGradebook[thing+"s"][i].id) {
uploadedGradebook[thing+"s"].splice(i, 1);
break;
}
}
break;
default:
//merge
_.detect(uploadedGradebook[thing+"s"], function(thng){
return id == thng.id;
}).original_id = val;
}
});
$(this).hide();
GradebookUploader.init();
$.each(uploadedGradebook.students, function(){
var row,
student = this;
if (student.original_id) {
row = _.detect(gridData.data, function(row){
return (row._original && row._original.id == student.original_id);
});
}
else {
row = {
id: student.id,
student: student
};
gridData.data.push(row);
}
$.each(student.submissions, function(){
// when we get to here, if the student didnt have a submission for this assignment in the originalGradebook, it wont have anything in row[this.assignment_id]
// so we check if row[this.assignment_id] is there, and if it is, extend it with this submission (so it gets a new grade).
row[this.assignment_id] = row[this.assignment_id] ? $.extend(row[this.assignment_id], this) : this;
if(!row[this.assignment_id]._original && this.grade) {
row[this.assignment_id]._original = {score: null};
}
row[this.assignment_id]._uploaded = this;
});
row.active = true;
row._uploaded = student;
});
// only show the columns where there were submissions that have grades that have changed.
var oldGridDataLength = gridData.columns.length;
gridData.columns = _.select(gridData.columns, function(col){
return col.id === "student" || _.detect(gridData.data, function(row){
return row[col.id] &&
row[col.id]._original &&
row[col.id]._uploaded &&
row[col.id]._original.score != row[col.id]._uploaded.grade;
});
});
// if there are still assignments with changes detected.
if (gridData.columns.length > 1) {
if (gridData.columns.length < oldGridDataLength) {
$("#assignments_without_changes_alert").show();
}
$("#gradebook_grid_form").submit(function(e){
//we use this function to get rid of the infinate nesting like
//uploadedGradebook.students[0]._original._original._original etc...
//so that when we convert it to json we dont get an infinate loop.
var flattenRecursiveObjects = function(i,o){
$.each(["_original", "_uploaded"], function(i, j){
if(o[j]){
var flattened = $.extend({}, o[j]);
delete o[j];
delete flattened[j];
o[j] = flattened;
}
});
};
$.each(uploadedGradebook.students, function(){
$.each(this.submissions, flattenRecursiveObjects);
});
$(this).find("input[name='json_data_to_submit']").val(JSON.stringify(uploadedGradebook));
}).show();
$(window).resize(function(){
$gradebook_grid.height( $(window).height() - $gradebook_grid.offset().top - 50 );
}).triggerHandler("resize");
gradebookGrid = new SlickGrid($gradebook_grid, gridData.data, gridData.columns, gridData.options);
gradebookGrid.onColumnHeaderClick = function(columnDef) { /*do nothing*/};
}
else {
$("#no_changes_detected").show();
}
},
handleThingsNeedingToBeResolved: function(){
var needingReview = {},
possibilitiesToMergeWith = {};
// do this because I had to use the active_assignments has many relationship because we dont want to see deleted assignments.
// but everthing else here expects there to be an originalGradebook.assignments array.
originalGradebook.assignments = originalGradebook.active_assignments;
// first, figure out if there is anything that needs to be resolved
$.each(["student", "assignment"], function(i, thing){
var $template = $("#" + thing + "_resolution_template").remove(),
$select = $template.find("select");
needingReview[thing] = [];
$.each(uploadedGradebook[thing+"s"], function(){
if (!this.original_id) {
needingReview[thing].push(this);
}
});
if (needingReview[thing].length) {
$select.change(function(){
$(this).next(".points_possible_section").css({opacity: 0});
if($(this).val() > 0) { //if the thing that was selected is an id( not ignore or add )
$("#" + thing + "_resolution_template select option").removeAttr("disabled");
$("#" + thing + "_resolution_template select").each(function(){
$("#" + thing + "_resolution_template select").not(this).find("option[value='" + $(this).val() + "']").attr("disabled", true);
});
}
else if ( $(this).val() === "new" ) {
$(this).next(".points_possible_section").css({opacity: 1});
}
});
possibilitiesToMergeWith[thing] = _.reject(originalGradebook[thing+"s"], function(thng){
return _.detect(uploadedGradebook[thing+"s"], function(newThng){
return newThng.original_id == thng.id;
});
});
$.each(possibilitiesToMergeWith[thing], function() {
$('<option value="' + this.id + '" >' + $.htmlEscape(this.name || this.title) + '</option>').appendTo($select);
});
$.each(needingReview[thing], function(i, record){
$template
.clone(true)
.fillTemplateData({
iterator: record.id,
data: {
name: record.name,
title: record.title,
points_possible: record.points_possible
}
})
.appendTo("#gradebook_importer_resolution_section ." + thing + "_section table tbody")
.show()
.find("input.points_possible")
.change(function(){
record.points_possible = $(this).val();
});
});
$("#gradebook_importer_resolution_section, #gradebook_importer_resolution_section ." + thing + "_section").show();
}
});
// end figuring out if thigs need to be resolved
if ( needingReview.student.length || needingReview.assignment.length ) {
// if there are things that need to be resolved, set up stuff for that form
$("#gradebook_importer_resolution_section").submit(function(e){
var returnFalse = false;
e.preventDefault();
$(this).find("select").each(function(){
if( !$(this).val() ) {
returnFalse = true;
$(this).errorBox(I18n.t('errors.select_an_option', "Please select an option"));
return false;
}
});
if(returnFalse) return false;
$(this).find("select").each(function(){
var $select = $(this),
parts = $select.attr("name").split("_"),
thing = parts[0],
id = parts[1],
val = $select.val();
switch(val){
case "new":
//do nothing
break;
case "ignore":
//remove the entry from the uploaded gradebook
for (var i in uploadedGradebook[thing+"s"]) {
if (id == uploadedGradebook[thing+"s"][i].id) {
uploadedGradebook[thing+"s"].splice(i, 1);
break;
}
}
break;
default:
//merge
_.detect(uploadedGradebook[thing+"s"], function(thng){
return id == thng.id;
}).original_id = val;
}
});
$(this).hide();
// if there is nothing that needs to resolved, just skip to initialize slick grid.
GradebookUploader.init();
});
}
else {
// if there is nothing that needs to resolved, just skip to initialize slick grid.
GradebookUploader.init();
}
}
}
};
};
})

File diff suppressed because it is too large Load Diff

View File

@ -16,104 +16,104 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
I18n.scoped("learning_outcome", function(I18n) {
$(document).ready(function() {
$('#outcome_results').pageless({
totalPages: parseInt($("#outcome_results_total_pages").text(), 10) || 1,
url: $(".outcome_results_url").attr('href'),
loaderMsg: I18n.t("loading_more_results", "Loading more results"),
scrape: function(data) {
if(typeof(data) == 'string') {
try {
data = JSON.parse(data);
} catch(e) {
data = [];
$(document).ready(function() {
$('#outcome_results').pageless({
totalPages: parseInt($("#outcome_results_total_pages").text(), 10) || 1,
url: $(".outcome_results_url").attr('href'),
loaderMsg: I18n.t("loading_more_results", "Loading more results"),
scrape: function(data) {
if(typeof(data) == 'string') {
try {
data = JSON.parse(data);
} catch(e) {
data = [];
}
}
}
for(var idx in data) {
var result = data[idx].learning_outcome_result;
var $result = $("#result_blank").clone(true).attr('id', 'result_' + result.id);
result.assessed_at_formatted = $.parseFromISO(result.assessed_at).datetime_formatted;
$result.toggleClass('mastery_result', !!result.mastery);
$result.fillTemplateData({data: result, except: ['mastery'], hrefValues: ['id', 'user_id']});
$("#outcome_results_list").append($result);
$result.show();
}
return "";
}
});
$(".delete_alignment_link").click(function(event) {
event.preventDefault();
$(this).parents(".alignment").confirmDelete({
url: $(this).attr('href'),
message: I18n.t("remove_outcome_alignment", "Are you sure you want to remove this alignment?"),
success: function(data) {
$(this).slideUp(function() {
$(this).remove();
});
for(var idx in data) {
var result = data[idx].learning_outcome_result;
var $result = $("#result_blank").clone(true).attr('id', 'result_' + result.id);
result.assessed_at_formatted = $.parseFromISO(result.assessed_at).datetime_formatted;
$result.toggleClass('mastery_result', !!result.mastery);
$result.fillTemplateData({data: result, except: ['mastery'], hrefValues: ['id', 'user_id']});
$("#outcome_results_list").append($result);
$result.show();
}
return "";
}
});
});
$("#alignments.orderable").sortable({
axis: 'y',
handle: '.move_alignment_link',
update: function(event, ui) {
var ids = [];
$("#alignments .alignment").each(function() {
ids.push($(this).getTemplateData({textValues: ['id']}).id);
$(".delete_alignment_link").click(function(event) {
event.preventDefault();
$(this).parents(".alignment").confirmDelete({
url: $(this).attr('href'),
message: I18n.t("remove_outcome_alignment", "Are you sure you want to remove this alignment?"),
success: function(data) {
$(this).slideUp(function() {
$(this).remove();
});
}
});
var url = $("#outcome_urls .reorder_alignments_url:last").attr('href');
$.ajaxJSON(url, 'POST', {order: ids.join(",")}, function(data) {
}, function() { });
}
});
var addAlignment = function(data) {
data.title = data['item[title]'] || data.title;
var $alignment = $("#alginment_" + data.id);
if($alignment.length === 0) {
$alignment = $("#alignment_blank").clone(true).removeAttr('id');
}
$alignment.addClass($.underscore(data.content_type));
var desc = $.titleize(data.content_type) || "Alignment";
$alignment.find(".type_icon").attr('alt', desc).attr('title', desc);
$alignment.attr('id', 'alignment_' + (data.id || "new"));
var hrefValues = ['user_id'];
if(data.id) { hrefValues = ['user_id', 'id']; }
$alignment.fillTemplateData({
data: data,
hrefValues: hrefValues
});
$("#alignments").append($alignment.show());
return $alignment;
};
$(".add_outcome_alignment_link").live('click', function(event) {
event.preventDefault();
if(INST && INST.selectContentDialog) {
var options = {for_modules: false};
options.select_button_text = I18n.t("align_item", "Align Item");
options.holder_name = I18n.t("this_outcome", "this Outcome");
options.dialog_title = I18n.t("align_to_outcome", "Align Item to this Outcome");
options.submit = function(item_data) {
var $item = addAlignment(item_data);
var url = $("#outcome_urls .align_url").attr('href');
item_data['asset_string'] = item_data['item[type]'] + "_" + item_data['item[id]'];
$item.loadingImage({image_size: 'small'});
$.ajaxJSON(url, 'POST', item_data, function(data) {
$item.loadingImage('remove');
$item.remove();
addAlignment(data.content_tag);
$("#alignments.orderable").sortable('refresh');
$("#alignments.orderable").sortable({
axis: 'y',
handle: '.move_alignment_link',
update: function(event, ui) {
var ids = [];
$("#alignments .alignment").each(function() {
ids.push($(this).getTemplateData({textValues: ['id']}).id);
});
};
INST.selectContentDialog(options);
}
});
$("#artifacts li").live('mouseover', function() {
$(".hover_alignment,.hover_artifact").removeClass('hover_alignment').removeClass('hover_artifact');
$(this).addClass('hover_artifact');
});
$("#alignments li").live('mouseover', function() {
$(".hover_alignment,.hover_artifact").removeClass('hover_alignment').removeClass('hover_artifact');
$(this).addClass('hover_alignment');
var url = $("#outcome_urls .reorder_alignments_url:last").attr('href');
$.ajaxJSON(url, 'POST', {order: ids.join(",")}, function(data) {
}, function() { });
}
});
var addAlignment = function(data) {
data.title = data['item[title]'] || data.title;
var $alignment = $("#alginment_" + data.id);
if($alignment.length === 0) {
$alignment = $("#alignment_blank").clone(true).removeAttr('id');
}
$alignment.addClass($.underscore(data.content_type));
var desc = $.titleize(data.content_type) || "Alignment";
$alignment.find(".type_icon").attr('alt', desc).attr('title', desc);
$alignment.attr('id', 'alignment_' + (data.id || "new"));
var hrefValues = ['user_id'];
if(data.id) { hrefValues = ['user_id', 'id']; }
$alignment.fillTemplateData({
data: data,
hrefValues: hrefValues
});
$("#alignments").append($alignment.show());
return $alignment;
};
$(".add_outcome_alignment_link").live('click', function(event) {
event.preventDefault();
if(INST && INST.selectContentDialog) {
var options = {for_modules: false};
options.select_button_text = I18n.t("align_item", "Align Item");
options.holder_name = I18n.t("this_outcome", "this Outcome");
options.dialog_title = I18n.t("align_to_outcome", "Align Item to this Outcome");
options.submit = function(item_data) {
var $item = addAlignment(item_data);
var url = $("#outcome_urls .align_url").attr('href');
item_data['asset_string'] = item_data['item[type]'] + "_" + item_data['item[id]'];
$item.loadingImage({image_size: 'small'});
$.ajaxJSON(url, 'POST', item_data, function(data) {
$item.loadingImage('remove');
$item.remove();
addAlignment(data.content_tag);
$("#alignments.orderable").sortable('refresh');
});
};
INST.selectContentDialog(options);
}
});
$("#artifacts li").live('mouseover', function() {
$(".hover_alignment,.hover_artifact").removeClass('hover_alignment').removeClass('hover_artifact');
$(this).addClass('hover_artifact');
});
$("#alignments li").live('mouseover', function() {
$(".hover_alignment,.hover_artifact").removeClass('hover_alignment').removeClass('hover_artifact');
$(this).addClass('hover_alignment');
});
});
});
});

View File

@ -16,467 +16,467 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
I18n.scoped("learning_outcomes", function(I18n) {
var outcomes = {
ratingCounter: 0,
updateOutcome: function(outcome, $outcome) {
if(!$outcome || $outcome.length === 0) {
$outcome = $("#outcome_" + outcome.id);
}
if(!$outcome || $outcome.length === 0) {
$outcome = $("#outcome_blank").clone(true).removeAttr('id');
$("#outcomes .outcome_group:first").append($outcome.show());
$("#outcomes .outcome_group:first").sortable('refresh');
}
outcome.asset_string = $.underscore("learning_outcome_" + outcome.id);
$outcome.find("textarea.description").val(outcome.description);
$outcome.fillTemplateData({
data: outcome,
id: "outcome_" + outcome.id,
htmlValues: ['description'],
hrefValues: ['id']
});
$outcome.addClass('loaded');
$outcome.find(".rubric_criterion .rating:not(.blank)").remove();
if(outcome.data && outcome.data.rubric_criterion) {
for(var idx in outcome.data.rubric_criterion.ratings) {
var rating = outcome.data.rubric_criterion.ratings[idx]
var $rating = $outcome.find(".rubric_criterion .rating.blank:first").clone(true).removeClass('blank');
var jdx = outcomes.ratingCounter++;
$rating.find(".description").text(rating.description);
$rating.find(".points").text(rating.points);
$outcome.find(".add_holder").before($rating.show());
var outcomes = {
ratingCounter: 0,
updateOutcome: function(outcome, $outcome) {
if(!$outcome || $outcome.length === 0) {
$outcome = $("#outcome_" + outcome.id);
}
$outcome.find(".mastery_points").text(outcome.data.rubric_criterion.mastery_points);
$outcome.find(".points_possible").text(outcome.data.rubric_criterion.points_possible);
}
if(outcome.permissions) {
$outcome.find(".edit_outcome_link").showIf(outcome.permissions.update && for_context);
var for_context = (outcome.context_code == $("#find_outcome_dialog .context_code").text());
$outcome.find(".really_delete_outcome_link").showIf(for_context);
$outcome.find(".remove_outcome_link").showIf(!for_context);
}
return $outcome;
},
sizeRatings: function() {
},
hideEditOutcome: function() {
// remove .prev('.outcome') if id is 'outcome_new'
$("#edit_outcome_form textarea").editorBox('destroy');
var $outcome = $("#outcomes #edit_outcome_form").prev(".learning_outcome");
$("body").append($("#edit_outcome_form").hide());
if($outcome.attr('id') == 'outcome_new') {
$outcome.remove();
} else {
$outcome.show();
}
},
editOutcome: function($outcome, $group) {
// set id to "outcome_new"
if($outcome && $outcome.length > 0 && !$outcome.hasClass('loaded')) {
$outcome.find(".show_details_link").triggerHandler('click', function() {
outcomes.editOutcome($outcome, $group);
if(!$outcome || $outcome.length === 0) {
$outcome = $("#outcome_blank").clone(true).removeAttr('id');
$("#outcomes .outcome_group:first").append($outcome.show());
$("#outcomes .outcome_group:first").sortable('refresh');
}
outcome.asset_string = $.underscore("learning_outcome_" + outcome.id);
$outcome.find("textarea.description").val(outcome.description);
$outcome.fillTemplateData({
data: outcome,
id: "outcome_" + outcome.id,
htmlValues: ['description'],
hrefValues: ['id']
});
return;
}
outcomes.hideEditOutcome();
if(!$outcome || $outcome.length === 0) {
$outcome = $("#outcome_blank").clone(true).attr('id', 'outcome_new');
if(!$group || $group.length == 0) {
$group = $("#outcomes .outcome_group:first");
$outcome.addClass('loaded');
$outcome.find(".rubric_criterion .rating:not(.blank)").remove();
if(outcome.data && outcome.data.rubric_criterion) {
for(var idx in outcome.data.rubric_criterion.ratings) {
var rating = outcome.data.rubric_criterion.ratings[idx]
var $rating = $outcome.find(".rubric_criterion .rating.blank:first").clone(true).removeClass('blank');
var jdx = outcomes.ratingCounter++;
$rating.find(".description").text(rating.description);
$rating.find(".points").text(rating.points);
$outcome.find(".add_holder").before($rating.show());
}
$outcome.find(".mastery_points").text(outcome.data.rubric_criterion.mastery_points);
$outcome.find(".points_possible").text(outcome.data.rubric_criterion.points_possible);
}
$group.append($outcome.show());
$group.sortable('refresh');
}
var $form = $("#edit_outcome_form");
$form.attr('action', $outcome.find(".edit_outcome_link").attr('href'));
$form.attr('method', 'PUT');
if($outcome.attr('id') == 'outcome_new') {
$form.attr('action', $("#outcome_links .add_outcome_url").attr('href'));
$form.attr('method', 'POST');
}
var data = $outcome.getTemplateData({textValues: ['short_description', 'description', 'mastery_points']});
// the OR here is because of a wierdness in chrome where .val() is an
// empty string but .html() is the actual imputed html that we want
data.description = $outcome.find("textarea.description").val() || $outcome.find("textarea.description").html();
$form.fillFormData(data, {object_name: 'learning_outcome'});
$form.find("#outcome_include_rubric_example").attr('checked', true).change();
$form.find(".rubric_criterion .rating:not(.blank)").remove();
$outcome.find(".rubric_criterion .rating:not(.blank)").each(function() {
$form.find("#outcome_include_rubric_example").attr('checked', true);
var $rating = $form.find(".rubric_criterion .rating.blank:first").clone(true).removeClass('blank');
var ratingData = $(this).getTemplateData({textValues: ['description', 'points']});
var idx = outcomes.ratingCounter++;
$rating.find(".outcome_rating_description").val(ratingData.description).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").val(ratingData.points).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$form.find(".add_holder").before($rating.show());
});
$form.find(".mastery_points").val(data.mastery_points);
$form.find("#outcome_include_rubric_example").change();
$outcome.after($form.show());
$outcome.hide();
$form.find(":text:visible:first").focus().select();
$form.find("textarea").editorBox();
},
deleteOutcome: function($outcome) {
$outcome.confirmDelete({
message: I18n.t("remove_learning_outcome", "Are you sure you want to remove this learning outcome?"),
url: $outcome.find(".delete_outcome_link").attr('href'),
success: function() {
$(this).slideUp(function() {
$(this).remove();
if(outcome.permissions) {
$outcome.find(".edit_outcome_link").showIf(outcome.permissions.update && for_context);
var for_context = (outcome.context_code == $("#find_outcome_dialog .context_code").text());
$outcome.find(".really_delete_outcome_link").showIf(for_context);
$outcome.find(".remove_outcome_link").showIf(!for_context);
}
return $outcome;
},
sizeRatings: function() {
},
hideEditOutcome: function() {
// remove .prev('.outcome') if id is 'outcome_new'
$("#edit_outcome_form textarea").editorBox('destroy');
var $outcome = $("#outcomes #edit_outcome_form").prev(".learning_outcome");
$("body").append($("#edit_outcome_form").hide());
if($outcome.attr('id') == 'outcome_new') {
$outcome.remove();
} else {
$outcome.show();
}
},
editOutcome: function($outcome, $group) {
// set id to "outcome_new"
if($outcome && $outcome.length > 0 && !$outcome.hasClass('loaded')) {
$outcome.find(".show_details_link").triggerHandler('click', function() {
outcomes.editOutcome($outcome, $group);
});
return;
}
outcomes.hideEditOutcome();
if(!$outcome || $outcome.length === 0) {
$outcome = $("#outcome_blank").clone(true).attr('id', 'outcome_new');
if(!$group || $group.length == 0) {
$group = $("#outcomes .outcome_group:first");
}
$group.append($outcome.show());
$group.sortable('refresh');
}
var $form = $("#edit_outcome_form");
$form.attr('action', $outcome.find(".edit_outcome_link").attr('href'));
$form.attr('method', 'PUT');
if($outcome.attr('id') == 'outcome_new') {
$form.attr('action', $("#outcome_links .add_outcome_url").attr('href'));
$form.attr('method', 'POST');
}
var data = $outcome.getTemplateData({textValues: ['short_description', 'description', 'mastery_points']});
// the OR here is because of a wierdness in chrome where .val() is an
// empty string but .html() is the actual imputed html that we want
data.description = $outcome.find("textarea.description").val() || $outcome.find("textarea.description").html();
$form.fillFormData(data, {object_name: 'learning_outcome'});
$form.find("#outcome_include_rubric_example").attr('checked', true).change();
$form.find(".rubric_criterion .rating:not(.blank)").remove();
$outcome.find(".rubric_criterion .rating:not(.blank)").each(function() {
$form.find("#outcome_include_rubric_example").attr('checked', true);
var $rating = $form.find(".rubric_criterion .rating.blank:first").clone(true).removeClass('blank');
var ratingData = $(this).getTemplateData({textValues: ['description', 'points']});
var idx = outcomes.ratingCounter++;
$rating.find(".outcome_rating_description").val(ratingData.description).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").val(ratingData.points).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$form.find(".add_holder").before($rating.show());
});
$form.find(".mastery_points").val(data.mastery_points);
$form.find("#outcome_include_rubric_example").change();
$outcome.after($form.show());
$outcome.hide();
$form.find(":text:visible:first").focus().select();
$form.find("textarea").editorBox();
},
deleteOutcome: function($outcome) {
$outcome.confirmDelete({
message: I18n.t("remove_learning_outcome", "Are you sure you want to remove this learning outcome?"),
url: $outcome.find(".delete_outcome_link").attr('href'),
success: function() {
$(this).slideUp(function() {
$(this).remove();
});
}
});
},
updateOutcomeGroup: function(group, $group) {
if(!$group || $group.length === 0) {
$group = $("#group_" + group.id);
}
if(!$group || $group.length === 0) {
$group = $("#group_blank").clone(true).removeAttr('id');
$("#outcomes .outcome_group:first").append($group.show());
$("#outcomes .outcome_group:first").sortable('refresh');
$group.sortable(outcomes.sortableOptions);
$(".outcome_group").sortable('option', 'connectWith', '.outcome_group');
}
group.asset_string = $.underscore("learning_outcome_group_" + group.id);
$group.find("textarea.description").val(group.description);
$group.fillTemplateData({
data: group,
id: "group_" + group.id,
hrefValues: ['id'],
htmlValues: ['description']
});
return $group;
},
hideEditOutcomeGroup: function() {
// remove .prev('.group') if id is 'group_new'
$("#edit_outcome_group_form textarea").editorBox('destroy');
var $group = $("#outcomes #edit_outcome_group_form").prev(".outcome_group");
$("body").append($("#edit_outcome_group_form").hide());
if($group.attr('id') == 'group_new') {
$group.remove();
} else {
$group.show();
}
},
editOutcomeGroup: function($group) {
// set id to "outcome_new"
outcomes.hideEditOutcomeGroup();
if(!$group || $group.length === 0) {
$group = $("#group_blank").clone(true).attr('id', 'group_new');
$("#outcomes .outcome_group:first").append($group.show());
$("#outcomes .outcome_group:first").sortable('refresh');
$group.sortable(outcomes.sortableOptions);
$(".outcome_group").sortable('option', 'connectWith', '.outcome_group');
}
var $form = $("#edit_outcome_group_form");
$form.attr('action', $group.find(".edit_group_link").attr('href'));
$form.attr('method', 'PUT');
if($group.attr('id') == 'group_new') {
$form.attr('action', $("#outcome_links .add_outcome_group_url").attr('href'));
$form.attr('method', 'POST');
}
var data = $group.getTemplateData({textValues: ['title', 'description']});
data.description = $group.find("textarea.description").val();
$form.fillFormData(data, {object_name: 'learning_outcome_group'});
$group.after($form.show());
$group.hide();
$form.find(":text:visible:first").focus().select();
$form.find("textarea").editorBox();
},
deleteOutcomeGroup: function($group) {
$group.confirmDelete({
message: I18n.t("remove_outcome_group", "Are you sure you want to remove this learning outcome group and all its outcomes?"),
url: $group.find(".delete_group_link").attr('href'),
success: function() {
$(this).slideUp(function() {
$(this).remove();
});
}
});
},
sortableOptions: {
handle: '.reorder_link',
connectWith: '.outcome_group',
items: '.learning_outcome,.outcome_group',
axis: 'y',
update: function(event, ui) {
var $group = $(ui.item).parent().closest(".outcome_group");
var id = $group.children(".header").getTemplateData({textValues: ['asset_string', 'id']}).id;
var assets = [];
var data = {}
$group.children(".learning_outcome,.outcome_group").each(function() {
var asset_string = $(this).children(".header").getTemplateData({textValues: ['asset_string']}).asset_string;
assets.push(asset_string);
});
for(var idx = 0; idx < assets.length; idx++) {
data['ordering[' + assets[idx] + ']'] = idx;
}
var url = $.replaceTags($("#outcome_links .reorder_items_url").attr('href'), 'id', id);
$.ajaxJSON(url, 'POST', data, function(data) {
}, function(data) {
});
}
});
},
updateOutcomeGroup: function(group, $group) {
if(!$group || $group.length === 0) {
$group = $("#group_" + group.id);
}
if(!$group || $group.length === 0) {
$group = $("#group_blank").clone(true).removeAttr('id');
$("#outcomes .outcome_group:first").append($group.show());
$("#outcomes .outcome_group:first").sortable('refresh');
$group.sortable(outcomes.sortableOptions);
$(".outcome_group").sortable('option', 'connectWith', '.outcome_group');
}
group.asset_string = $.underscore("learning_outcome_group_" + group.id);
$group.find("textarea.description").val(group.description);
$group.fillTemplateData({
data: group,
id: "group_" + group.id,
hrefValues: ['id'],
htmlValues: ['description']
});
return $group;
},
hideEditOutcomeGroup: function() {
// remove .prev('.group') if id is 'group_new'
$("#edit_outcome_group_form textarea").editorBox('destroy');
var $group = $("#outcomes #edit_outcome_group_form").prev(".outcome_group");
$("body").append($("#edit_outcome_group_form").hide());
if($group.attr('id') == 'group_new') {
$group.remove();
} else {
$group.show();
}
},
editOutcomeGroup: function($group) {
// set id to "outcome_new"
outcomes.hideEditOutcomeGroup();
if(!$group || $group.length === 0) {
$group = $("#group_blank").clone(true).attr('id', 'group_new');
$("#outcomes .outcome_group:first").append($group.show());
$("#outcomes .outcome_group:first").sortable('refresh');
$group.sortable(outcomes.sortableOptions);
$(".outcome_group").sortable('option', 'connectWith', '.outcome_group');
}
var $form = $("#edit_outcome_group_form");
$form.attr('action', $group.find(".edit_group_link").attr('href'));
$form.attr('method', 'PUT');
if($group.attr('id') == 'group_new') {
$form.attr('action', $("#outcome_links .add_outcome_group_url").attr('href'));
$form.attr('method', 'POST');
}
var data = $group.getTemplateData({textValues: ['title', 'description']});
data.description = $group.find("textarea.description").val();
$form.fillFormData(data, {object_name: 'learning_outcome_group'});
$group.after($form.show());
$group.hide();
$form.find(":text:visible:first").focus().select();
$form.find("textarea").editorBox();
},
deleteOutcomeGroup: function($group) {
$group.confirmDelete({
message: I18n.t("remove_outcome_group", "Are you sure you want to remove this learning outcome group and all its outcomes?"),
url: $group.find(".delete_group_link").attr('href'),
success: function() {
$(this).slideUp(function() {
$(this).remove();
});
}
});
},
sortableOptions: {
handle: '.reorder_link',
connectWith: '.outcome_group',
items: '.learning_outcome,.outcome_group',
axis: 'y',
update: function(event, ui) {
var $group = $(ui.item).parent().closest(".outcome_group");
var id = $group.children(".header").getTemplateData({textValues: ['asset_string', 'id']}).id;
var assets = [];
var data = {}
$group.children(".learning_outcome,.outcome_group").each(function() {
var asset_string = $(this).children(".header").getTemplateData({textValues: ['asset_string']}).asset_string;
assets.push(asset_string);
});
for(var idx = 0; idx < assets.length; idx++) {
data['ordering[' + assets[idx] + ']'] = idx;
}
var url = $.replaceTags($("#outcome_links .reorder_items_url").attr('href'), 'id', id);
$.ajaxJSON(url, 'POST', data, function(data) {
}, function(data) {
});
}
}
}
$(document).ready(function() {
$("#outcome_information_link").click(function(event) {
event.preventDefault();
$("#outcome_criterion_dialog").dialog('close').dialog({
autoOpen: false,
title: I18n.t("outcome_criterion", "Learning Outcome Criterion"),
width: 400
}).dialog('open');
});
$(".show_details_link,.hide_details_link").click(function(event, callback) {
event.preventDefault();
var $outcome = $(this).closest(".learning_outcome");
if($(this).hasClass('show_details_link')) {
if($outcome.hasClass('loaded')) {
$outcome.addClass('expanded');
} else {
var $link = $(this);
$link.text("loading details...");
var url = $outcome.find("a.show_details_link").attr('href');
$.ajaxJSON(url, 'GET', {}, function(data) {
$link.text(I18n.t("show_details", "show details"));
outcomes.updateOutcome(data.learning_outcome, $outcome);
$(document).ready(function() {
$("#outcome_information_link").click(function(event) {
event.preventDefault();
$("#outcome_criterion_dialog").dialog('close').dialog({
autoOpen: false,
title: I18n.t("outcome_criterion", "Learning Outcome Criterion"),
width: 400
}).dialog('open');
});
$(".show_details_link,.hide_details_link").click(function(event, callback) {
event.preventDefault();
var $outcome = $(this).closest(".learning_outcome");
if($(this).hasClass('show_details_link')) {
if($outcome.hasClass('loaded')) {
$outcome.addClass('expanded');
if(callback && $.isFunction(callback)) {
callback();
} else {
var $link = $(this);
$link.text("loading details...");
var url = $outcome.find("a.show_details_link").attr('href');
$.ajaxJSON(url, 'GET', {}, function(data) {
$link.text(I18n.t("show_details", "show details"));
outcomes.updateOutcome(data.learning_outcome, $outcome);
$outcome.addClass('expanded');
if(callback && $.isFunction(callback)) {
callback();
}
}, function(data) {
$link.text(I18n.t("details_failed_to_load", "details failed to load, please try again"));
});
}
} else {
$outcome.removeClass('expanded');
}
});
$(".outcome_group:visible").each(function() {
$(this).sortable(outcomes.sortableOptions);
});
$(".delete_group_link").click(function(event) {
event.preventDefault();
outcomes.deleteOutcomeGroup($(this).closest(".outcome_group"));
});
$(".edit_group_link").click(function(event) {
event.preventDefault();
outcomes.editOutcomeGroup($(this).closest(".outcome_group"));
});
$("#find_outcome_dialog .select_outcomes_link").click(function(event) {
event.preventDefault();
$("#find_outcome_dialog .select_outcome_checkbox:checked").each(function() {
var $outcome_select = $(this).parents(".outcomes_dialog_select");
var id = $outcome_select.getTemplateData({textValues: ['id']}).id;
var $outcome = $("#outcome_dialog_" + id);
var id = $outcome.getTemplateData({textValues: ['id']}).id;
var group_id = $("#outcomes .outcome_group:first > .header").getTemplateData({textValues: ['id']}).id;
var url = $.replaceTags($("#find_outcome_dialog .add_outcome_url").attr('href'), 'learning_outcome_id', id);
url = $.replaceTags(url, 'learning_outcome_group_id', group_id);
var data = $outcome.getTemplateData({textValues: ['id', 'short_description', 'description']});
data.permissions = {};
var $outcome = outcomes.updateOutcome(data);
$("html,body").scrollTo($outcome);
$outcome.loadingImage();
$("#find_outcome_dialog").dialog('close');
$.ajaxJSON(url, 'POST', {}, function(data) {
$outcome.loadingImage('remove');
outcomes.updateOutcome(data.learning_outcome);
}, function() {
$outcome.loadingImage('remove');
$outcome.remove();
});
});
});
$(".edit_outcome_link").click(function(event) {
event.preventDefault();
outcomes.editOutcome($(this).parents(".learning_outcome"));
});
$(".delete_outcome_link").click(function(event) {
event.preventDefault();
outcomes.deleteOutcome($(this).parents(".learning_outcome"));
});
$(".add_outcome_link").click(function(event) {
event.preventDefault();
var $group = $(this).closest(".outcome_group");
if($group.length == 0) { $group = null; }
outcomes.editOutcome(null, $group);
});
$(".add_outcome_group_link").click(function(event) {
event.preventDefault();
outcomes.editOutcomeGroup();
});
$("#edit_outcome_group_form .cancel_button").click(function(event) {
outcomes.hideEditOutcomeGroup();
});
$("#edit_outcome_form .cancel_button").click(function(event) {
outcomes.hideEditOutcome();
});
$("#find_outcome_dialog .outcomes_dialog_select").click(function(event) {
if($(event.target).closest("input").length > 0) { return; }
event.preventDefault();
$("#find_outcome_dialog .outcomes_dialog_select.selected_side_tab").removeClass('selected_side_tab');
$(this).addClass('selected_side_tab');
var id = $(this).getTemplateData({textValues: ['id']}).id;
$("#find_outcome_dialog").find(".outcomes_dialog_outcome").hide().end()
.find("#outcome_dialog_" + id).show();
});
$(".find_outcome_link").click(function(event) {
var $dialog = $("#find_outcome_dialog");
event.preventDefault();
$dialog.dialog('close').dialog({
autoOpen: true,
width: 600,
height: 350,
title: I18n.t("find_existing_outcome", 'Find Existing Outcome')
}).dialog('open');
if(!$dialog.hasClass('loaded')) {
$dialog.find(".loading_message").text(I18n.t("loading_outcomes", "Loading outcomes..."));
var url = $dialog.find(".outcomes_url").attr('href');
$.ajaxJSON(url, 'GET', {}, function(data) {
$dialog.find(".loading_message").remove();
if(data.length === 0) {
$dialog.find(".loading_message").text("No outcomes found");
}
for(var idx in data) {
var outcome = data[idx].learning_outcome
var $outcome_select = $dialog.find(".outcomes_dialog_select.blank:first").clone(true);
$outcome_select.fillTemplateData({data: outcome}).removeClass('blank');
$dialog.find(".outcomes_dialog_outcomes_select").append($outcome_select.show());
var $outcome = $dialog.find(".outcomes_dialog_outcome.blank:first").clone(true);
$outcome.removeClass('blank');
$outcome.data('outcome', outcome);
$outcome.find(".criterion.blank").hide();
outcome.outcome_total = outcome.points_possible;
$outcome.fillTemplateData({
data: outcome,
htmlValues: ['description'],
id: 'outcome_dialog_' + outcome.id
});
$dialog.find(".outcomes_dialog_outcomes").append($outcome);
}
$dialog.find(".outcomes_dialog_holder").show();
$dialog.find(".outcomes_dialog_outcomes_select .outcomes_dialog_select:visible:first").click();
$dialog.addClass('loaded');
}, function(data) {
$link.text(I18n.t("details_failed_to_load", "details failed to load, please try again"));
$dialog.find(".loading_message").text(I18n.t("loading_outcomes_failed", "Loading outcomes failed, please try again"));
});
}
} else {
$outcome.removeClass('expanded');
}
});
$(".outcome_group:visible").each(function() {
$(this).sortable(outcomes.sortableOptions);
});
$(".delete_group_link").click(function(event) {
event.preventDefault();
outcomes.deleteOutcomeGroup($(this).closest(".outcome_group"));
});
$(".edit_group_link").click(function(event) {
event.preventDefault();
outcomes.editOutcomeGroup($(this).closest(".outcome_group"));
});
$("#find_outcome_dialog .select_outcomes_link").click(function(event) {
event.preventDefault();
$("#find_outcome_dialog .select_outcome_checkbox:checked").each(function() {
var $outcome_select = $(this).parents(".outcomes_dialog_select");
var id = $outcome_select.getTemplateData({textValues: ['id']}).id;
var $outcome = $("#outcome_dialog_" + id);
var id = $outcome.getTemplateData({textValues: ['id']}).id;
var group_id = $("#outcomes .outcome_group:first > .header").getTemplateData({textValues: ['id']}).id;
var url = $.replaceTags($("#find_outcome_dialog .add_outcome_url").attr('href'), 'learning_outcome_id', id);
url = $.replaceTags(url, 'learning_outcome_group_id', group_id);
var data = $outcome.getTemplateData({textValues: ['id', 'short_description', 'description']});
data.permissions = {};
var $outcome = outcomes.updateOutcome(data);
$("html,body").scrollTo($outcome);
$outcome.loadingImage();
$("#find_outcome_dialog").dialog('close');
$.ajaxJSON(url, 'POST', {}, function(data) {
$outcome.loadingImage('remove');
outcomes.updateOutcome(data.learning_outcome);
}, function() {
$outcome.loadingImage('remove');
$outcome.remove();
});
});
});
$(".edit_outcome_link").click(function(event) {
event.preventDefault();
outcomes.editOutcome($(this).parents(".learning_outcome"));
});
$(".delete_outcome_link").click(function(event) {
event.preventDefault();
outcomes.deleteOutcome($(this).parents(".learning_outcome"));
});
$(".add_outcome_link").click(function(event) {
event.preventDefault();
var $group = $(this).closest(".outcome_group");
if($group.length == 0) { $group = null; }
outcomes.editOutcome(null, $group);
});
$(".add_outcome_group_link").click(function(event) {
event.preventDefault();
outcomes.editOutcomeGroup();
});
$("#edit_outcome_group_form .cancel_button").click(function(event) {
outcomes.hideEditOutcomeGroup();
});
$("#edit_outcome_form .cancel_button").click(function(event) {
outcomes.hideEditOutcome();
});
$("#find_outcome_dialog .outcomes_dialog_select").click(function(event) {
if($(event.target).closest("input").length > 0) { return; }
event.preventDefault();
$("#find_outcome_dialog .outcomes_dialog_select.selected_side_tab").removeClass('selected_side_tab');
$(this).addClass('selected_side_tab');
var id = $(this).getTemplateData({textValues: ['id']}).id;
$("#find_outcome_dialog").find(".outcomes_dialog_outcome").hide().end()
.find("#outcome_dialog_" + id).show();
});
$(".find_outcome_link").click(function(event) {
var $dialog = $("#find_outcome_dialog");
event.preventDefault();
$dialog.dialog('close').dialog({
autoOpen: true,
width: 600,
height: 350,
title: I18n.t("find_existing_outcome", 'Find Existing Outcome')
}).dialog('open');
if(!$dialog.hasClass('loaded')) {
$dialog.find(".loading_message").text(I18n.t("loading_outcomes", "Loading outcomes..."));
var url = $dialog.find(".outcomes_url").attr('href');
$.ajaxJSON(url, 'GET', {}, function(data) {
$dialog.find(".loading_message").remove();
if(data.length === 0) {
$dialog.find(".loading_message").text("No outcomes found");
$("#edit_outcome_form").formSubmit({
processData: function(data) {
data['learning_outcome_group_id'] = $(this).closest(".outcome_group").find(".header").first().getTemplateData({textValues: ['id']}).id;
return data;
},
beforeSubmit: function(data) {
var $outcome = $(this).prev(".outcome");
if($outcome.attr('id') == 'outcome_new') {
$outcome.attr('id', 'outcome_adding');
}
for(var idx in data) {
var outcome = data[idx].learning_outcome
var $outcome_select = $dialog.find(".outcomes_dialog_select.blank:first").clone(true);
$outcome_select.fillTemplateData({data: outcome}).removeClass('blank');
$dialog.find(".outcomes_dialog_outcomes_select").append($outcome_select.show());
var $outcome = $dialog.find(".outcomes_dialog_outcome.blank:first").clone(true);
$outcome.removeClass('blank');
$outcome.data('outcome', outcome);
$outcome.find(".criterion.blank").hide();
outcome.outcome_total = outcome.points_possible;
$outcome.fillTemplateData({
data: outcome,
htmlValues: ['description'],
id: 'outcome_dialog_' + outcome.id
});
$dialog.find(".outcomes_dialog_outcomes").append($outcome);
$(this).loadingImage();
},
success: function(data) {
$(this).loadingImage('remove');
outcomes.updateOutcome(data.learning_outcome, $(this).prev(".learning_outcome"));
outcomes.hideEditOutcome();
},
error: function(data) {
$(this).loadingImage('remove');
$(this).formErrors(data);
}
});
$("#edit_outcome_group_form").formSubmit({
processData: function(data) {
var group_id = $(this).parent().closest(".outcome_group").children(".header").getTemplateData({textValues: ['id']}).id;
data['learning_outcome_group[learning_outcome_group_id]'] = group_id;
return data;
},
beforeSubmit: function(data) {
var $group = $(this).prev(".outcome_group");
if($group.attr('id') == 'group_new') {
$group.attr('id', 'group_adding');
}
$(this).loadingImage();
},
success: function(data) {
$(this).loadingImage('remove');
outcomes.updateOutcomeGroup(data.learning_outcome_group, $(this).prev(".outcome_group"));
outcomes.hideEditOutcomeGroup();
},
error: function(data) {
$(this).loadingImage('remove');
$(this).formErrors(data);
}
});
$("#edit_outcome_form .switch_views_link").click(function(event) {
event.preventDefault();
$("#edit_outcome_form textarea:first").editorBox('toggle');
});
$("#outcome_include_rubric_example").change(function() {
var $form = $(this).parents("form");
$form.find(".rubric_criterion").showIf($(this).attr('checked'));
$form.find(".outcome_rating_points:first").blur();
if(!$form.find(".outcome_criterion_title").val()) {
$form.find(".outcome_criterion_title").val($form.find(".outcome_short_description").val());
}
if($form.find(".rating:not(.blank)").length === 0) {
var $rating = $form.find(".rating.blank:first").clone(true).removeClass('blank');
var idx = outcomes.ratingCounter++;
$rating.find(".outcome_rating_description").val(I18n.t("criteria.exceeds_expectations", "Exceeds Expectations")).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").val("5").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$form.find(".add_holder").before($rating.show());
idx = outcomes.ratingCounter++;
$rating = $form.find(".rating.blank:first").clone(true).removeClass('blank');
$rating.find(".outcome_rating_description").val(I18n.t("criteria.meets_expectations", "Meets Expectations")).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").val("3").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$form.find(".add_holder").before($rating.show());
idx = outcomes.ratingCounter++;
$rating = $form.find(".rating.blank:first").clone(true).removeClass('blank');
$rating.find(".outcome_rating_description").val(I18n.t("criteria.does_not_meet_expectations", "Does Not Meet Expectations")).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").val("0").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$form.find(".add_holder").before($rating.show());
$form.find(".mastery_points").val("3");
}
$form.find(".outcome_rating_points:first").blur();
});
$("#edit_outcome_form .outcome_rating_points").blur(function() {
var maxPoints = 0;
$(this).val(parseFloat($(this).val()));
$("#edit_outcome_form .rating:not(.blank) .outcome_rating_points").each(function() {
var points = parseFloat($(this).val(), 10);
if(points) {
maxPoints = Math.max(points, maxPoints);
}
$dialog.find(".outcomes_dialog_holder").show();
$dialog.find(".outcomes_dialog_outcomes_select .outcomes_dialog_select:visible:first").click();
$dialog.addClass('loaded');
}, function(data) {
$dialog.find(".loading_message").text(I18n.t("loading_outcomes_failed", "Loading outcomes failed, please try again"));
});
}
});
$("#edit_outcome_form").formSubmit({
processData: function(data) {
data['learning_outcome_group_id'] = $(this).closest(".outcome_group").find(".header").first().getTemplateData({textValues: ['id']}).id;
return data;
},
beforeSubmit: function(data) {
var $outcome = $(this).prev(".outcome");
if($outcome.attr('id') == 'outcome_new') {
$outcome.attr('id', 'outcome_adding');
$("#edit_outcome_form .points_possible").text(maxPoints);
})
$("#edit_outcome_form .mastery_points").blur(function() {
$(this).val(parseFloat($(this).val()) || 0);
});
$("#edit_outcome_form .add_rating_link").click(function(event) {
event.preventDefault();
var $rating = $(this).parents("table").find("tr.rating:visible:first").clone(true).removeClass('blank');
if($rating.length === 0) {
$rating = $(this).parents("table").find("tr.rating.blank").clone(true).removeClass('blank');
}
$(this).loadingImage();
},
success: function(data) {
$(this).loadingImage('remove');
outcomes.updateOutcome(data.learning_outcome, $(this).prev(".learning_outcome"));
outcomes.hideEditOutcome();
},
error: function(data) {
$(this).loadingImage('remove');
$(this).formErrors(data);
}
});
$("#edit_outcome_group_form").formSubmit({
processData: function(data) {
var group_id = $(this).parent().closest(".outcome_group").children(".header").getTemplateData({textValues: ['id']}).id;
data['learning_outcome_group[learning_outcome_group_id]'] = group_id;
return data;
},
beforeSubmit: function(data) {
var $group = $(this).prev(".outcome_group");
if($group.attr('id') == 'group_new') {
$group.attr('id', 'group_adding');
}
$(this).loadingImage();
},
success: function(data) {
$(this).loadingImage('remove');
outcomes.updateOutcomeGroup(data.learning_outcome_group, $(this).prev(".outcome_group"));
outcomes.hideEditOutcomeGroup();
},
error: function(data) {
$(this).loadingImage('remove');
$(this).formErrors(data);
}
});
$("#edit_outcome_form .switch_views_link").click(function(event) {
event.preventDefault();
$("#edit_outcome_form textarea:first").editorBox('toggle');
});
$("#outcome_include_rubric_example").change(function() {
var $form = $(this).parents("form");
$form.find(".rubric_criterion").showIf($(this).attr('checked'));
$form.find(".outcome_rating_points:first").blur();
if(!$form.find(".outcome_criterion_title").val()) {
$form.find(".outcome_criterion_title").val($form.find(".outcome_short_description").val());
}
if($form.find(".rating:not(.blank)").length === 0) {
var $rating = $form.find(".rating.blank:first").clone(true).removeClass('blank');
$(this).parents("table").find(".criterion_title").after($rating.show());
var idx = outcomes.ratingCounter++;
$rating.find(".outcome_rating_description").val(I18n.t("criteria.exceeds_expectations", "Exceeds Expectations")).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").val("5").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$form.find(".add_holder").before($rating.show());
idx = outcomes.ratingCounter++;
$rating = $form.find(".rating.blank:first").clone(true).removeClass('blank');
$rating.find(".outcome_rating_description").val(I18n.t("criteria.meets_expectations", "Meets Expectations")).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").val("3").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$form.find(".add_holder").before($rating.show());
idx = outcomes.ratingCounter++;
$rating = $form.find(".rating.blank:first").clone(true).removeClass('blank');
$rating.find(".outcome_rating_description").val(I18n.t("criteria.does_not_meet_expectations", "Does Not Meet Expectations")).attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").val("0").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$form.find(".add_holder").before($rating.show());
$form.find(".mastery_points").val("3");
}
$form.find(".outcome_rating_points:first").blur();
});
$("#edit_outcome_form .outcome_rating_points").blur(function() {
var maxPoints = 0;
$(this).val(parseFloat($(this).val()));
$("#edit_outcome_form .rating:not(.blank) .outcome_rating_points").each(function() {
var points = parseFloat($(this).val(), 10);
if(points) {
maxPoints = Math.max(points, maxPoints);
}
$rating.find(".outcome_rating_description").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$rating.find(".outcome_rating_points").val(parseFloat($rating.find(".outcome_rating_points").val(), 10) + 1);
$rating.find(".outcome_rating_points:first").blur();
outcomes.sizeRatings();
});
$("#edit_outcome_form .delete_rating_link").click(function(event) {
event.preventDefault();
$(this).parents("tr").remove();
outcomes.sizeRatings();
});
$("#edit_outcome_form .points_possible").text(maxPoints);
})
$("#edit_outcome_form .mastery_points").blur(function() {
$(this).val(parseFloat($(this).val()) || 0);
});
$("#edit_outcome_form .add_rating_link").click(function(event) {
event.preventDefault();
var $rating = $(this).parents("table").find("tr.rating:visible:first").clone(true).removeClass('blank');
if($rating.length === 0) {
$rating = $(this).parents("table").find("tr.rating.blank").clone(true).removeClass('blank');
}
$(this).parents("table").find(".criterion_title").after($rating.show());
var idx = outcomes.ratingCounter++;
$rating.find(".outcome_rating_description").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][description]');
$rating.find(".outcome_rating_points").attr('name', 'learning_outcome[rubric_criterion][ratings][' + idx + '][points]');
$rating.find(".outcome_rating_points").val(parseFloat($rating.find(".outcome_rating_points").val(), 10) + 1);
$rating.find(".outcome_rating_points:first").blur();
outcomes.sizeRatings();
});
$("#edit_outcome_form .delete_rating_link").click(function(event) {
event.preventDefault();
$(this).parents("tr").remove();
outcomes.sizeRatings();
});
});
});

View File

@ -1,89 +1,89 @@
I18n.scoped('link_enrollment', function (I18n) {
window.link_enrollment = (function() {
return {
choose: function(user_name, enrollment_id, current_user_id, callback) {
var $user = $(this).parents(".user");
var $dialog = $("#link_student_dialog");
var user_data = {};
user_data.short_name = user_name;
$dialog.fillTemplateData({data: user_data});
if(!$dialog.data('loaded')) {
$dialog.find(".loading_message").text(I18n.t('messages.loading_students', "Loading Students..."));
var url = $dialog.find(".student_url").attr('href');
$.ajaxJSON(url, 'GET', {}, function(data) {
for(var idx in data) {
var user = data[idx];
var $option = $("<option/>");
if(user.id && user.name) {
$option.val(user.id).text(user.name);
$dialog.find(".student_options").append($option);
window.link_enrollment = (function() {
return {
choose: function(user_name, enrollment_id, current_user_id, callback) {
var $user = $(this).parents(".user");
var $dialog = $("#link_student_dialog");
var user_data = {};
user_data.short_name = user_name;
$dialog.fillTemplateData({data: user_data});
if(!$dialog.data('loaded')) {
$dialog.find(".loading_message").text(I18n.t('messages.loading_students', "Loading Students..."));
var url = $dialog.find(".student_url").attr('href');
$.ajaxJSON(url, 'GET', {}, function(data) {
for(var idx in data) {
var user = data[idx];
var $option = $("<option/>");
if(user.id && user.name) {
$option.val(user.id).text(user.name);
$dialog.find(".student_options").append($option);
}
}
}
var $option = $("<option/>");
$option.val("none").text(I18n.t('options.no_link', "[ No Link ]"));
$dialog.data('loaded', true);
$dialog.find(".student_options").append($option);
var $option = $("<option/>");
$option.val("none").text(I18n.t('options.no_link', "[ No Link ]"));
$dialog.data('loaded', true);
$dialog.find(".student_options").append($option);
$dialog.find(".enrollment_id").val(enrollment_id);
$dialog.find(".student_options").val("none").val(current_user_id);
$dialog.find(".loading_message").hide().end()
.find(".students_link").show();
$dialog.find(".existing_user").showIf(current_user_id);
$dialog.data('callback', callback);
user_data.existing_user_name = $dialog.find(".student_options option[value='" + current_user_id + "']").text();
$dialog.fillTemplateData({data: user_data});
}, function() {
$dialog.find(".loading_message").text(I18n.t('errors.load_failed', "Loading Students Failed, please try again"));
$dialog.data('callback', callback);
});
} else {
$dialog.find(".enrollment_id").val(enrollment_id);
$dialog.find(".student_options").val("none").val(current_user_id);
$dialog.find(".loading_message").hide().end()
.find(".students_link").show();
$dialog.find(".existing_user").showIf(current_user_id);
$dialog.data('callback', callback);
$dialog.find(".student_options").val("none").val(current_user_id);
user_data.existing_user_name = $dialog.find(".student_options option[value='" + current_user_id + "']").text();
$dialog.fillTemplateData({data: user_data});
}, function() {
$dialog.find(".loading_message").text(I18n.t('errors.load_failed', "Loading Students Failed, please try again"));
$dialog.data('callback', callback);
});
} else {
$dialog.find(".enrollment_id").val(enrollment_id);
}
$dialog.find(".existing_user").showIf(current_user_id);
$dialog.find(".student_options").val("none").val(current_user_id);
user_data.existing_user_name = $dialog.find(".student_options option[value='" + current_user_id + "']").text();
$dialog.fillTemplateData({data: user_data});
$dialog.find(".student_options option:not(.blank)").remove();
$dialog
.dialog('close').dialog({
autoOpen: false,
title: I18n.t('titles.link_to_student', "Link to Student"),
width: 400
}).dialog('open');
}
$dialog.find(".existing_user").showIf(current_user_id);
$dialog.find(".student_options option:not(.blank)").remove();
$dialog
.dialog('close').dialog({
autoOpen: false,
title: I18n.t('titles.link_to_student', "Link to Student"),
width: 400
}).dialog('open');
}
};
})();
$(document).ready(function() {
$(document).bind('enrollment_added', function() {
$("#link_student_dialog").data('loaded', false);
});
$("#link_student_dialog .cancel_button").click(function() {
$("#link_student_dialog").dialog('close');
});
$("#link_student_dialog_form").formSubmit({
beforeSubmit: function(data) {
$(this)
.find("button").attr('disabled', true).end()
.find(".save_button").text(I18n.t('messages.linking_to_student', "Linking to Student..."));
},
success: function(data) {
$(this)
.find("button").attr('disabled', false).end()
.find(".save_button").text(I18n.t('buttons.link', "Link to Student"));
var enrollment = data.enrollment;
var callback = $("#link_student_dialog").data('callback');
};
})();
$(document).ready(function() {
$(document).bind('enrollment_added', function() {
$("#link_student_dialog").data('loaded', false);
});
$("#link_student_dialog .cancel_button").click(function() {
$("#link_student_dialog").dialog('close');
if($.isFunction(callback) && enrollment) {
callback(enrollment);
});
$("#link_student_dialog_form").formSubmit({
beforeSubmit: function(data) {
$(this)
.find("button").attr('disabled', true).end()
.find(".save_button").text(I18n.t('messages.linking_to_student', "Linking to Student..."));
},
success: function(data) {
$(this)
.find("button").attr('disabled', false).end()
.find(".save_button").text(I18n.t('buttons.link', "Link to Student"));
var enrollment = data.enrollment;
var callback = $("#link_student_dialog").data('callback');
$("#link_student_dialog").dialog('close');
if($.isFunction(callback) && enrollment) {
callback(enrollment);
}
},
error: function(data) {
$(this)
.find("button").attr('disabled', false)
.find(".save_button").text(I18n.t('errors.link_failed', "Linking Failed, please try again"));
}
},
error: function(data) {
$(this)
.find("button").attr('disabled', false)
.find(".save_button").text(I18n.t('errors.link_failed', "Linking Failed, please try again"));
}
});
});
});
});

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -19,279 +19,279 @@
var moderation;
I18n.scoped('quizzes.moderate', function(I18n) {
moderation = {
updateTimes: function() {
var now = new Date();
moderation.studentsCurrentlyTakingQuiz = !!$("#students .student.in_progress");
$("#students .student.in_progress").each(function() {
var $row = $(this);
var row = $row.data('timing') || {};
var started_at = $row.attr('data-started-at');
var end_at = $row.attr('data-end-at');
if(!row.referenceDate) {
$.extend(row, timing.setReferenceDate(started_at, end_at, now));
moderation = {
updateTimes: function() {
var now = new Date();
moderation.studentsCurrentlyTakingQuiz = !!$("#students .student.in_progress");
$("#students .student.in_progress").each(function() {
var $row = $(this);
var row = $row.data('timing') || {};
var started_at = $row.attr('data-started-at');
var end_at = $row.attr('data-end-at');
if(!row.referenceDate) {
$.extend(row, timing.setReferenceDate(started_at, end_at, now));
}
if(!row.referenceDate) { return; }
$row.data('timing', row);
var diff = row.referenceDate.getTime() - now.getTime() - row.clientServerDiff;
if(row.isDeadline && diff < 0) {
$row.find(".time").text(I18n.t('time_up', "Time Up!"));
return;
}
$row.data('minutes_left', diff / 60000);
var date = new Date(Math.abs(diff));
var yr = date.getUTCFullYear() - 1970;
var mon = date.getUTCMonth();
mon = mon + (12 * yr);
var day = date.getUTCDate() - 1;
var hr = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var times = [];
if(mon) { times.push(mon < 10 ? '0' + mon : mon); }
if(day) { times.push(day < 10 ? '0' + day : day); }
if(hr) { times.push(hr < 10 ? '0' + hr : hr); }
if(true || min) { times.push(min < 10 ? '0' + min : min); }
if(true || sec) { times.push(sec < 10 ? '0' + sec : sec); }
$row.find(".time").text(times.join(":"));
});
},
updateSubmission: function(submission, updateLastUpdatedAt) {
var $student = $("#student_" + submission.user_id);
if(updateLastUpdatedAt) {
moderation.lastUpdatedAt = new Date(Math.max(Date.parse(submission.updated_at), moderation.lastUpdatedAt));
}
if(!row.referenceDate) { return; }
$row.data('timing', row);
var diff = row.referenceDate.getTime() - now.getTime() - row.clientServerDiff;
if(row.isDeadline && diff < 0) {
$row.find(".time").text(I18n.t('time_up', "Time Up!"));
return;
var state_text = "";
if(submission.workflow_state == 'complete' || submission.workflow_state == 'pending_review') {
state_text = I18n.t('finished_in_duration', "finished in %{duration}", {'duration': submission.finished_in_words});
}
var data = {
attempt: submission.attempt || '--',
extra_time: submission.extra_time,
extra_attempts: submission.extra_attempts,
score: submission.kept_score
};
if(submission.attempts_left == -1) {
data.attempts_left = '--';
} else if(submission.attempts_left) {
data.attempts_left = submission.attempts_left;
}
$row.data('minutes_left', diff / 60000);
var date = new Date(Math.abs(diff));
var yr = date.getUTCFullYear() - 1970;
var mon = date.getUTCMonth();
mon = mon + (12 * yr);
var day = date.getUTCDate() - 1;
var hr = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var times = [];
if(mon) { times.push(mon < 10 ? '0' + mon : mon); }
if(day) { times.push(day < 10 ? '0' + day : day); }
if(hr) { times.push(hr < 10 ? '0' + hr : hr); }
if(true || min) { times.push(min < 10 ? '0' + min : min); }
if(true || sec) { times.push(sec < 10 ? '0' + sec : sec); }
$row.find(".time").text(times.join(":"));
});
},
updateSubmission: function(submission, updateLastUpdatedAt) {
var $student = $("#student_" + submission.user_id);
if(updateLastUpdatedAt) {
moderation.lastUpdatedAt = new Date(Math.max(Date.parse(submission.updated_at), moderation.lastUpdatedAt));
}
var state_text = "";
if(submission.workflow_state == 'complete' || submission.workflow_state == 'pending_review') {
state_text = I18n.t('finished_in_duration', "finished in %{duration}", {'duration': submission.finished_in_words});
}
var data = {
attempt: submission.attempt || '--',
extra_time: submission.extra_time,
extra_attempts: submission.extra_attempts,
score: submission.kept_score
};
if(submission.attempts_left == -1) {
data.attempts_left = '--';
} else if(submission.attempts_left) {
data.attempts_left = submission.attempts_left;
}
if(submission.workflow_state != 'untaken') {
data.time = state_text;
}
$student
.fillTemplateData({data: data})
.toggleClass('extendable', submission['extendable?'])
.toggleClass('in_progress', submission.workflow_state == 'untaken')
.toggleClass('manually_unlocked', !!submission.manually_unlocked)
.attr('data-started-at', submission.started_at || '')
.attr('data-end-at', submission.end_at || '')
.data('timing', null)
.find(".extra_time_allowed").showIf(submission.extra_time).end()
.find(".unlocked").showIf(submission.manually_unlocked);
},
lastUpdatedAt: "",
studentsCurrentlyTakingQuiz: false
};
$(document).ready(function(event) {
timing.initTimes();
setInterval(moderation.updateTimes, 500)
var updateErrors = 0;
var moderate_url = $(".update_url").attr('href');
moderation.lastUpdatedAt = Date.parse($(".last_updated_at").text());
var currently_updating = false;
var $updating_img = $(".reload_link img");
function updating(bool) {
currently_updating = bool;
if(bool) {
$updating_img.attr('src', $updating_img.attr('src').replace("ajax-reload.gif", "ajax-reload-animated.gif"));
} else {
$updating_img.attr('src', $updating_img.attr('src').replace("ajax-reload-animated.gif", "ajax-reload.gif"));
if(submission.workflow_state != 'untaken') {
data.time = state_text;
}
$student
.fillTemplateData({data: data})
.toggleClass('extendable', submission['extendable?'])
.toggleClass('in_progress', submission.workflow_state == 'untaken')
.toggleClass('manually_unlocked', !!submission.manually_unlocked)
.attr('data-started-at', submission.started_at || '')
.attr('data-end-at', submission.end_at || '')
.data('timing', null)
.find(".extra_time_allowed").showIf(submission.extra_time).end()
.find(".unlocked").showIf(submission.manually_unlocked);
},
lastUpdatedAt: "",
studentsCurrentlyTakingQuiz: false
};
$(document).ready(function(event) {
timing.initTimes();
setInterval(moderation.updateTimes, 500)
var updateErrors = 0;
var moderate_url = $(".update_url").attr('href');
moderation.lastUpdatedAt = Date.parse($(".last_updated_at").text());
var currently_updating = false;
var $updating_img = $(".reload_link img");
function updating(bool) {
currently_updating = bool;
if(bool) {
$updating_img.attr('src', $updating_img.attr('src').replace("ajax-reload.gif", "ajax-reload-animated.gif"));
} else {
$updating_img.attr('src', $updating_img.attr('src').replace("ajax-reload-animated.gif", "ajax-reload.gif"));
}
}
}
function updateSubmissions(repeat) {
if(currently_updating) { return; }
updating(true);
var last_updated_at = moderation.lastUpdatedAt && moderation.lastUpdatedAt.toISOString();
$.ajaxJSON($.replaceTags(moderate_url, 'update', last_updated_at), 'GET', {}, function(data) {
updating(false);
if(repeat) {
if(data.length || moderation.studentsCurrentlyTakingQuiz) {
setTimeout(function() { updateSubmissions(true); }, 60000);
} else {
setTimeout(function() { updateSubmissions(true); }, 180000);
}
}
for(var idx in data) {
moderation.updateSubmission(data[idx], true);
}
}, function(data) {
updating(false);
updateErrors++;
if(updateErrors > 5) {
$.flashMessage(I18n.t('errors.server_communication_failed', "There was a problem communicating with the server. The system will try again in five minutes, or you can reload the page"));
updateErrors = 0;
function updateSubmissions(repeat) {
if(currently_updating) { return; }
updating(true);
var last_updated_at = moderation.lastUpdatedAt && moderation.lastUpdatedAt.toISOString();
$.ajaxJSON($.replaceTags(moderate_url, 'update', last_updated_at), 'GET', {}, function(data) {
updating(false);
if(repeat) {
setTimeout(function() { updateSubmissions(true); }, 300000);
if(data.length || moderation.studentsCurrentlyTakingQuiz) {
setTimeout(function() { updateSubmissions(true); }, 60000);
} else {
setTimeout(function() { updateSubmissions(true); }, 180000);
}
}
} else if(repeat) {
setTimeout(function() { updateSubmissions(true); }, 120000);
}
});
};
setTimeout(function() { updateSubmissions(true); }, 1000);
function checkChange() {
var cnt = $(".student_check:checked").length;
$("#checked_count").text(cnt);
$(".moderate_multiple_button").showIf(cnt);
}
$("#check_all").change(function() {
$(".student_check").attr('checked', $(this).attr('checked'));
checkChange();
});
$(".student_check").change(function() {
if(!$(this).attr('checked')) {
$("#check_all").attr('checked', false);
for(var idx in data) {
moderation.updateSubmission(data[idx], true);
}
}, function(data) {
updating(false);
updateErrors++;
if(updateErrors > 5) {
$.flashMessage(I18n.t('errors.server_communication_failed', "There was a problem communicating with the server. The system will try again in five minutes, or you can reload the page"));
updateErrors = 0;
if(repeat) {
setTimeout(function() { updateSubmissions(true); }, 300000);
}
} else if(repeat) {
setTimeout(function() { updateSubmissions(true); }, 120000);
}
});
};
setTimeout(function() { updateSubmissions(true); }, 1000);
function checkChange() {
var cnt = $(".student_check:checked").length;
$("#checked_count").text(cnt);
$(".moderate_multiple_button").showIf(cnt);
}
checkChange();
});
$(".moderate_multiple_button").live('click', function(event) {
var student_ids = []
var data = {};
$(".student_check:checked").each(function() {
$("#check_all").change(function() {
$(".student_check").attr('checked', $(this).attr('checked'));
checkChange();
});
$(".student_check").change(function() {
if(!$(this).attr('checked')) {
$("#check_all").attr('checked', false);
}
checkChange();
});
$(".moderate_multiple_button").live('click', function(event) {
var student_ids = []
var data = {};
$(".student_check:checked").each(function() {
var $student = $(this).parents(".student");
student_ids.push($(this).attr('data-id'));
var student_data = {
manually_unlocked: $student.hasClass('manually_unlocked') ? '1' : '0',
extra_attempts: parseInt($student.find(".extra_attempts").text(), 10) || "",
extra_time: parseInt($student.find(".extra_time").text(), 10) || ""
};
$.each(['manually_unlocked', 'extra_attempts', 'extra_time'], function() {
if(data[this] == null) {
data[this] = student_data[this].toString();
} else if(data[this] != student_data[this].toString()) {
data[this] = '';
}
});
});
$("#moderate_student_form").data('ids', student_ids);
$("#moderate_student_dialog h2").text(I18n.t('extensions_for_students', {'one': "Extensions for 1 Student", 'other': "Extensions for %{count} Students"}, {'count': student_ids.length}));
$("#moderate_student_form").fillFormData(data);
$("#moderate_student_dialog").dialog('close').dialog({
auotOpen: false,
title: I18n.t('titles.student_extensions', "Student Extensions"),
width: 400
}).dialog('open');
});
$(".moderate_student_link").live('click', function(event) {
event.preventDefault();
var $student = $(this).parents(".student");
student_ids.push($(this).attr('data-id'));
var student_data = {
var data = {
manually_unlocked: $student.hasClass('manually_unlocked') ? '1' : '0',
extra_attempts: parseInt($student.find(".extra_attempts").text(), 10) || "",
extra_time: parseInt($student.find(".extra_time").text(), 10) || ""
};
$.each(['manually_unlocked', 'extra_attempts', 'extra_time'], function() {
if(data[this] == null) {
data[this] = student_data[this].toString();
} else if(data[this] != student_data[this].toString()) {
data[this] = '';
}
});
var name = $student.find(".student_name").text();
$("#moderate_student_form").fillFormData(data);
$("#moderate_student_form").data('ids', [$student.attr('data-user-id')]);
$("#moderate_student_form").find("button").attr('disabled', false);
$("#moderate_student_dialog h2").text(I18n.t('extensions_for_student', "Extensions for %{student}", {'student': name}));
$("#moderate_student_dialog").dialog('close').dialog({
auotOpen: false,
title: I18n.t('titles.student_extensions', "Student Extensions"),
width: 400
}).dialog('open');
});
$("#moderate_student_form").data('ids', student_ids);
$("#moderate_student_dialog h2").text(I18n.t('extensions_for_students', {'one': "Extensions for 1 Student", 'other': "Extensions for %{count} Students"}, {'count': student_ids.length}));
$("#moderate_student_form").fillFormData(data);
$("#moderate_student_dialog").dialog('close').dialog({
auotOpen: false,
title: I18n.t('titles.student_extensions', "Student Extensions"),
width: 400
}).dialog('open');
});
$(".moderate_student_link").live('click', function(event) {
event.preventDefault();
var $student = $(this).parents(".student");
var data = {
manually_unlocked: $student.hasClass('manually_unlocked') ? '1' : '0',
extra_attempts: parseInt($student.find(".extra_attempts").text(), 10) || "",
extra_time: parseInt($student.find(".extra_time").text(), 10) || ""
};
var name = $student.find(".student_name").text();
$("#moderate_student_form").fillFormData(data);
$("#moderate_student_form").data('ids', [$student.attr('data-user-id')]);
$("#moderate_student_form").find("button").attr('disabled', false);
$("#moderate_student_dialog h2").text(I18n.t('extensions_for_student', "Extensions for %{student}", {'student': name}));
$("#moderate_student_dialog").dialog('close').dialog({
auotOpen: false,
title: I18n.t('titles.student_extensions', "Student Extensions"),
width: 400
}).dialog('open');
});
$(".reload_link").click(function(event) {
event.preventDefault();
updateSubmissions();
});
$("#moderate_student_form").submit(function(event) {
event.preventDefault();
event.stopPropagation();
var ids = $(this).data('ids');
if(ids.length == 0) { return; }
var $form = $(this);
$form.find("button").attr('disabled', true).filter(".save_button").text(I18n.t('buttons.saving', "Saving..."));
var finished = 0, errors = 0;
var formData = $(this).getFormData();
function checkIfFinished() {
if(finished >= ids.length) {
if(errors > 0) {
if(ids.length == 1) {
$form.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.save_failed', "Save Failed, please try again"));
$(".reload_link").click(function(event) {
event.preventDefault();
updateSubmissions();
});
$("#moderate_student_form").submit(function(event) {
event.preventDefault();
event.stopPropagation();
var ids = $(this).data('ids');
if(ids.length == 0) { return; }
var $form = $(this);
$form.find("button").attr('disabled', true).filter(".save_button").text(I18n.t('buttons.saving', "Saving..."));
var finished = 0, errors = 0;
var formData = $(this).getFormData();
function checkIfFinished() {
if(finished >= ids.length) {
if(errors > 0) {
if(ids.length == 1) {
$form.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.save_failed', "Save Failed, please try again"));
} else {
$form.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.save_failed_n_updates_lost', "Save Failed, %{n} Students were not updated", {'n': errors}));
}
} else {
$form.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.save_failed_n_updates_lost', "Save Failed, %{n} Students were not updated", {'n': errors}));
$form.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.save', "Save"));
$("#moderate_student_dialog").dialog('close');
}
} else {
$form.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.save', "Save"));
$("#moderate_student_dialog").dialog('close');
}
};
for(var idx in ids) {
var id = ids[idx];
var url = $.replaceTags($(".extension_url").attr('href'), 'user_id', id);
$.ajaxJSON(url, 'POST', formData, function(data) {
finished++;
moderation.updateSubmission(data);
checkIfFinished();
}, function(data) {
finished++;
errors++;
checkIfFinished();
});
}
};
for(var idx in ids) {
var id = ids[idx];
var url = $.replaceTags($(".extension_url").attr('href'), 'user_id', id);
$.ajaxJSON(url, 'POST', formData, function(data) {
finished++;
moderation.updateSubmission(data);
checkIfFinished();
}, function(data) {
finished++;
errors++;
checkIfFinished();
});
$("#moderate_student_dialog").find('.cancel_button').click(function() {
$("#moderate_student_dialog").dialog('close');
});
$(".extend_time_link").live('click', function(event) {
event.preventDefault();
var $row = $(event.target).parents(".student");
var end_at = $.parseFromISO($row.attr('data-end-at')).datetime_formatted;
var started_at = $.parseFromISO($row.attr('data-started-at')).datetime_formatted;
var $dialog = $("#extend_time_dialog");
$dialog.data('row', $row);
$dialog.fillTemplateData({
data: {
end_at: end_at,
started_at: started_at
}
});
}
});
$("#moderate_student_dialog").find('.cancel_button').click(function() {
$("#moderate_student_dialog").dialog('close');
});
$(".extend_time_link").live('click', function(event) {
event.preventDefault();
var $row = $(event.target).parents(".student");
var end_at = $.parseFromISO($row.attr('data-end-at')).datetime_formatted;
var started_at = $.parseFromISO($row.attr('data-started-at')).datetime_formatted;
var $dialog = $("#extend_time_dialog");
$dialog.data('row', $row);
$dialog.fillTemplateData({
data: {
end_at: end_at,
started_at: started_at
$dialog.find("button").attr('disabled', false);
$dialog.dialog('close').dialog({
auto_open: false,
title: I18n.t('titles.extend_quiz_time', "Extend Quiz Time"),
width: 400
}).dialog('open');
});
$("#extend_time_dialog").find(".cancel_button").click(function() {
$("#extend_time_dialog").dialog('close');
}).end().find(".save_button").click(function() {
var $dialog = $("#extend_time_dialog");
var data = $dialog.getFormData();
var params = {};
data.time = parseInt(data.time, 10) || 0;
if(data.time <= 0) { return; }
if(data.time_type == 'extend_from_now' && data.time < $dialog.data('row').data('minutes_left')) {
var result = confirm(I18n.t('confirms.taking_time_away', "That would be less time than the student currently has. Continue anyway?"));
if(!result) { return; }
}
});
$dialog.find("button").attr('disabled', false);
$dialog.dialog('close').dialog({
auto_open: false,
title: I18n.t('titles.extend_quiz_time', "Extend Quiz Time"),
width: 400
}).dialog('open');
});
$("#extend_time_dialog").find(".cancel_button").click(function() {
$("#extend_time_dialog").dialog('close');
}).end().find(".save_button").click(function() {
var $dialog = $("#extend_time_dialog");
var data = $dialog.getFormData();
var params = {};
data.time = parseInt(data.time, 10) || 0;
if(data.time <= 0) { return; }
if(data.time_type == 'extend_from_now' && data.time < $dialog.data('row').data('minutes_left')) {
var result = confirm(I18n.t('confirms.taking_time_away', "That would be less time than the student currently has. Continue anyway?"));
if(!result) { return; }
}
params[data.time_type] = data.time;
$dialog.find("button").attr('disabled', true).filter(".save_button").text(I18n.t('buttons.extending_time', "Extending Time..."));
var url = $.replaceTags($(".extension_url").attr('href'), 'user_id', $dialog.data('row').attr('data-user-id'));
$.ajaxJSON(url, 'POST', params, function(data) {
$dialog.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.extend_time', "Extend Time"));
moderation.updateSubmission(data);
$dialog.dialog('close');
}, function(data) {
$dialog.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.time_extension_failed', "Extend Time Failed, please try again"));
params[data.time_type] = data.time;
$dialog.find("button").attr('disabled', true).filter(".save_button").text(I18n.t('buttons.extending_time', "Extending Time..."));
var url = $.replaceTags($(".extension_url").attr('href'), 'user_id', $dialog.data('row').attr('data-user-id'));
$.ajaxJSON(url, 'POST', params, function(data) {
$dialog.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.extend_time', "Extend Time"));
moderation.updateSubmission(data);
$dialog.dialog('close');
}, function(data) {
$dialog.find("button").attr('disabled', false).filter(".save_button").text(I18n.t('buttons.time_extension_failed', "Extend Time Failed, please try again"));
});
});
});
});
});

View File

@ -1,10 +1,10 @@
I18n.scoped('plugins', function(I18n) {
$("form.edit_plugin_setting").live('submit', function() {
$(this).find("button").attr('disabled', true).filter(".save_button").text(I18n.t('buttons.saving', "Saving..."));
});
$(document).ready(function() {
$(".disabled_checkbox").change(function() {
$("#settings .plugin_settings").showIf(!$(this).attr('checked'));
}).change();
});
$("form.edit_plugin_setting").live('submit', function() {
$(this).find("button").attr('disabled', true).filter(".save_button").text(I18n.t('buttons.saving', "Saving..."));
});
$(document).ready(function() {
$(".disabled_checkbox").change(function() {
$("#settings .plugin_settings").showIf(!$(this).attr('checked'));
}).change();
});
})

View File

@ -18,132 +18,132 @@
var calcCmd;
I18n.scoped('calculator', function(I18n){
var generateFinds = function($table) {
var finds = {};
finds.formula_rows = $table.find(".formula_row");
finds.formula_rows.each(function(i) {
this.formula = $(this).find(".formula");
this.status = $(this).find(".status");
$(this).data('formula', $(this).find(".formula"));
$(this).data('status', $(this).find(".status"));
});
finds.round = $table.find(".round");
finds.status = $table.find(".status");
finds.last_row_details = $table.find(".last_row_details");
return finds;
};
$.fn.superCalc = function(options, more_options) {
if(options == 'recalculate') {
$(this).triggerHandler('calculate', more_options);
} else if(options == 'clear') {
calcCmd.clearMemory();
} else if(options == 'cache_finds') {
$(this).data('cached_finds', generateFinds($(this).data('table')));
} else if(options == 'clear_cached_finds') {
$(this).data('cached_finds', null);
} else {
options = options || {};
options.c1 = true;
var $entryBox = $(this);
var $table = $("<table class='formulas'>" +
"<thead><tr><th>" + $.h(I18n.t('headings.formula', "Formula")) + "</th><th>" + $.h(I18n.t('headings.result', "Result")) + "</th><th>&nbsp;</th></tr></thead>" +
"<tfoot>" +
"<tr><td colspan='3' class='last_row_details' style='display: none;'>" + $.h(I18n.t('last_formula_row', "the last formula row will be used to compute the final answer")) + "</td></tr>" +
"<tr><td></td><td class='decimal_places'>" +
I18n.t('how_many_decimal_places', '%{number_selector} Decimal Places', {number_selector: $.raw("<select class='round'><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option></select>")}) +
"</td></tr>" +
"</tfoot>" +
"<tbody></tbody>"+
"</table>");
$(this).data('table', $table);
$entryBox.before($table);
$table.find("tfoot tr:last td:first").append($entryBox);
var $displayBox = $entryBox.clone(true).removeAttr('id');
$table.find("tfoot tr:last td:first").append($displayBox);
var $enter = $("<button type='button' class='save_formula_button'>" + $.h(I18n.t('buttons.save', "Save")) + "</button>");
$table.find("tfoot tr:last td:first").append($enter);
$entryBox.hide();
var $input = $("<input type='text' readonly='true'/>");
$table.find("tfoot tr:last td:first").append($input.hide());
$entryBox.data('supercalc_options', options);
$entryBox.data('supercalc_answer', $input);
$table.delegate('.save_formula_button', 'click', function() {
$displayBox.triggerHandler('keypress', true);
var generateFinds = function($table) {
var finds = {};
finds.formula_rows = $table.find(".formula_row");
finds.formula_rows.each(function(i) {
this.formula = $(this).find(".formula");
this.status = $(this).find(".status");
$(this).data('formula', $(this).find(".formula"));
$(this).data('status', $(this).find(".status"));
});
$table.delegate('.delete_formula_row_link', 'click', function(event) {
event.preventDefault();
$(event.target).parents("tr").remove();
$entryBox.triggerHandler('calculate');
});
$table.find("tbody").sortable({
items: '.formula_row',
update: function() {
$entryBox.triggerHandler('calculate');
}
});
$table.delegate('.round', 'change', function() {
$entryBox.triggerHandler('calculate');
});
$entryBox.bind('calculate', function(event, no_dom) {
finds.round = $table.find(".round");
finds.status = $table.find(".status");
finds.last_row_details = $table.find(".last_row_details");
return finds;
};
$.fn.superCalc = function(options, more_options) {
if(options == 'recalculate') {
$(this).triggerHandler('calculate', more_options);
} else if(options == 'clear') {
calcCmd.clearMemory();
var finds = $(this).data('cached_finds') || generateFinds($table);
if(options.pre_process && $.isFunction(options.pre_process)) {
var lines = options.pre_process();
for(var idx in lines) {
if(!no_dom) {
$entryBox.val(lines[idx] || "");
}
try {
calcCmd.compute(lines[idx]);
} catch(e) {
}
}
}
finds.formula_rows.each(function() {
var formula_text = this.formula.html();
$entryBox.val(formula_text);
var res = null;
try {
res = "= " + calcCmd.computeValue(formula_text);
} catch(e) {
res = e.toString();
}
if(res && res.match(/=/)) {
var val = parseFloat(res.substring(res.indexOf("=") + 1), 10);
var rounder = Math.pow(10, parseInt(finds.round.val(), 10) || 0) || 1;
var res = "= " + (Math.round(val * rounder) / rounder);
}
this.status.attr('data-res', res);
if(!no_dom) {
this.status.html(res);
} else if(options == 'cache_finds') {
$(this).data('cached_finds', generateFinds($(this).data('table')));
} else if(options == 'clear_cached_finds') {
$(this).data('cached_finds', null);
} else {
options = options || {};
options.c1 = true;
var $entryBox = $(this);
var $table = $("<table class='formulas'>" +
"<thead><tr><th>" + $.h(I18n.t('headings.formula', "Formula")) + "</th><th>" + $.h(I18n.t('headings.result', "Result")) + "</th><th>&nbsp;</th></tr></thead>" +
"<tfoot>" +
"<tr><td colspan='3' class='last_row_details' style='display: none;'>" + $.h(I18n.t('last_formula_row', "the last formula row will be used to compute the final answer")) + "</td></tr>" +
"<tr><td></td><td class='decimal_places'>" +
I18n.t('how_many_decimal_places', '%{number_selector} Decimal Places', {number_selector: $.raw("<select class='round'><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option></select>")}) +
"</td></tr>" +
"</tfoot>" +
"<tbody></tbody>"+
"</table>");
$(this).data('table', $table);
$entryBox.before($table);
$table.find("tfoot tr:last td:first").append($entryBox);
var $displayBox = $entryBox.clone(true).removeAttr('id');
$table.find("tfoot tr:last td:first").append($displayBox);
var $enter = $("<button type='button' class='save_formula_button'>" + $.h(I18n.t('buttons.save', "Save")) + "</button>");
$table.find("tfoot tr:last td:first").append($enter);
$entryBox.hide();
var $input = $("<input type='text' readonly='true'/>");
$table.find("tfoot tr:last td:first").append($input.hide());
$entryBox.data('supercalc_options', options);
$entryBox.data('supercalc_answer', $input);
$table.delegate('.save_formula_button', 'click', function() {
$displayBox.triggerHandler('keypress', true);
});
$table.delegate('.delete_formula_row_link', 'click', function(event) {
event.preventDefault();
$(event.target).parents("tr").remove();
$entryBox.triggerHandler('calculate');
});
$table.find("tbody").sortable({
items: '.formula_row',
update: function() {
$entryBox.triggerHandler('calculate');
}
});
if(!no_dom) {
if(finds.formula_rows.length > 1) {
finds.formula_rows.removeClass('last_row').filter(":last").addClass('last_row');
}
finds.last_row_details.showIf(finds.formula_rows.length > 1);
finds.status.removeAttr('title').filter(":last").attr('title', I18n.t('sample_final_answer', 'This value is an example final answer for this question type'));
$entryBox.val("");
}
});
$displayBox.bind('keypress', function(event, enter) {
$entryBox.val($displayBox.val());
if(event.keyCode == 13 || enter && $displayBox.val()) {
event.preventDefault();
event.stopPropagation();
var $tr = $("<tr class='formula_row'><td class='formula' title='" + $.h(I18n.t('drag_to_reorder', 'Drag to reorder')) + "'></td><td class='status'></td><td><a href='#' class='delete_formula_row_link no-hover'><img src='/images/delete_circle.png'/></a></td></tr>");
$tr.find("td:first").text($entryBox.val());
$entryBox.val("");
$displayBox.val("");
$table.find("tbody").append($tr);
$table.delegate('.round', 'change', function() {
$entryBox.triggerHandler('calculate');
$displayBox.focus();
if(options && options.formula_added && $.isFunction(options.formula_added)) {
options.formula_added.call($entryBox);
});
$entryBox.bind('calculate', function(event, no_dom) {
calcCmd.clearMemory();
var finds = $(this).data('cached_finds') || generateFinds($table);
if(options.pre_process && $.isFunction(options.pre_process)) {
var lines = options.pre_process();
for(var idx in lines) {
if(!no_dom) {
$entryBox.val(lines[idx] || "");
}
try {
calcCmd.compute(lines[idx]);
} catch(e) {
}
}
}
}
});
}
};
finds.formula_rows.each(function() {
var formula_text = this.formula.html();
$entryBox.val(formula_text);
var res = null;
try {
res = "= " + calcCmd.computeValue(formula_text);
} catch(e) {
res = e.toString();
}
if(res && res.match(/=/)) {
var val = parseFloat(res.substring(res.indexOf("=") + 1), 10);
var rounder = Math.pow(10, parseInt(finds.round.val(), 10) || 0) || 1;
var res = "= " + (Math.round(val * rounder) / rounder);
}
this.status.attr('data-res', res);
if(!no_dom) {
this.status.html(res);
}
});
if(!no_dom) {
if(finds.formula_rows.length > 1) {
finds.formula_rows.removeClass('last_row').filter(":last").addClass('last_row');
}
finds.last_row_details.showIf(finds.formula_rows.length > 1);
finds.status.removeAttr('title').filter(":last").attr('title', I18n.t('sample_final_answer', 'This value is an example final answer for this question type'));
$entryBox.val("");
}
});
$displayBox.bind('keypress', function(event, enter) {
$entryBox.val($displayBox.val());
if(event.keyCode == 13 || enter && $displayBox.val()) {
event.preventDefault();
event.stopPropagation();
var $tr = $("<tr class='formula_row'><td class='formula' title='" + $.h(I18n.t('drag_to_reorder', 'Drag to reorder')) + "'></td><td class='status'></td><td><a href='#' class='delete_formula_row_link no-hover'><img src='/images/delete_circle.png'/></a></td></tr>");
$tr.find("td:first").text($entryBox.val());
$entryBox.val("");
$displayBox.val("");
$table.find("tbody").append($tr);
$entryBox.triggerHandler('calculate');
$displayBox.focus();
if(options && options.formula_added && $.isFunction(options.formula_added)) {
options.formula_added.call($entryBox);
}
}
});
}
};
});

View File

@ -23,7 +23,7 @@ describe I18nExtraction::JsExtractor do
scope_results = scope && (options.has_key?(:scope_results) ? options.delete(:scope_results) : true)
extractor = I18nExtraction::JsExtractor.new
source = "I18n.scoped('#{scope}', function(I18n) {\n#{source}\n});" if scope
source = "I18n.scoped('#{scope}', function(I18n) {\n#{source.gsub(/^/, ' ')}\n});" if scope
extractor.process(source, options)
(scope_results ?
scope.split(/\./).inject(extractor.translations) { |hash, s| hash[s] } :
@ -93,6 +93,21 @@ describe I18nExtraction::JsExtractor do
end
context "scoping" do
it "should correctly infer the scope" do
extract(<<-SOURCE, nil).should == {'asdf' => {'bar' => 'Bar'}}
I18n.scoped('asdf', function(I18n) {
I18n.t('bar', 'Bar');
});
SOURCE
extract(<<-SOURCE, nil).should == {'asdf' => {'bar' => 'Bar'}}
require(['i18n'], function(I18n) {
I18n = I18n.scoped('asdf');
I18n.t('bar', 'Bar');
});
SOURCE
end
it "should require a scope for all I18n calls" do
lambda{ extract(<<-SOURCE, nil) }.should raise_error /possibly unscoped I18n call on line 4/
I18n.scoped('asdf', function(I18n) {
@ -100,6 +115,14 @@ describe I18nExtraction::JsExtractor do
});
I18n.t('foo', 'Foo');
SOURCE
lambda{ extract(<<-SOURCE, nil) }.should raise_error /possibly unscoped I18n call on line 5/
require(['i18n'], function(I18n) {
I18n = I18n.scoped('asdf');
I18n.t('bar', 'Bar');
});
I18n.t('foo', 'Foo');
SOURCE
end
it "should auto-scope relative keys to the current scope" do