
var adminCustomSeriesGrid;

function createAdminCustomSeriesGrid (myData, divId)
{
    var store = new Ext.data.Store(
        {
            reader: new Ext.data.ArrayReader({},
                [
                    {name: 'series_id'},
                    {name: 'series_title', type: 'string'},
                    {name: 'series_url'},
                    {name: 'isNew'},
                    {name: 'isHidden'},
                    {name: 'isDeleted'}
                ]
            ),
            sortInfo: { field: 'series_title' }
        }
    );

    store.loadData(myData);

    var icon = ALBase.make_static_uri('/icons/famfamfam/silk/bin_closed.png');

    adminCustomSeriesGrid = new Ext.grid.GridPanel(
        {
            store: store,

            columns: [
                {
                    id:        'series_title',
                    dataIndex: 'series_title',
                    header:    'Series Title',
                    renderer:  renderSeriesTitle,
                    width:     159,
                    sortable:  true
                },
                {
                    id:        'isHidden',
                    dataIndex: 'isHidden',
                    header:    'Hide/Show',
                    renderer:  renderAdminHideShowSeries,
                    width:     85,
                    align:     'center',
                    fixed:     true,
                    sortable:  true
                },
                {
                    id:        'series_id',
                    dataIndex: 'series_id',
                    header:    '<img src="' + icon + '" alt="remove" />',
                    renderer:  renderSeriesDelete,
                    width:     30,
                    align:     'center',
                    fixed:     true,
                    sortable:  false
                }
            ],

            view: new Ext.grid.GridView(
                {
                    autoFill:           true,
                    deferEmptyText:     false,
                    emptyText:          'No custom training is defined',
                    startCollapsed:     false
                }
            ),

            autoExpandColumn: 'series_title',
            autoHeight:       false,
            height:           350,
            enableColumnHide: false,
            enableColumnMove: false,
            enableHdMenu:     false,
            collapsible:      false,
            iconCls:          'icon-grid',
            stripeRows:       true,
            width:            295
        }
    );

    adminCustomSeriesGrid.render(divId);
}

//----------------------------------------------------------

function custom_content_series_edit (form)
{
    var seriesId = $(form.series_id).getValue();
    if (seriesId == null || seriesId == 0 || seriesId == '0')
    {
        genericError('Missing series ID.');
        return false;
    }

    var applicationId = $(form.application_id).getValue();
    if (applicationId == null || applicationId == 0 || applicationId == '0')
    {
        alert('Please select one or more Applications.');
        return false;
    }

    var typeId = $(form.type_id).getValue();
    if (typeId == null || typeId == 0 || typeId == '0')
    {
        alert('Please select one or more Types.');
        return false;
    }

    var platformId = $(form.platform_id).getValue();
    if (platformId == null || platformId == 0 || platformId == '0')
    {
        alert('Please select one or more Platforms.');
        return false;
    }

    makeAjaxRequest(
        {
            url: '/admin/customseries/edit',
            parameters: {
                series_id:      seriesId,
                application_id: applicationId,
                type_id:        typeId,
                platform_id:    platformId
            },
            onSuccess: function () {
                al_alert('The new series information was saved.');
            },
            failureMessage: 'The attempt to edit the series failed'
        }
    );

    return false;
}

function custom_content_section_add (form)
{
    var seriesId = $(form.series_id).getValue();
    if (seriesId == null || seriesId == 0 || seriesId == '0')
    {
        genericError('Missing series ID.');
        return;
    }

    var sectionName = $(form.section_name).getValue().strip();
    if (sectionName.length == 0)
    {
        alert('Please enter a section name.');
        return;
    }

    var langId = $(form.lang_id).getValue();
    if (langId == null || langId == 0 || langId == '0')
    {
        alert('Please select a language.');
        return;
    }

    makeAjaxRequest(
        {
            url: '/admin/customseries/addsection',
            parameters: {
                series_id:    seriesId,
                section_name: sectionName,
                lang_id:      langId
            },
            onSuccess: function () {
                fb.loadPageOnClose = 'self';    // will reload current page
                fb.end();                       // close floatbox
            },
            failureMessage: 'The attempt to create a new section failed'
        }
    );
}

