(function (context, $) { "use strict"; context.JK = context.JK || {}; // TODO: MUCH OF THIS CLASS IS REPEATED IN THE FOLLOWING FILES: // createSession.js.erb // accounts_profiles.js context.JK.BandSetupScreen = function (app) { var logger = context.JK.logger; var rest = context.JK.Rest(); var inviteMusiciansUtil = null; var invitationDialog = null; var autoComplete = null; var userNames = []; var userIds = []; var userPhotoUrls = []; var selectedFriendIds = {}; var nilOptionStr = ''; var nilOptionText = 'n/a'; var bandId = ''; var friendInput=null; var step1, step2; var isSaving = false; function is_new_record() { return bandId.length == 0; } function removeErrors() { $('#band-setup-form .error-text').remove() $('#band-setup-form .error').removeClass("error") } function resetForm() { removeErrors(); // name $("#band-name").val(''); // country $("#band-country").empty(); $("#band-country").val(''); // region $("#band-region").empty(); $("#band-region").val(''); // city $("#band-city").empty(); $("#band-city").val(''); // description $("#band-biography").val(''); // website $('#band-website').val(''); resetGenres(); $("#band-setup-step-1").show(); $("#band-setup-step-2").hide(); $(friendInput) .unbind('blur') .attr("placeholder", "Looking up friends...") .prop('disabled', true) } function resetGenres() { $('input[type=checkbox]:checked', '#band-genres').each(function (i) { $(this).removeAttr("checked"); }); var $tdGenres = $("#tdBandGenres"); } function getSelectedGenres() { var genres = []; $('input[type=checkbox]:checked', '#band-genres').each(function (i) { var genre = $(this).val(); genres.push(genre); }); return genres; } function validateGeneralInfo() { removeErrors(); var band = buildBand(); return rest.validateBand(band); } function renderErrors(errors) { var name = context.JK.format_errors("name", errors); var country = context.JK.format_errors("country", errors); var state = context.JK.format_errors("state", errors); var city = context.JK.format_errors("city", errors); var biography = context.JK.format_errors("biography", errors); var genres = context.JK.format_errors("genres", errors); var website = context.JK.format_errors("website", errors); if(name) $("#band-name").closest('div.field').addClass('error').end().after(name); if(country) $("#band-country").closest('div.field').addClass('error').end().after(country); if(state) $("#band-region").closest('div.field').addClass('error').end().after(state); if(city) $("#band-city").closest('div.field').addClass('error').end().after(city); if(genres) $(".band-setup-genres").closest('div.field').addClass('error').end().after(genres); if(biography) $("#band-biography").closest('div.field').addClass('error').end().after(biography); if(website) $("#band-website").closest('div.field').addClass('error').end().after(website); } function buildBand() { var band = {}; band.name = $("#band-name").val(); band.website = $("#band-website").val(); band.biography = $("#band-biography").val(); band.city = $("#band-city").val(); band.state = $("#band-region").val(); band.country = $("#band-country").val(); band.genres = getSelectedGenres(); return band; } function showProfile(band_id) { context.location = "/client#/bandProfile/" + band_id; } function saveBand() { if (isSaving) return; isSaving = true; var band = buildBand() if (is_new_record()) { rest.createBand(band) .done(function (response) { isSaving = false; if (0 < $('#selected-friends-band .invitation').length) { createBandInvitations(response.id, function () { showProfile(response.id); }); } else showProfile(response.id); }) .fail(function (jqXHR) { isSaving = false; app.notifyServerError(jqXHR, "Unable to create band") }); ; } else { band.id = bandId; if (!step1 && !step2){ rest.updateBand(band) .done(function (response) { isSaving = false; createBandInvitations(band.id, function () { showProfile(band.id); }); }).fail(function (jqXHR) { isSaving = false; app.notifyServerError(jqXHR, "Unable to create band") }); } else { if (step1) { rest.updateBand(band) .done(function (response) { isSaving = false; app.notifyAlert('Band Information', 'Your changes have been saved'); }).fail(function (jqXHR) { isSaving = false; app.notifyServerError(jqXHR, "Unable to update band") }); } else if (step2) { isSaving = false; if (0 < $('#selected-friends-band .invitation').length) { createBandInvitations(bandId, function () { app.notifyAlert('Band Members', 'Your invitations have been sent'); showProfile(bandId); }); } else showProfile(bandId); } } } } function createBandInvitations(bandId, onComplete) { var callCount = 0; var totalInvitations = 0; $('#selected-friends-band .invitation').each(function (index, invitation) { callCount++; totalInvitations++; var userId = $(invitation).attr('user-id'); rest.createBandInvitation(bandId, userId) .done(function (response) { callCount--; }).fail(app.ajaxError); }); function checker() { if (callCount === 0) { onComplete(); } else { context.setTimeout(checker, 10); } } checker(); return totalInvitations; } function beforeShow(data) { inviteMusiciansUtil.clearSelections(); bandId = data.id == 'new' ? '' : data.id; step1 = step2 = false; if ('step2'==data['d']) { step2 = true; delete data['d']; } else if ('step1'==data['d']){ step1 = true; delete data['d']; } resetForm(); } function afterShow(data) { inviteMusiciansUtil.loadFriends(); if (!is_new_record()) { $("#band-setup-title").html("edit band"); $("#btn-band-setup-save").html("SAVE CHANGES"); $("#band-change-photo").html('Upload band photo.'); $('#tdBandPhoto').css('visibility', 'visible'); // retrieve and initialize band profile data points loadBandDetails(); if (step2) { $("#band-setup-step-2").show(); $("#band-setup-step-1").hide(); $('.band-setup-text-step2').each(function(idx) { $(this).hide(); }); $('#btn-band-setup-back').text('CANCEL'); $('#btn-band-setup-save').text('SEND INVITATIONS'); } else if (step1) { $("#band-setup-step-1").show(); $("#band-setup-step-2").hide(); $('.band-setup-text-step1').each(function(idx) { $(this).hide(); }); $('#btn-band-setup-next').text('SAVE'); } if (! step1 && ! step2) { $('#btn-band-setup-next').text('NEXT'); $('#btn-band-setup-back').text('CANCEL'); $('#btn-band-setup-save').text('CREATE BAND'); $('.band-setup-text-step1').each(function(idx) { $(this).show(); }); $('.band-setup-text-step2').each(function(idx) { $(this).show(); }); } } else { loadGenres(); rest.getResolvedLocation() .done(function (location) { loadCountries(location.country, function () { loadRegions(location.region, function () { loadCities(location.city); }); }); }); $("#band-setup-title").html("set up band"); $("#btn-band-setup-save").html("CREATE BAND"); $('#tdBandPhoto').css('visibility', 'hidden'); // can't upload photo when going through initial setup } } function loadBandDetails() { rest.getBand(bandId).done(function (band) { $("#band-name").val(band.name); $("#band-website").val(band.website); $("#band-biography").val(band.biography); if (band.photo_url) { $("#band-avatar").attr('src', band.photo_url); } loadGenres(band.genres); loadCountries(band.country, function () { loadRegions(band.state, function () { loadCities(band.city); }); }); // TODO: initialize avatar }); } function loadGenres(selectedGenres) { $("#band-genres").empty(); rest.getGenres().done(function (genres) { $.each(genres, function (index, genre) { var genreTemplate = $('#template-band-setup-genres').html(); var selected = ''; if (selectedGenres) { var genreMatch = $.grep(selectedGenres, function (n, i) { return n.id === genre.id; }); if (genreMatch.length > 0) { selected = "checked"; } } var genreHtml = context.JK.fillTemplate(genreTemplate, { id: genre.id, description: genre.description, checked: selected }); $('#band-genres').append(genreHtml); }); }); } function loadCountries(initialCountry, onCountriesLoaded) { var countrySelect = $("#band-country"); var nilOption = $(nilOptionStr); nilOption.text(nilOptionText); countrySelect.append(nilOption); rest.getCountries().done(function (response) { $.each(response["countriesx"], function (index, countryx) { if (!countryx.countrycode) return; var option = $(nilOptionStr); option.text(countryx.countryname); option.attr("value", countryx.countrycode); if (initialCountry === countryx.countrycode) { option.attr("selected", "selected"); } countrySelect.append(option); }); context.JK.dropdown(countrySelect); if (onCountriesLoaded) { onCountriesLoaded(); } }); } function loadRegions(initialRegion, onRegionsLoaded) { var $region = $("#band-region"); $region.empty(); var selectedCountry = $("#band-country").val(); var nilOption = $(nilOptionStr); nilOption.text(nilOptionText); $region.append(nilOption); if (selectedCountry) { rest.getRegions({'country': selectedCountry}).done(function (response) { $.each(response["regions"], function (index, region) { if (!region) return; var option = $(nilOptionStr); option.text(region['name']); option.attr("value", region['region']); if (initialRegion === region['region']) { option.attr("selected", "selected"); } $region.append(option); }); context.JK.dropdown($region); if (onRegionsLoaded) { onRegionsLoaded(); } }).error(function(err) { context.JK.dropdown($region); if (onRegionsLoaded) { onRegionsLoaded(); } }); } } function loadCities(initialCity) { var $city = $("#band-city"); $city.empty(); var selectedCountry = $("#band-country").val(); var selectedRegion = $("#band-region").val(); var nilOption = $(nilOptionStr); nilOption.text(nilOptionText); $city.append(nilOption); nilOption.attr('selected','selected'); if (selectedCountry && selectedRegion) { rest.getCities({'country': selectedCountry, 'region': selectedRegion}).done(function (response) { $.each(response["cities"], function (index, city) { if (!city) return; var option = $(nilOptionStr); option.text(city); option.attr("value", city); if (initialCity === city) { option.attr("selected", "selected"); } $city.append(option); }); context.JK.dropdown($city); }).error(function(err) { context.JK.dropdown($city); }); } else { context.JK.dropdown($city); } } function addInvitation(value, data) { if ($('#selected-band-invitees div[user-id=' + data + ']').length === 0) { var template = $('#template-band-invitation').html(); var invitationHtml = context.JK.fillTemplate(template, {userId: data, userName: value}); $('#selected-band-invitees').append(invitationHtml); $('#band-invitee-input').select(); selectedFriendIds[data] = true; } else { $('#band-invitee-input').select(); context.alert('Invitation already exists for this musician.'); } } function navigateToBandPhoto(evt) { evt.stopPropagation(); context.location = '/client#/band/setup/photo/' + bandId; return false; } function removeInvitation(evt) { delete selectedFriendIds[$(evt.currentTarget).parent().attr('user-id')]; $(evt.currentTarget).closest('.invitation').remove(); } function events() { $('#selected-band-invitees').on("click", ".invitation a", removeInvitation); // friend input focus $('#band-invitee-input').focus(function () { $(this).val(''); }); $('#btn-band-setup-cancel').click(function () { resetForm(); window.history.go(-1); return false; }); $('#btn-band-setup-next').click(function () { validateGeneralInfo() .done(function (response) { if (!step1 && !step2) { $("#band-setup-step-2").show(); $("#band-setup-step-1").hide(); } else if (step1) { saveBand(); } }) .fail(function (jqXHR) { if(jqXHR.status == 422) { renderErrors(JSON.parse(jqXHR.responseText)) } else { app.notifyServerError(jqXHR, "Unable to validate band") } }); }); $('#btn-band-setup-back').click(function () { if (!step2) { $("#band-setup-step-1").show(); $("#band-setup-step-2").hide(); } else { showProfile(bandId); return false; } }); $('#btn-band-setup-save').click(saveBand); $('#band-country').on('change', function (evt) { evt.stopPropagation(); loadRegions(); loadCities(); return false; }); $('#band-region').on('change', function (evt) { evt.stopPropagation(); loadCities(); return false; }); $('#band-change-photo').click(navigateToBandPhoto); $('#band-setup .avatar-profile').click(navigateToBandPhoto); $('div[layout-id="band/setup"] .btn-email-invitation').click(function () { invitationDialog.showEmailDialog(); }); $('div[layout-id="band/setup"] .btn-gmail-invitation').click(function () { invitationDialog.showGoogleDialog(); }); $('div[layout-id="band/setup"] .btn-facebook-invitation').click(function () { invitationDialog.showFacebookDialog(); }); $(friendInput).focus(function() { $(this).val(''); }) } function initialize(invitationDialogInstance, friendSelectorDialog) { inviteMusiciansUtil = new JK.InviteMusiciansUtil(app); inviteMusiciansUtil.initialize(friendSelectorDialog); friendInput = inviteMusiciansUtil.inviteBandCreate('#band-setup-invite-musicians', "