jam-cloud/app/assets/javascripts/accounts_profile.js

346 lines
13 KiB
JavaScript

(function(context,$) {
"use strict";
context.JK = context.JK || {};
context.JK.AccountProfileScreen = function(app) {
var logger = context.JK.logger;
var api = context.JK.API(app);
var userId;
var user = {};
var recentUserDetail = null;
var loadingLocationData = false;
function beforeShow(data) {
userId = data.id;
}
function afterShow(data) {
resetForm();
renderAccountProfile();
}
function resetForm() {
// remove all display errors
$('#account-profile-content-scroller form .error-text').remove()
$('#account-profile-content-scroller form .error').removeClass("error")
}
function populateAccountProfile(userDetail, instruments) {
var template = context.JK.fillTemplate($('#template-account-profile').html(), {
country: userDetail.country,
region: userDetail.state,
first_name: userDetail.first_name,
last_name: userDetail.last_name,
user_instruments: userDetail.instruments,
birth_date : userDetail.birth_date,
gender: userDetail.gender
});
var content_root = $('#account-profile-content-scroller')
content_root.html(template);
// now use javascript to fix up values too hard to do with templating
// set gender
$('select[name=gender]', content_root).val(userDetail.gender)
// set birth_date
if(userDetail.birth_date) {
var birthDateFields = userDetail.birth_date.split('-')
var birthDateYear = birthDateFields[0];
var birthDateMonth = birthDateFields[1];
var birthDateDay = birthDateFields[2];
$('select#user_birth_date_1i', content_root).val(parseInt(birthDateYear));
$('select#user_birth_date_2i', content_root).val(parseInt(birthDateMonth));
$('select#user_birth_date_3i', content_root).val(parseInt(birthDateDay));
}
// update instruments
$.each(instruments, function(index, instrument) {
var template = context.JK.fillTemplate($('#account-profile-instrument').html(), {
checked : isUserInstrument(instrument, userDetail.instruments) ? "checked=\"checked\"" :"",
description : instrument.description,
id : instrument.id
})
$('.instrument_selector', content_root).append(template)
})
// and fill in the proficiency for the instruments that the user can play
$.each(userDetail.instruments, function(index, userInstrument) {
$('tr[data-instrument-id="' + userInstrument.instrument_id + '"] select.proficiency_selector', content_root).val(userInstrument.proficiency_level)
})
}
function isUserInstrument(instrument, userInstruments) {
var isUserInstrument = false;
$.each(userInstruments, function(index, userInstrument) {
if(instrument.id == userInstrument.instrument_id) {
isUserInstrument = true;
return false;
}
})
return isUserInstrument;
}
function populateAccountProfileLocation(userDetail, regions, cities) {
populateRegions(regions, userDetail.state);
populateCities(cities, userDetail.city);
}
function populateRegions(regions, userRegion) {
var regionSelect = getRegionElement()
regionSelect.children().remove()
$.each(regions, function(index, region) {
if(!region) return;
var option = $('<option></option>')
option.text(region)
option.attr("value", region)
regionSelect.append(option)
})
regionSelect.val(userRegion)
regionSelect.attr("disabled", null)
}
function populateCities(cities, userCity) {
var citySelect = getCityElement();
citySelect.children().remove()
$.each(cities, function(index, city) {
if(!city) return;
var option = $('<option></option>')
option.text(city)
option.attr("value", city)
citySelect.append(option)
})
citySelect.val(userCity)
citySelect.attr("disabled", null)
}
/****************** MAIN PORTION OF SCREEN *****************/
// events for main screen
function events() {
$('#account-profile-content-scroller').on('click', '#account-edit-profile-cancel', function(evt) { evt.stopPropagation(); navToAccount(); return false; } );
$('#account-profile-content-scroller').on('click', '#account-edit-profile-submit', function(evt) { evt.stopPropagation(); handleUpdateProfile(); return false; } );
$('#account-profile-content-scroller').on('submit', '#account-edit-email-form', function(evt) { evt.stopPropagation(); handleUpdateProfile(); return false; } );
$('#account-profile-content-scroller').on('change', 'select[name=region]', function(evt) { evt.stopPropagation(); handleRegionChanged(); return false; } );
}
function renderAccountProfile() {
$.when( api.getUserDetail(),
api.getInstruments())
.done(function(userDetailResponse, instrumentsResponse) {
var userDetail = userDetailResponse[0];
recentUserDetail = userDetail // store userDetail for later
var instruments = instrumentsResponse[0];
// show page; which can be done quickly at this point
populateAccountProfile(userDetail, instruments);
loadingLocationData = true;
// make the 3 slower requests, which only matter if the user wants to affect their ISP or location
$.when(
api.getRegions( { country: userDetail.country } ),
api.getCities( { country: userDetail.country, region: userDetail.state }))
.done(function(regionsResponse, citiesResponse) {
var regions = regionsResponse[0];
var cities = citiesResponse[0];
populateAccountProfileLocation(userDetail, regions["regions"], cities["cities"])
})
.fail(app.ajaxError)
.always(function() {loadingLocationData = false;})
})
.fail(app.ajaxError);
}
function navToAccount() {
resetForm();
window.location = '#/account';
}
function handleUpdateProfile() {
if (loadingLocationData) return;
resetForm();
var country = getCountryElement().val();
var region = getRegionElement().val();
var city = getCityElement().val();
var firstName = getFirstNameElement().val();
var lastName = getLastNameElement().val();
var gender = getGenderElement().val()
var birthDate = getBirthDate();
var instruments = getInstrumentsValue();
postUpdateProfile({
country: country,
state: region,
city: city,
first_name: firstName,
last_name: lastName,
gender: gender,
birth_date: birthDate,
instruments: instruments
})
.done(postUpdateProfileSuccess)
.fail(postUpdateProfileFailure)
}
function postUpdateProfile(options) {
var url = "/api/users/" + context.JK.currentUserId;
return $.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json',
url: url,
data: JSON.stringify(options),
processData: false
});
}
function postUpdateProfileSuccess(response) {
navToAccount();
}
function postUpdateProfileFailure(xhr, textStatus, errorMessage) {
var errors = JSON.parse(xhr.responseText)
if(xhr.status == 422) {
/**
var current_password_errors = context.JK.format_errors("current_password", errors)
var password_errors = context.JK.format_errors("password", errors)
var password_confirmation_errors = context.JK.format_errors("password_confirmation", errors)
if(current_password_errors != null) {
$('#account-edit-password-form #account-forgot-password').closest('div.field').addClass('error').end().after(current_password_errors);
}
if(password_errors != null) {
$('#account-edit-password-form input[name=password]').closest('div.field').addClass('error').end().after(password_errors);
}
if(password_confirmation_errors != null) {
$('#account-edit-password-form input[name=password_confirmation]').closest('div.field').addClass('error').end().after(password_confirmation_errors);
}
*/
}
else {
app.ajaxError(xhr, textStatus, errorMessage)
}
}
function handleRegionChanged() {
var selectedCountry = getCountryElement().val()
var selectedRegion = getRegionElement().val()
var cityElement = getCityElement();
// only update
if(selectedCountry && selectedRegion) {
// set city disabled while updating
cityElement.attr('disabled', true);
loadingLocationData = false;
cityElement.children().remove()
cityElement.append($('<option></option>').text('loading...'))
api.getCities( { country: selectedCountry, region: selectedRegion })
.done(getCitiesDone)
.fail(app.ajaxError)
.always(function() { loadingLocationData = false; })
}
}
function getCitiesDone(data) {
populateCities(data['cities'], recentUserDetail.city)
}
function getCountryElement() {
return $('#account-profile-content-scroller select[name=country]')
}
function getRegionElement() {
return $('#account-profile-content-scroller select[name=region]')
}
function getCityElement() {
return $('#account-profile-content-scroller select[name=city]')
}
function getFirstNameElement() {
return $('#account-profile-content-scroller input[name=first_name]')
}
function getLastNameElement() {
return $('#account-profile-content-scroller input[name=last_name]')
}
function getGenderElement() {
return $('#account-profile-content-scroller select[name=gender]')
}
function getBirthDate() {
var month = $('#account-profile-content-scroller select#user_birth_date_2i').val()
var day = $('#account-profile-content-scroller select#user_birth_date_3i').val()
var year = $('#account-profile-content-scroller select#user_birth_date_1i').val()
if(month != null && month.length > 0 && day != null && day.length > 0 && year != null && year.length > 0) {
return month + "-" + day + "-" + year;
}
else {
return null;
}
}
// looks in instrument_selector parent element, and gathers up all
// selected elements, and the proficiency level declared
function getInstrumentsValue() {
var instrumentsParentElement = $(".instrument_selector")
var instruments = []
$('input[type=checkbox]:checked', instrumentsParentElement).each(function(i) {
var instrumentElement = $(this).closest('tr');
// traverse up to common parent of this instrument, and pick out proficiency selector
var proficiency = $('select.proficiency_selector', instrumentElement).val()
instruments.push({
instrument_id: instrumentElement.attr('data-instrument-id'),
proficiency_level: proficiency,
priority : i
})
});
return instruments;
}
function initialize() {
var screenBindings = {
'beforeShow': beforeShow,
'afterShow': afterShow
};
app.bindScreen('account/profile', screenBindings);
events();
}
this.initialize = initialize;
this.beforeShow = beforeShow;
this.afterShow = afterShow;
return this;
};
})(window,jQuery);