function custom_content_movie_check (form)
{
    var sectionId = $(form.section_id).getValue();
    if (sectionId == null || sectionId == 0 || sectionId == '0')
    {
        genericError('Missing section ID.');
        return false;
    }

    // $(form element).getValue() does not work for radio buttons...
    var assetType = $$('input[type=radio][name="asset_type"]:checked').first().value;
    if (typeof assetType == 'undefined' || assetType.length == 0)
    {
        genericError('Missing asset type.');
        return false;
    }

    var movieName = $(form.movie_name).getValue().strip();
    if (movieName.length == 0)
    {
        alert('Please enter a tutorial name.');
        return false;
    }

    if (assetType == 'movie') {
        var movieFile = $(form.movie_file).getValue().strip();
        if (movieFile.length == 0)
        {
            alert('Please select a video or audio file.');
            return false;
        }
    }
    else if (assetType == 'document') {
        var documentFile = $(form.document_file).getValue().strip();
        if (documentFile.length == 0)
        {
            alert('Please select a document file.');
            return false;
        }
    }
    else if (assetType == 'url') {
        var url = $(form.url).getValue().strip();
        if (url.length == 0)
        {
            alert('Please enter a tutorial URL.');
            return false;
        }
        var regex = new RegExp('^https?://[A-Za-z0-9]');
        if (regex.test(url) == false) {
            alert('Please enter a tutorial URL that starts with'
                + ' "http://" or "https://".');
            return false;
        }
    }
    else {
        genericError('Invalid asset type.');
        return false;
    }

    var langId = $(form.lang_id).getValue();
    if (langId == null || langId == 0 || langId == '0')
    {
        alert('Please select a language.');
        return false;
    }

    if (assetType != 'url') {
        startProgressMask({
                           message: 'Uploading file, please wait...',
                           initialExpireSeconds: 45
                          });
    }
    return true;
}

//----------------------------------------------------------

function custom_content_edit_author (form)
{
    var seriesId = $(form.series_id).getValue();
    if (seriesId == null || seriesId == 0 || seriesId == '0')
    {
        genericError('Missing series ID.');
        return;
    }

    var author = $(form.author).getValue().strip();
    if (author == null || author == '')
    {
        if (!confirm('Are you sure you want an empty series author?')) {
            return false;
        }
    }

    editMetadataAjaxRequest(seriesId, 'author', author, 'series_author');
}

function custom_content_edit_description (form)
{
    var seriesId = $(form.series_id).getValue();
    if (seriesId == null || seriesId == 0 || seriesId == '0')
    {
        genericError('Missing series ID.');
        return;
    }

    var description = $(form.description).getValue().strip();
    if (description == null || description == '')
    {
        alert('Please enter a description.');
        return false;
    }

    editMetadataAjaxRequest(seriesId, 'description', description, 'blurb');
}

function custom_content_edit_footer (form)
{
    var seriesId = $(form.series_id).getValue();
    if (seriesId == null || seriesId == 0 || seriesId == '0')
    {
        genericError('Missing series ID.');
        return;
    }

    var footer = $(form.footer).getValue().strip();
    if (footer == null || footer == '')
    {
        if (!confirm('Are you sure you want an empty series footer?')) {
            return false;
        }
    }

    editMetadataAjaxRequest(seriesId, 'footer', footer, 'series_footer');
}

function custom_content_edit_title (form)
{
    var seriesId = $(form.series_id).getValue();
    if (seriesId == null || seriesId == 0 || seriesId == '0')
    {
        genericError('Missing series ID.');
        return;
    }

    var title = $(form.title).getValue().strip();
    if (title == null || title == '')
    {
        alert('Please enter a title.');
        return false;
    }

    editMetadataAjaxRequest(seriesId, 'title', title, 'series_title');
}

function editMetadataAjaxRequest (seriesId, field, value, divId)
{
    var parameters = {
            series_id: seriesId
    };
    parameters[field] = value;

    makeAjaxRequest(
        {
            url: '/admin/customseries/edit' + field,
            parameters: parameters,
            onSuccess: function (json) {
                var value = json[field];
                if (field == 'author') {
                    if (value) {
                        value = 'Tutorial series by ' + value;
                    }
                    else {
                        value = '<i>(This series has no author information)</i>';
                    }
                }
                if (field == 'footer') {
                    if (! value) {
                        value = '<i>(This series has no footer information)</i>';
                    }
                }
                var myDiv = $(parent.document.getElementById(divId));
                if (myDiv) {
                    myDiv.innerHTML = value;
                    myDiv.addClassName('newly_created');
                }
                parent.removeNewlyCreatedAfterDelay();
                fb.end();                       // close floatbox
            },
            failureMessage: 'The attempt to edit the ' + field + ' failed'
        }
    );
}

