base.js 28.1 KB
Newer Older
1 2 3 4
var $body;
var $modal;
var $modalCover;
var $newComponentItem;
5 6
var $changedInput;
var $spinner;
7

cahrens committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
$(document).ready(function () {
    $body = $('body');
    $modal = $('.history-modal');
    $modalCover = $('<div class="modal-cover">');
    // cdodge: this looks funny, but on AWS instances, this base.js get's wrapped in a separate scope as part of Django static
    // pipelining (note, this doesn't happen on local runtimes). So if we set it on window, when we can access it from other
    // scopes (namely the course-info tab)
    window.$modalCover = $modalCover;

    // Control whether template caching in local memory occurs (see template_loader.js). Caching screws up development but may
    // be a good optimization in production (it works fairly well)
    window.cachetemplates = false;

    $body.append($modalCover);
    $newComponentItem = $('.new-component-item');
    $newComponentTypePicker = $('.new-component');
    $newComponentTemplatePickers = $('.new-component-templates');
    $newComponentButton = $('.new-component-button');
    $spinner = $('<span class="spinner-in-field-icon"></span>');
    $body.bind('keyup', onKeyUp);

    $('.expand-collapse-icon').bind('click', toggleSubmodules);
    $('.visibility-options').bind('change', setVisibility);

    $modal.bind('click', hideModal);
    $modalCover.bind('click', hideModal);
    $('.uploads .upload-button').bind('click', showUploadModal);
    $('.upload-modal .close-button').bind('click', hideModal);

    $body.on('click', '.embeddable-xml-input', function () {
        $(this).select();
    });
40

cahrens committed
41 42
    $('.unit .item-actions .delete-button').bind('click', deleteUnit);
    $('.new-unit-item').bind('click', createNewUnit);
43

cahrens committed
44
    $('body').addClass('js');
45

46 47 48 49 50
    // lean/simple modal
    $('a[rel*=modal]').leanModal({overlay : 0.80, closeButton: '.action-modal-close' });
    $('a.action-modal-close').click(function(e){
        (e).preventDefault();
    });
51

cahrens committed
52 53 54 55 56
    // nav - dropdown related
    $body.click(function (e) {
        $('.nav-dropdown .nav-item .wrapper-nav-sub').removeClass('is-shown');
        $('.nav-dropdown .nav-item .title').removeClass('is-selected');
    });
Chris Dodge committed
57

cahrens committed
58
    $('.nav-dropdown .nav-item .title').click(function (e) {
59

cahrens committed
60 61 62 63
        $subnav = $(this).parent().find('.wrapper-nav-sub');
        $title = $(this).parent().find('.title');
        e.preventDefault();
        e.stopPropagation();
64

cahrens committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        if ($subnav.hasClass('is-shown')) {
            $subnav.removeClass('is-shown');
            $title.removeClass('is-selected');
        }

        else {
            $('.nav-dropdown .nav-item .title').removeClass('is-selected');
            $('.nav-dropdown .nav-item .wrapper-nav-sub').removeClass('is-shown');
            $title.addClass('is-selected');
            $subnav.addClass('is-shown');
        }
    });

    // general link management - new window/tab
    $('a[rel="external"]').attr('title', 'This link will open in a new browser window/tab').click(function (e) {
        window.open($(this).attr('href'));
        e.preventDefault();
    });

    // general link management - lean modal window
    $('a[rel="modal"]').attr('title', 'This link will open in a modal window').leanModal({overlay: 0.50, closeButton: '.action-modal-close' });
    $('.action-modal-close').click(function (e) {
        (e).preventDefault();
    });

    // toggling overview section details
    $(function () {
        if ($('.courseware-section').length > 0) {
            $('.toggle-button-sections').addClass('is-shown');
        }
    });
    $('.toggle-button-sections').bind('click', toggleSections);

    // autosave when a field is updated on the subsection page
    $body.on('keyup', '.subsection-display-name-input, .unit-subtitle, .policy-list-value', checkForNewValue);
    $('.subsection-display-name-input, .unit-subtitle, .policy-list-name, .policy-list-value').each(function (i) {
        this.val = $(this).val();
    });
    $("#start_date, #start_time, #due_date, #due_time").bind('change', autosaveInput);
    $('.sync-date, .remove-date').bind('click', autosaveInput);

    // expand/collapse methods for optional date setters
    $('.set-date').bind('click', showDateSetter);
    $('.remove-date').bind('click', removeDateSetter);
    // add new/delete section
    $('.new-courseware-section-button').bind('click', addNewSection);
    $('.delete-section-button').bind('click', deleteSection);

    // add new/delete subsection
    $('.new-subsection-item').bind('click', addNewSubsection);
    $('.delete-subsection-button').bind('click', deleteSubsection);
    // add/remove policy metadata button click handlers
    $('.add-policy-data').bind('click', addPolicyMetadata);
    $('.remove-policy-data').bind('click', removePolicyMetadata);
    $body.on('click', '.policy-list-element .save-button', savePolicyMetadata);
    $body.on('click', '.policy-list-element .cancel-button', cancelPolicyMetadata);

    $('.sync-date').bind('click', syncReleaseDate);

    // import form setup
    $('.import .file-input').bind('change', showImportSubmit);
    $('.import .choose-file-button, .import .choose-file-button-inline').bind('click', function (e) {
        e.preventDefault();
        $('.import .file-input').click();
    });

    $('.new-course-button').bind('click', addNewCourse);

    // section name editing
    $('.section-name').bind('click', editSectionName);
    $('.edit-section-name-cancel').bind('click', cancelEditSectionName);
    // $('.edit-section-name-save').bind('click', saveEditSectionName);

    // section date setting
    $('.set-publish-date').bind('click', setSectionScheduleDate);
    $('.edit-section-start-cancel').bind('click', cancelSetSectionScheduleDate);
    $('.edit-section-start-save').bind('click', saveSetSectionScheduleDate);

    $('.upload-modal .choose-file-button').bind('click', showFileSelectionMenu);

    $body.on('click', '.section-published-date .edit-button', editSectionPublishDate);
    $body.on('click', '.section-published-date .schedule-button', editSectionPublishDate);
    $body.on('click', '.edit-subsection-publish-settings .save-button', saveSetSectionScheduleDate);
    $body.on('click', '.edit-subsection-publish-settings .cancel-button', hideModal);
    $body.on('change', '.edit-subsection-publish-settings .start-date', function () {
        if ($('.edit-subsection-publish-settings').find('.start-time').val() == '') {
            $('.edit-subsection-publish-settings').find('.start-time').val('12:00am');
        }
    });
    $('.edit-subsection-publish-settings').on('change', '.start-date, .start-time', function () {
        $('.edit-subsection-publish-settings').find('.save-button').show();
    });
157 158
});

159 160 161 162
// function collapseAll(e) {
//     $('.branch').addClass('collapsed');
//     $('.expand-collapse-icon').removeClass('collapse').addClass('expand');
// }
163

164
function toggleSections(e) {
cahrens committed
165
    e.preventDefault();
166

cahrens committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    $section = $('.courseware-section');
    sectionCount = $section.length;
    $button = $(this);
    $labelCollapsed = $('<i class="ss-icon ss-symbolicons-block">up</i> <span class="label">Collapse All Sections</span>');
    $labelExpanded = $('<i class="ss-icon ss-symbolicons-block">down</i> <span class="label">Expand All Sections</span>');

    var buttonLabel = $button.hasClass('is-activated') ? $labelCollapsed : $labelExpanded;
    $button.toggleClass('is-activated').html(buttonLabel);

    if ($button.hasClass('is-activated')) {
        $section.addClass('collapsed');
        // first child in order to avoid the icons on the subsection lists which are not in the first child
        $section.find('header .expand-collapse-icon').removeClass('collapse').addClass('expand');
    } else {
        $section.removeClass('collapsed');
        // first child in order to avoid the icons on the subsection lists which are not in the first child
        $section.find('header .expand-collapse-icon').removeClass('expand').addClass('collapse');
    }
185 186
}