//----------------------------------------------------------

function custom_content_edit_section_name (form)
{
    var seriesId = $(form.series_id).getValue();
    if (seriesId == null || seriesId == 0 || seriesId == '0')
    {
        genericError('Missing series ID.');
        return;
    }

    var sectionId = $(form.section_id).getValue();
    if (sectionId == null || sectionId == 0 || sectionId == '0')
    {
        genericError('Missing section ID.');
        return;
    }

    var name = $(form.name).getValue().strip();
    if (name == null || name == '')
    {
        alert('Please enter a section name.');
        return false;
    }

    var divId = 'section_name_' + sectionId;

    editSectionMetadataAjaxRequest(seriesId, sectionId, 'name', name, divId);
}

function editSectionMetadataAjaxRequest (seriesId, sectionId, field, value, divId)
{
    var parameters = {
            series_id:  seriesId,
            section_id: sectionId
    };
    parameters[field] = value;

    var callback;
    if (field == 'name') {
        callback = function (value) {
            var myDiv = $(parent.document.getElementById(divId));
            if (myDiv) {
                myDiv.innerHTML = value;
                myDiv.addClassName('newly_created_dark');
            }
            parent.removeNewlyCreatedAfterDelay();
            myDiv = $(parent.document.getElementById(divId + '_add_movie'));
            if (myDiv) {
                myDiv.innerHTML = value;
            }
        };
    }
    else {
        callback = function (value) {
            var myDiv = $(parent.document.getElementById(divId));
            if (myDiv) {
                myDiv.innerHTML = value;
                myDiv.addClassName('newly_created');
            }
            parent.removeNewlyCreatedAfterDelay();
        };
    }

    makeAjaxRequest(
        {
            url: '/admin/customseries/editsection' + field,
            parameters: parameters,
            onSuccess: function (json) {
                var value = json[field];
                callback(value);
                fb.end();                       // close floatbox
            },
            failureMessage: 'The attempt to edit the ' + field + ' failed'
        }
    );
}

//----------------------------------------------------------

function custom_content_edit_movie_title (form)
{
    var sectionId = $(form.section_id).getValue();
    if (sectionId == null || sectionId == 0 || sectionId == '0')
    {
        genericError('Missing section ID.');
        return;
    }

    var movieId = $(form.movie_id).getValue();
    if (movieId == null || movieId == 0 || movieId == '0')
    {
        genericError('Missing movie ID.');
        return;
    }

    var title = $(form.title).getValue().strip();
    if (title == null || title == '')
    {
        alert('Please enter a tutorial title.');
        return false;
    }

    var divId = 'movie_name_' + movieId;

    editMovieMetadataAjaxRequest(sectionId, movieId, 'title', title, divId);
}

function editMovieMetadataAjaxRequest (sectionId, movieId, field, value, divId)
{
    var parameters = {
            section_id: sectionId,
            movie_id:   movieId
    };
    parameters[field] = value;

    var newClass;
    if (field == 'name') {
        newClass = 'newly_created_dark';
    }
    else {
        newClass = 'newly_created';
    }

    var callback = function (value) {
        var myDiv = $(parent.document.getElementById(divId));
        if (myDiv) {
            myDiv.innerHTML = value;
            myDiv.addClassName(newClass);
        }
        parent.removeNewlyCreatedAfterDelay();
    };

    makeAjaxRequest(
        {
            url: '/admin/customseries/editmovie' + field,
            parameters: parameters,
            onSuccess: function (json) {
                var value = json[field];
                callback(value);
                fb.end();                       // close floatbox
            },
            failureMessage: 'The attempt to edit the ' + field + ' failed'
        }
    );
}

//----------------------------------------------------------

function custom_series_hide_show (series_id, action, series_title)
{
    series_title = series_title.replace(/%22/g, '"');

    var confirmMsg;
    var newIsHidden;
    if (action == 'hide') {
        confirmMsg = 'The series "' + series_title + '" is currently included in search and browse results.\r\n\r\nAre you sure you want to hide it from search and browse results?  (You can show it again later if you would like.)';
        newIsHidden = 1;
    }
    else {
        confirmMsg = 'The series "' + series_title + '" is currently hidden from search and browse results.\r\n\r\nAre you sure you want to include it in search and browse results?';
        newIsHidden = 0;
    }

    if (! confirm(confirmMsg)) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/toggleserieshidden/' + action,
            parameters: {
                series_id: series_id
            },
            onSuccess: function (json) {
                // Calling "reload" turns out to be a problem if
                // the page was due to a POST, since it will re-post
                // when the relaod happens.  So just set the location:
                //
                //window.location.reload();
                var myHref = window.location.href;
                window.location.href = myHref;
            },
            failureMessage: 'The attempt to modify the series failed'
        }
    );
}

function custom_series_delete (series_id, series_title)
{
    series_title = series_title.replace(/%22/g, '"').replace(/%27/g, "'");

    var confirmMsg = 'You are about to permanently delete the custom training series "' + series_title + '", as well as all the training resources it may contain (movies, documents, and URLs).\r\n\r\nThis will remove any access to these items for all users.  This action cannot be undone.\r\n\r\nAre you sure you want to delete it?';

    if (! confirm(confirmMsg)) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/deleteseries',
            parameters: {
                series_id: series_id
            },
            onSuccess: function (json) {
                // Calling "reload" turns out to be a problem if
                // the page was due to a POST, since it will re-post
                // when the relaod happens.  So just set the location:
                //
                //window.location.reload();
                var myHref = window.location.href;
                window.location.href = myHref;
            },
            failureMessage: 'The attempt to delete the series failed'
        }
    );
}

//----------------------------------------------------------

function custom_movie_hide_show (movie_id, section_id, action, movie_title)
{
    movie_title = movie_title.replace(/%22/g, '"').replace(/%27/g, "'");

    var confirmMsg;
    var newIsHidden;
    if (action == 'hide') {
        confirmMsg = 'The movie "' + movie_title + '" is currently visible in this training series.\r\n\r\nAre you sure you want to hide it?  (You can show it again later if you would like.)';
        newIsHidden = 1;
    }
    else {
        confirmMsg = 'The movie "' + movie_title + '" is currently hidden in this training series.\r\n\r\nAre you sure you want to make it visible?';
        newIsHidden = 0;
    }

    if (! confirm(confirmMsg)) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/togglemoviehidden/' + action,
            parameters: {
                section_id: section_id,
                movie_id: movie_id
            },
            onSuccess: function (json) {
                // Calling "reload" turns out to be a problem if
                // the page was due to a POST, since it will re-post
                // when the relaod happens.  So just set the location:
                //
                //window.location.reload();
                var myHref = window.location.href;
                window.location.href = myHref;
            },
            failureMessage: 'The attempt to modify the movie failed'
        }
    );
}

function custom_movie_delete (movie_id, section_id, movie_title)
{
    movie_title = movie_title.replace(/%22/g, '"').replace(/%27/g, "'");

    var confirmMsg = 'You are about to permanently delete the custom training resource "' + movie_title + '".\r\n\r\nThis will remove any access to this item for all users.  This action cannot be undone.\r\n\r\nAre you sure you want to delete it?';

    if (! confirm(confirmMsg)) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/deletemovie',
            parameters: {
                section_id: section_id,
                movie_id: movie_id
            },
            onSuccess: function (json) {
                // Calling "reload" turns out to be a problem if
                // the page was due to a POST, since it will re-post
                // when the relaod happens.  So just set the location:
                //
                //window.location.reload();
                var myHref = window.location.href;
                window.location.href = myHref;
            },
            failureMessage: 'The attempt to delete the movie failed'
        }
    );
}

//----------------------------------------------------------

function _custom_content_section_reorder (direction, event)
{
    var el = event.element();
    event.stop();    // do not let clicks hit the section header

    var seriesId  = $(el).readAttribute('data-series-id');
    var sectionId = $(el).readAttribute('data-section-id');

    var sectionName = $('section_name_' + sectionId).innerHTML;
    sectionName = sectionName.replace(/^[^.]*[.][ ]*/, ''); // strip e.g. "A. "

    var confirmMsg = 'Move section "' + sectionName + '" ';
    if (direction == 'up') {
        confirmMsg += 'above the previous section?';
    }
    else {
        confirmMsg += 'below the next section?';
    }
    if (! confirm(confirmMsg)) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/sectionreorder',
            parameters: {
                series_id:  seriesId,
                section_id: sectionId,
                direction:  direction
            },
            onSuccess: function () {
                window.location.reload();
            },
            failureMessage: 'The attempt to reorder the sections failed'
        }
    );
}