187
function editSectionPublishDate(e) {
cahrens committed
188 189 190 191 192 193 194 195 196 197 198
    e.preventDefault();
    $modal = $('.edit-subsection-publish-settings').show();
    $modal = $('.edit-subsection-publish-settings').show();
    $modal.attr('data-id', $(this).attr('data-id'));
    $modal.find('.start-date').val($(this).attr('data-date'));
    $modal.find('.start-time').val($(this).attr('data-time'));
    if ($modal.find('.start-date').val() == '' && $modal.find('.start-time').val() == '') {
        $modal.find('.save-button').hide();
    }
    $modal.find('.section-name').html('"' + $(this).closest('.courseware-section').find('.section-name-span').text() + '"');
    $modalCover.show();
199 200
}

Tom Giannattasio committed
201
function showImportSubmit(e) {
cahrens committed
202 203 204 205 206 207 208 209 210 211 212
    var filepath = $(this).val();
    if (filepath.substr(filepath.length - 6, 6) == 'tar.gz') {
        $('.error-block').hide();
        $('.file-name').html($(this).val().replace('C:\\fakepath\\', ''));
        $('.file-name-block').show();
        $('.import .choose-file-button').hide();
        $('.submit-button').show();
        $('.progress').show();
    } else {
        $('.error-block').html('File format not supported. Please upload a file with a <code>tar.gz</code> extension.').show();
    }
Tom Giannattasio committed
213 214
}

215
function syncReleaseDate(e) {
cahrens committed
216 217 218 219
    e.preventDefault();
    $(this).closest('.notice').hide();
    $("#start_date").val("");
    $("#start_time").val("");
220 221
}

222
function addPolicyMetadata(e) {
cahrens committed
223 224 225 226 227 228 229
    e.preventDefault();
    var template = $('#add-new-policy-element-template > li');
    var newNode = template.clone();
    var _parent_el = $(this).parent('ol:.policy-list');
    newNode.insertBefore('.add-policy-data');
    $('.remove-policy-data').bind('click', removePolicyMetadata);
    newNode.find('.policy-list-name').focus();
230 231
}

232
function savePolicyMetadata(e) {
cahrens committed
233
    e.preventDefault();
234

cahrens committed
235 236 237 238 239
    var $policyElement = $(this).parents('.policy-list-element');
    saveSubsection()
    $policyElement.removeClass('new-policy-list-element');
    $policyElement.find('.policy-list-name').attr('disabled', 'disabled');
    $policyElement.removeClass('editing');
240 241 242
}

function cancelPolicyMetadata(e) {
cahrens committed
243
    e.preventDefault();
244

cahrens committed
245 246 247 248 249 250 251 252 253
    var $policyElement = $(this).parents('.policy-list-element');
    if (!$policyElement.hasClass('editing')) {
        $policyElement.remove();
    } else {
        $policyElement.removeClass('new-policy-list-element');
        $policyElement.find('.policy-list-name').val($policyElement.data('currentValues')[0]);
        $policyElement.find('.policy-list-value').val($policyElement.data('currentValues')[1]);
    }
    $policyElement.removeClass('editing');
254 255 256
}

function removePolicyMetadata(e) {
cahrens committed
257
    e.preventDefault();
258

cahrens committed
259 260
    if (!confirm('Are you sure you wish to delete this item. It cannot be reversed!'))
        return;
261

cahrens committed
262 263 264 265 266 267 268 269
    policy_name = $(this).data('policy-name');
    var _parent_el = $(this).parent('li:.policy-list-element');
    if ($(_parent_el).hasClass("new-policy-list-element")) {
        _parent_el.remove();
    } else {
        _parent_el.appendTo("#policy-to-delete");
    }
    saveSubsection()
270
}
Lyla Fischer committed
271