function _custom_content_movie_reorder (direction, event)
{
    var el = event.element();
    event.stop();    // do not let clicks hit other handlers

    var seriesId  = $(el).readAttribute('data-series-id');
    var sectionId = $(el).readAttribute('data-section-id');
    var movieId   = $(el).readAttribute('data-movie-id');

    var movieName = $('movie_name_' + movieId).innerHTML;

    var confirmMsg = 'Move tutorial "' + movieName + '" ';
    if (direction == 'up') {
        confirmMsg += 'above the previous tutorial?';
    }
    else {
        confirmMsg += 'below the next tutorial?';
    }
    if (! confirm(confirmMsg)) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/moviereorder',
            parameters: {
                series_id:  seriesId,
                section_id: sectionId,
                movie_id:   movieId,
                direction:  direction
            },
            onSuccess: function () {
                window.location.reload();
            },
            failureMessage: 'The attempt to reorder the movies failed'
        }
    );
}

function custom_content_section_up (event)
{
    _custom_content_section_reorder('up', event);
}

function custom_content_section_down (event)
{
    _custom_content_section_reorder('down', event);
}

function custom_content_movie_up (event)
{
    _custom_content_movie_reorder('up', event);
}

function custom_content_movie_down (event)
{
    _custom_content_movie_reorder('down', event);
}

// The up and down arrows to reorder sections sit on top of the
// section headers.  If we handled them using onclick="...",
// the click also expands/collapses the headers.  So instead we
// register click events on the arrows, so that we can cancel
// the default event when finished.

Ext.onReady(function ()
    {
        $$('.custom_section_reorder_up').each( function (uparrow)
            {
                $(uparrow).observe('click', custom_content_section_up);
            }
        );
        $$('.custom_section_reorder_down').each( function (downarrow)
            {
                $(downarrow).observe('click', custom_content_section_down);
            }
        );
        $$('.custom_movie_reorder_up').each( function (uparrow)
            {
                $(uparrow).observe('click', custom_content_movie_up);
            }
        );
        $$('.custom_movie_reorder_down').each( function (downarrow)
            {
                $(downarrow).observe('click', custom_content_movie_down);
            }
        );
    }
);

//----------------------------------------------------------

function custom_content_add_application (form)
{
    var app = $(form.app_name).getValue().strip();
    if (app.length == 0)
    {
        alert('Please enter an application Name.');
        return;
    }

    var version = $(form.version).getValue().strip();
    if (version.length == 0)
    {
        if (!confirm('Are you sure you want an empty Application version?')) {
            return false;
        }
    }

    var confirmMsg;
    if (version) {
        confirmMsg = 'Are you sure you want to create a new Application named '
                   + '"' + app + '" with version "' + version + '"?';
    }
    else {
        confirmMsg = 'Are you sure you want to create a new Application named '
                   + '"' + app + '" with no version?';
    }
    if (! confirm(confirmMsg)) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/addcustomapplication',
            parameters: {
                app:     app,
                version: version
            },
            onSuccess: function (json) {
                if (json.alreadyExists) {
                    alert('That combination of application name and version already exists.');
                }
                else {
                    fb.loadPageOnClose = 'self';    // will reload current page
                    fb.end();                       // close floatbox
                }
            },
            failureMessage: 'The attempt to add a custom application failed'
        }
    );
}

function custom_content_add_platform (form)
{
    var name = $(form.platform_name).getValue().strip();
    if (name.length == 0)
    {
        alert('Please enter a Platform name.');
        return;
    }

    if (! confirm('Are you sure you want to create a new Platform named '
                 + '"' + name + '"?')) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/addcustomplatform',
            parameters: {
                name: name
            },
            onSuccess: function (json) {
                if (json.alreadyExists) {
                    alert('That platform already exists.');
                }
                else {
                    fb.loadPageOnClose = 'self';    // will reload current page
                    fb.end();                       // close floatbox
                }
            },
            failureMessage: 'The attempt to add a custom platform failed'
        }
    );
}

function custom_content_add_type (form)
{
    var name = $(form.type_name).getValue().strip();
    if (name.length == 0)
    {
        alert('Please enter a Type name.');
        return;
    }

    if (! confirm('Are you sure you want to create a new Type named '
                 + '"' + name + '"?')) return;

    makeAjaxRequest(
        {
            url: '/admin/customseries/addcustomtype',
            parameters: {
                name: name
            },
            onSuccess: function (json) {
                if (json.alreadyExists) {
                    alert('That type already exists.');
                }
                else {
                    fb.loadPageOnClose = 'self';    // will reload current page
                    fb.end();                       // close floatbox
                }
            },
            failureMessage: 'The attempt to add a custom type failed'
        }
    );
}