272
function getEdxTimeFromDateTimeVals(date_val, time_val, format) {
cahrens committed
273
    var edxTimeStr = null;
274

cahrens committed
275 276 277
    if (date_val != '') {
        if (time_val == '')
            time_val = '00:00';
278

cahrens committed
279 280 281 282
        // Note, we are using date.js utility which has better parsing abilities than the built in JS date parsing
        date = Date.parse(date_val + " " + time_val);
        if (format == null)
            format = 'yyyy-MM-ddTHH:mm';
283

cahrens committed
284 285
        edxTimeStr = date.toString(format);
    }
286

cahrens committed
287
    return edxTimeStr;
288 289
}

290
function getEdxTimeFromDateTimeInputs(date_id, time_id, format) {
cahrens committed
291 292
    var input_date = $('#' + date_id).val();
    var input_time = $('#' + time_id).val();
293

cahrens committed
294
    return getEdxTimeFromDateTimeVals(input_date, input_time, format);
295 296
}

297
function checkForNewValue(e) {
cahrens committed
298 299
    if ($(this).parents('.new-policy-list-element')[0]) {
        return;
300 301
    }

cahrens committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    if (this.val) {
        this.hasChanged = this.val != $(this).val();
    } else {
        this.hasChanged = false;
    }

    this.val = $(this).val();
    if (this.hasChanged) {
        if (this.saveTimer) {
            clearTimeout(this.saveTimer);
        }

        this.saveTimer = setTimeout(function () {
            $changedInput = $(e.target);
            saveSubsection();
            this.saveTimer = null;
        }, 500);
    }
320 321
}

322
function autosaveInput(e) {
cahrens committed
323 324 325
    if (this.saveTimer) {
        clearTimeout(this.saveTimer);
    }
326

cahrens committed
327 328 329 330 331
    this.saveTimer = setTimeout(function () {
        $changedInput = $(e.target);
        saveSubsection();
        this.saveTimer = null;
    }, 500);
332
}
333

334
function saveSubsection() {
cahrens committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    if ($changedInput && !$changedInput.hasClass('no-spinner')) {
        $spinner.css({
            'position': 'absolute',
            'top': Math.floor($changedInput.position().top + ($changedInput.outerHeight() / 2) + 3),
            'left': $changedInput.position().left + $changedInput.outerWidth() - 24,
            'margin-top': '-10px'
        });
        $changedInput.after($spinner);
        $spinner.show();
    }

    var id = $('.subsection-body').data('id');

    // pull all 'normalized' metadata editable fields on page
    var metadata_fields = $('input[data-metadata-name]');

    var metadata = {};
    for (var i = 0; i < metadata_fields.length; i++) {
        var el = metadata_fields[i];
        metadata[$(el).data("metadata-name")] = el.value;
355
    }
cahrens committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

    // now add 'free-formed' metadata which are presented to the user as dual input fields (name/value)
    $('ol.policy-list > li.policy-list-element').each(function (i, element) {
        var name = $(element).children('.policy-list-name').val();
        metadata[name] = $(element).children('.policy-list-value').val();
    });

    // now add any 'removed' policy metadata which is stored in a separate hidden div
    // 'null' presented to the server means 'remove'
    $("#policy-to-delete > li.policy-list-element").each(function (i, element) {
        var name = $(element).children('.policy-list-name').val();
        if (name != "")
            metadata[name] = null;
    });

    // Piece back together the date/time UI elements into one date/time string
    // NOTE: our various "date/time" metadata elements don't always utilize the same formatting string
    // so make sure we're passing back the correct format
    metadata['start'] = getEdxTimeFromDateTimeInputs('start_date', 'start_time');
    metadata['due'] = getEdxTimeFromDateTimeInputs('due_date', 'due_time', 'MMMM dd HH:mm');

    $.ajax({
        url: "/save_item",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({ 'id': id, 'metadata': metadata}),
        success: function () {
            $spinner.delay(500).fadeOut(150);
        },
        error: function () {
            showToastMessage('There has been an error while saving your changes.');
        }
    });
390 391
}

392

393
function createNewUnit(e) {
cahrens committed
394
    e.preventDefault();
395

cahrens committed
396 397
    parent = $(this).data('parent');
    template = $(this).data('template');
398

cahrens committed
399 400 401 402 403 404 405 406 407
    $.post('/clone_item',
        {'parent_location': parent,
            'template': template,
            'display_name': 'New Unit'
        },
        function (data) {
            // redirect to the edit page
            window.location = "/edit/" + data['id'];
        });
408 409
}

410
function deleteUnit(e) {
cahrens committed
411 412
    e.preventDefault();
    _deleteItem($(this).parents('li.leaf'));
413 414 415
}

function deleteSubsection(e) {
cahrens committed
416 417
    e.preventDefault();
    _deleteItem($(this).parents('li.branch'));
418
}
419

420
function deleteSection(e) {
cahrens committed
421 422
    e.preventDefault();
    _deleteItem($(this).parents('section.branch'));
423
}
424

425
function _deleteItem($el) {
cahrens committed
426 427 428 429 430 431 432 433 434 435
    if (!confirm('Are you sure you wish to delete this item. It cannot be reversed!'))
        return;

    var id = $el.data('id');

    $.post('/delete_item',
        {'id': id, 'delete_children': true, 'delete_all_versions': true},
        function (data) {
            $el.remove();
        });
436 437
}

438
function showUploadModal(e) {
cahrens committed
439 440 441 442
    e.preventDefault();
    $modal = $('.upload-modal').show();
    $('.file-input').bind('change', startUpload);
    $modalCover.show();
443 444 445
}

function showFileSelectionMenu(e) {
cahrens committed
446 447
    e.preventDefault();
    $('.file-input').click();
448 449 450
}

function startUpload(e) {
cahrens committed
451 452 453 454 455 456 457 458 459
    $('.upload-modal h1').html('Uploading…');
    $('.upload-modal .file-name').html($('.file-input').val().replace('C:\\fakepath\\', ''));
    $('.upload-modal .file-chooser').ajaxSubmit({
        beforeSend: resetUploadBar,
        uploadProgress: showUploadFeedback,
        complete: displayFinishedUpload
    });
    $('.upload-modal .choose-file-button').hide();
    $('.upload-modal .progress-bar').removeClass('loaded').show();
460 461
}

cahrens committed
462 463 464 465
function resetUploadBar() {
    var percentVal = '0%';
    $('.upload-modal .progress-fill').width(percentVal);
    $('.upload-modal .progress-fill').html(percentVal);
466 467 468
}

function showUploadFeedback(event, position, total, percentComplete) {
cahrens committed
469 470 471
    var percentVal = percentComplete + '%';
    $('.upload-modal .progress-fill').width(percentVal);
    $('.upload-modal .progress-fill').html(percentVal);
472 473 474
}

function displayFinishedUpload(xhr) {
cahrens committed
475 476 477
    if (xhr.status = 200) {
        markAsLoaded();
    }
478

cahrens committed
479 480 481 482 483 484 485
    var resp = JSON.parse(xhr.responseText);
    $('.upload-modal .embeddable-xml-input').val(xhr.getResponseHeader('asset_url'));
    $('.upload-modal .embeddable').show();
    $('.upload-modal .file-name').hide();
    $('.upload-modal .progress-fill').html(resp.msg);
    $('.upload-modal .choose-file-button').html('Load Another File').show();
    $('.upload-modal .progress-fill').width('100%');
486

cahrens committed
487 488
    // see if this id already exists, if so, then user must have updated an existing piece of content
    $("tr[data-id='" + resp.url + "']").remove();
489

cahrens committed
490 491 492
    var template = $('#new-asset-element').html();
    var html = Mustache.to_html(template, resp);
    $('table > tbody').prepend(html);
493

494 495
}

496
function markAsLoaded() {
cahrens committed
497 498 499
    $('.upload-modal .copy-button').css('display', 'inline-block');
    $('.upload-modal .progress-bar').addClass('loaded');
}
500 501

function hideModal(e) {
cahrens committed
502 503 504 505 506 507 508 509 510 511 512
    if (e) {
        e.preventDefault();
    }
    // Unit editors do not want the modal cover to hide when users click outside
    // of the editor. Users must press Cancel or Save to exit the editor.
    // module_edit adds and removes the "is-fixed" class.
    if (!$modalCover.hasClass("is-fixed")) {
        $('.file-input').unbind('change', startUpload);
        $modal.hide();
        $modalCover.hide();
    }
513 514 515
}

function onKeyUp(e) {
cahrens committed
516 517 518
    if (e.which == 87) {
        $body.toggleClass('show-wip hide-wip');
    }
519 520
}

521
function toggleSubmodules(e) {
cahrens committed
522 523 524
    e.preventDefault();
    $(this).toggleClass('expand').toggleClass('collapse');
    $(this).closest('.branch, .window').toggleClass('collapsed');
525 526 527
}

function setVisibility(e) {
cahrens committed
528 529
    $(this).find('.checked').removeClass('checked');
    $(e.target).closest('.option').addClass('checked');
530 531 532
}

function editComponent(e) {
cahrens committed
533 534
    e.preventDefault();
    $(this).closest('.xmodule_edit').addClass('editing').find('.component-editor').slideDown(150);
535 536 537
}

function closeComponentEditor(e) {
cahrens committed
538 539
    e.preventDefault();
    $(this).closest('.xmodule_edit').removeClass('editing').find('.component-editor').slideUp(150);
540 541
}

542
function showDateSetter(e) {
cahrens committed
543 544 545 546
    e.preventDefault();
    var $block = $(this).closest('.due-date-input');
    $(this).hide();
    $block.find('.date-setter').show();
547
}
548

549
function removeDateSetter(e) {
cahrens committed
550 551 552 553 554 555 556
    e.preventDefault();
    var $block = $(this).closest('.due-date-input');
    $block.find('.date-setter').hide();
    $block.find('.set-date').show();
    // clear out the values
    $block.find('.date').val('');
    $block.find('.time').val('');
557
}
558

559
function showToastMessage(message, $button, lifespan) {
cahrens committed
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    var $toast = $('<div class="toast-notification"></div>');
    var $closeBtn = $('<a href="#" class="close-button">×</a>');
    $toast.append($closeBtn);
    var $content = $('<div class="notification-content"></div>');
    $content.html(message);
    $toast.append($content);
    if ($button) {
        $button.addClass('action-button');
        $button.bind('click', hideToastMessage);
        $content.append($button);
    }
    $closeBtn.bind('click', hideToastMessage);

    if ($('.toast-notification')[0]) {
        var targetY = $('.toast-notification').offset().top + $('.toast-notification').outerHeight();
        $toast.css('top', (targetY + 10) + 'px');
    }

    $body.prepend($toast);
    $toast.fadeIn(200);

    if (lifespan) {
        $toast.timer = setTimeout(function () {
            $toast.fadeOut(300);
        }, lifespan * 1000);
    }
586
}
587

588
function hideToastMessage(e) {
cahrens committed
589 590
    e.preventDefault();
    $(this).closest('.toast-notification').remove();
591
}
592

593
function addNewSection(e, isTemplate) {
cahrens committed
594
    e.preventDefault();
595

cahrens committed
596
    $(e.target).addClass('disabled');
597

cahrens committed
598 599 600 601 602 603 604
    var $newSection = $($('#new-section-template').html());
    var $cancelButton = $newSection.find('.new-section-name-cancel');
    $('.courseware-overview').prepend($newSection);
    $newSection.find('.new-section-name').focus().select();
    $newSection.find('.section-name-form').bind('submit', saveNewSection);
    $cancelButton.bind('click', cancelNewSection);
    $body.bind('keyup', { $cancelButton: $cancelButton }, checkForCancel);
605 606 607
}

function checkForCancel(e) {
cahrens committed
608 609 610 611
    if (e.which == 27) {
        $body.unbind('keyup', checkForCancel);
        e.data.$cancelButton.click();
    }
612 613
}

Chris Dodge committed
614

615
function saveNewSection(e) {
cahrens committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    e.preventDefault();

    var $saveButton = $(this).find('.new-section-name-save');
    var parent = $saveButton.data('parent');
    var template = $saveButton.data('template');
    var display_name = $(this).find('.new-section-name').val();

    $.post('/clone_item', {
            'parent_location': parent,
            'template': template,
            'display_name': display_name,
        },
        function (data) {
            if (data.id != undefined)
                location.reload();
        }
    );
633 634 635
}

function cancelNewSection(e) {
cahrens committed
636 637 638
    e.preventDefault();
    $('.new-courseware-section-button').removeClass('disabled');
    $(this).parents('section.new-section').remove();
639 640
}

Chris Dodge committed
641
function addNewCourse(e) {
cahrens committed
642
    e.preventDefault();
643

cahrens committed
644 645 646
    $(e.target).hide();
    var $newCourse = $($('#new-course-template').html());
    var $cancelButton = $newCourse.find('.new-course-cancel');
647
    $('.inner-wrapper').prepend($newCourse);
cahrens committed
648 649 650 651
    $newCourse.find('.new-course-name').focus().select();
    $newCourse.find('form').bind('submit', saveNewCourse);
    $cancelButton.bind('click', cancelNewCourse);
    $body.bind('keyup', { $cancelButton: $cancelButton }, checkForCancel);
Chris Dodge committed
652 653 654
}

function saveNewCourse(e) {
cahrens committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
    e.preventDefault();

    var $newCourse = $(this).closest('.new-course');
    var template = $(this).find('.new-course-save').data('template');
    var org = $newCourse.find('.new-course-org').val();
    var number = $newCourse.find('.new-course-number').val();
    var display_name = $newCourse.find('.new-course-name').val();

    if (org == '' || number == '' || display_name == '') {
        alert('You must specify all fields in order to create a new course.');
        return;
    }

    $.post('/create_new_course', {
            'template': template,
            'org': org,
            'number': number,
            'display_name': display_name
        },
        function (data) {
            if (data.id != undefined) {
                window.location = '/' + data.id.replace(/.*:\/\//, '');
            } else if (data.ErrMsg != undefined) {
                alert(data.ErrMsg);
            }
        });
Chris Dodge committed
681 682 683
}

function cancelNewCourse(e) {
cahrens committed
684 685 686
    e.preventDefault();
    $('.new-course-button').show();
    $(this).parents('section.new-course').remove();
Chris Dodge committed
687 688
}

689
function addNewSubsection(e) {
cahrens committed
690 691 692 693 694
    e.preventDefault();
    var $section = $(this).closest('.courseware-section');
    var $newSubsection = $($('#new-subsection-template').html());
    $section.find('.subsection-list > ol').append($newSubsection);
    $section.find('.new-subsection-name-input').focus().select();
695

cahrens committed
696 697
    var $saveButton = $newSubsection.find('.new-subsection-name-save');
    var $cancelButton = $newSubsection.find('.new-subsection-name-cancel');
698

cahrens committed
699
    var parent = $(this).parents("section.branch").data("id");
700

cahrens committed
701 702
    $saveButton.data('parent', parent);
    $saveButton.data('template', $(this).data('template'));
703

cahrens committed
704 705 706
    $newSubsection.find('.new-subsection-form').bind('submit', saveNewSubsection);
    $cancelButton.bind('click', cancelNewSubsection);
    $body.bind('keyup', { $cancelButton: $cancelButton }, checkForCancel);
707 708 709
}

function saveNewSubsection(e) {
cahrens committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
    e.preventDefault();

    var parent = $(this).find('.new-subsection-name-save').data('parent');
    var template = $(this).find('.new-subsection-name-save').data('template');

    var display_name = $(this).find('.new-subsection-name-input').val();

    $.post('/clone_item', {
            'parent_location': parent,
            'template': template,
            'display_name': display_name
        },
        function (data) {
            if (data.id != undefined) {
                location.reload();
            }
        }
    );
728 729 730
}

function cancelNewSubsection(e) {
cahrens committed
731 732
    e.preventDefault();
    $(this).parents('li.branch').remove();
733
}
734 735

function editSectionName(e) {
cahrens committed
736 737 738 739 740 741 742 743
    e.preventDefault();
    $(this).unbind('click', editSectionName);
    $(this).children('.section-name-edit').show();
    $(this).find('.edit-section-name').focus();
    $(this).children('.section-name-span').hide();
    $(this).find('.section-name-edit').bind('submit', saveEditSectionName);
    $(this).find('.edit-section-name-cancel').bind('click', cancelNewSection);
    $body.bind('keyup', { $cancelButton: $(this).find('.edit-section-name-cancel') }, checkForCancel);
744 745 746
}

function cancelEditSectionName(e) {
cahrens committed
747 748 749 750 751
    e.preventDefault();
    $(this).parent().hide();
    $(this).parent().siblings('.section-name-span').show();
    $(this).closest('.section-name').bind('click', editSectionName);
    e.stopPropagation();
752 753 754
}

function saveEditSectionName(e) {
cahrens committed
755
    e.preventDefault();
756

cahrens committed
757
    $(this).closest('.section-name').unbind('click', editSectionName);
758

cahrens committed
759 760
    var id = $(this).closest('.courseware-section').data('id');
    var display_name = $.trim($(this).find('.edit-section-name').val());
761

cahrens committed
762 763
    $(this).closest('.courseware-section .section-name').append($spinner);
    $spinner.show();
764

cahrens committed
765 766 767 768
    if (display_name == '') {
        alert("You must specify a name before saving.");
        return;
    }
769

cahrens committed
770
    var $_this = $(this);
771
    // call into server to commit the new order
cahrens committed
772 773 774 775 776 777 778 779 780 781 782 783 784
    $.ajax({
        url: "/save_item",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({ 'id': id, 'metadata': {'display_name': display_name}})
    }).success(function () {
            $spinner.delay(250).fadeOut(250);
            $_this.closest('h3').find('.section-name-span').html(display_name).show();
            $_this.hide();
            $_this.closest('.section-name').bind('click', editSectionName);
            e.stopPropagation();
        });
785
}
786 787

function setSectionScheduleDate(e) {
cahrens committed
788 789 790
    e.preventDefault();
    $(this).closest("h4").hide();
    $(this).parent().siblings(".datepair").show();
791 792 793
}

function cancelSetSectionScheduleDate(e) {
cahrens committed
794 795 796
    e.preventDefault();
    $(this).closest(".datepair").hide();
    $(this).parent().siblings("h4").show();
797 798 799
}

function saveSetSectionScheduleDate(e) {
cahrens committed
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    e.preventDefault();

    var input_date = $('.edit-subsection-publish-settings .start-date').val();
    var input_time = $('.edit-subsection-publish-settings .start-time').val();

    var start = getEdxTimeFromDateTimeVals(input_date, input_time);

    var id = $modal.attr('data-id');

    // call into server to commit the new order
    $.ajax({
        url: "/save_item",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({ 'id': id, 'metadata': {'start': start}})
    }).success(function () {
            var $thisSection = $('.courseware-section[data-id="' + id + '"]');
            $thisSection.find('.section-published-date').html('<span class="published-status"><strong>Will Release:</strong> ' + input_date + ' at ' + input_time + '</span><a href="#" class="edit-button" data-date="' + input_date + '" data-time="' + input_time + '" data-id="' + id + '">Edit</a>');
            $thisSection.find('.section-published-date').animate({
                'background-color': 'rgb(182,37,104)'
            }, 300).animate({
                    'background-color': '#edf1f5'
                }, 300).animate({
                    'background-color': 'rgb(182,37,104)'
                }, 300).animate({
                    'background-color': '#edf1f5'
                }, 300);

            hideModal();
        });
831
}