+/*jslint nomen: true*/
+/*global $, GraphSchedule, range, history, setTimeout */
+function UI() {
+ "use strict";
+}
+
+(function () {
+ "use strict";
+ UI.prototype = {
+ sentence : {
+ 'lazy' : {
+ text : 'He does not seem to me to be a free man who does not sometimes do nothing.',
+ signature : 'Marcus T. Cicero'
+ },
+ 'run' : {
+ text : 'A journey of a thousand miles begins with a single step.',
+ signature : 'Lao-tzu'
+ }
+ },
+ graphSchedule : null,
+ app : null
+ };
+
+ UI.prototype.fillExercises = function (exercisesData) {
+ var i, len, self = this;
+
+ $('#exercises').replaceWith(
+ $('<ul data-role="listview" id="exercises"></ul>')
+ );
+ for (i = 0, len = exercisesData.length; i < len; i += 1) {
+ $('#exercises').append(
+ $(this.getExercisesTemplate(exercisesData[i], i))
+ );
+ }
+ $('#exercises').listview();
+ $('#exercises :jqmData(role="slider")').slider();
+ $('#exercises li').on('click', function () {
+ var $toggle = $(this).find(':jqmData(role="slider")');
+ $toggle.val(($toggle.val() === 'off') ? 'on' : 'off');
+ $toggle.slider('refresh');
+ self.app.saveExercises(self.getExercisesList());
+ });
+ $('#exercises :jqmData(role="slider")').on('change', function (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ self.app.saveExercises(self.getExercisesList());
+ });
+ };
+
+ UI.prototype.popup = function (text, callback) {
+ var i, popup = $("#popup"),
+ buttons = {'Cancel': function () { $("#popup").popup('close') }};
+ // to hide default button give {'Cancel': false} in callback
+
+ for (i in callback) {
+ if (callback.hasOwnProperty(i)) {
+ buttons[i] = callback[i];
+ }
+ }
+
+ $(".ui-popup-button-bg", popup).empty();
+ for (i in buttons) {
+ if (buttons.hasOwnProperty(i)) {
+ if (buttons[i]) {
+ $('<a/>')
+ .text(i)
+ .attr({'data-role': 'button', 'data-inline': 'true'})
+ .bind('click', buttons[i])
+ .appendTo($(".ui-popup-button-bg", popup));
+ }
+ }
+ }
+ $(".text", popup).text(text);
+
+ popup.trigger("create");
+ popup.popup('open', {positionTo: 'window'});
+
+ // N_SE-49979 workaround to unlock forbidden keys
+ popup.one("popupafterclose", function () {
+ $(document).off('keydown');
+ });
+ };
+
+ UI.prototype.clearTabbars = function () {
+ $('[data-role = "tabbar"] li > a').removeClass('ui-focus, ui-btn-active');
+ };
+
+ UI.prototype.fillTimesRanges = function (timesData) {
+ var self = this, len, i;
+
+ $('#availableTime').replaceWith(
+ $('<ul data-role="listview" id="availableTime"></ul>')
+ );
+ for (i = 0, len = timesData.length; i < len; i += 1) {
+ $('#availableTime')
+ .append($(this.getAvailableTimeTemplate(timesData[i])));
+ }
+ $('#availableTime').trigger('create');
+ $('#availableTime').listview().listview('refresh');
+ $('#availableTime :jqmData(name=edit)').on('click', function (e) {
+ if (self.app.config.trainingEnabled) {
+ self.popup('You should stop the training first.');
+ } else {
+ e.preventDefault();
+ e.stopPropagation();
+ self.editTimeRange($(this).data('val'));
+ }
+ });
+ $('#availableTime :jqmData(name=disable)').on('click', function (e) {
+ if (self.app.config.trainingEnabled) {
+ self.popup('You should stop the training first.');
+ } else {
+ e.stopPropagation();
+ self.app.disableTimeRange($(this).data('val'));
+ }
+ });
+ $('#availableTime :jqmData(name=delete)').on('click', function (e) {
+ var value = $(this).data('val');
+ e.stopPropagation();
+ if (self.app.config.trainingEnabled) {
+ self.popup('You should stop the training first.');
+ return;
+ }
+ self.popup('Are you sure?', {
+ 'Delete': function () {
+ self.app.deleteTimeRange(value);
+ $("#popup").popup('close');
+ }
+ });
+ });
+ };
+
+ UI.prototype.fillTimeRangeForm = function fillTimeRangeForm(timeRange) {
+ var tmpData = new Date();
+ // Filling form;
+ $('#startTime').attr('data-val',
+ new Date(tmpData.setHours(timeRange.start)));
+ $('#duration').attr('data-val', timeRange.duration);
+
+ if ($('#startTime').data('datetimepicker')) {
+ $('#startTime').data('datetimepicker').options.date
+ .setHours(timeRange.start);
+ $('#startTime').data('datetimepicker').ui
+ .find('.ui-datefield-hour').html(
+ (timeRange.start < 10) ? '0' + timeRange.start : timeRange.start
+ );
+ }
+ if ($('#duration').data('datetimepicker')) {
+ $('#duration').data('datetimepicker').options.date
+ .setHours(timeRange.duration);
+ $('#duration').data('datetimepicker').ui.find('.ui-datefield-hour')
+ .html(
+ (timeRange.duration < 10) ? '0'
+ + timeRange.duration : timeRange.duration
+ );
+ $('#duration').data('datetimepicker')._populateDataSelector = function (field, pat) {
+ var result = $.tizen.datetimepicker.prototype._populateDataSelector
+ .call(this, field, pat);
+ result.values = range(1, 20);
+ result.data = range(1, 20);
+ result.current -= 1;
+ return result;
+ };
+ }
+ $.each($("input[name='periodType']"), function () {
+ $(this).attr('checked', $(this).val() === timeRange.style)
+ .checkboxradio('refresh');
+ });
+ $('#formEnablePeriod')[0].value = timeRange.enabled ? 'on' : 'off';
+ $('#formEnablePeriod').slider('refresh');
+ };
+
+ UI.prototype.editTimeRange = function (nr, event) {
+ if (event && typeof event.stopPropagation === 'function') {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ if (this.app.editTimeRange(nr) >= 0) {
+ $('#updateTime').val('modify');
+ $('#rangesOfTimes h1').text('Edit Time');
+ } else {
+ $('#updateTime').val('add');
+ $('#rangesOfTimes h1').text('Add Time');
+ }
+
+ // change page to form;
+ $.mobile.changePage("#rangesOfTimes");
+ };
+
+ UI.prototype.getExercisesList = function () {
+ return $('#exercises :jqmData(role=slider)').map(function (o, v) {
+ return ({
+ index : $(v).attr('data-index'),
+ checked : ($(v).val() === 'on') ? true : false
+ });
+ });
+ };
+
+ UI.prototype.addExercise = function () {
+ var trimmedName = $("#newExerciseName").val().trim();
+ trimmedName = $('<span>').text(trimmedName).html();
+ if (trimmedName !== '') {
+ if (this.app.addExercise(trimmedName)) {
+ $("#newExerciseName").trigger('blur');
+ setTimeout(history.back.bind(history), 50);
+ }
+ } else {
+ this.showErrors([ {
+ name : 'Name of exercise is not correct.',
+ code : 100
+ } ]);
+ }
+ };
+
+ UI.prototype.configToUI = function () {
+ };
+
+ UI.prototype.updateMainUI = function () {
+ this.setStatusRun(this.app.config.trainingEnabled);
+ this.graphSchedule.setTimeRanges(this.app.periodsWeekToBoolArray());
+ };
+
+ UI.prototype.getTimeRangeFromForm = function () {
+ return {
+ start : $('#startTime').data('datetimepicker').options.date
+ .getHours(),
+ duration : $('#duration').data('datetimepicker').options.date
+ .getHours(),
+ stop : $('#startTime').data('datetimepicker').options.date
+ .getHours()
+ + $('#duration').data('datetimepicker').options.date
+ .getHours(),
+ style : $('.selectPeriodType :radio:checked').val(),
+ enabled : ($('#formEnablePeriod')[0].value === 'on' ? true : false)
+ };
+ };
+
+ UI.prototype.editTimeRangeAction = function (nr) {
+ if (this.app.saveTimeRange(nr, this.getTimeRangeFromForm())) {
+ history.back();
+ } else {
+ throw ({
+ message : 'Time start and stop is not present.',
+ code : 1
+ });
+ }
+ };
+
+ UI.prototype.showNoticeInMonitor = function (notice, alarm) {
+ $('#communicate').html(notice);
+ $('#communicate').toggleClass('onAlert', alarm);
+ };
+
+ UI.prototype.changeButtonAddTime = function (text) {
+ $('#addTime').html(text);
+ };
+
+ UI.prototype.showErrors = function (errors) {
+ var i; // count;
+ for (i = 0; i < errors.length; i += 1) {
+ this.popup(errors[i].name);
+ }
+ this.unblockButtons();
+ };
+
+ UI.prototype.unblockButtons = function () {
+ $('#btnNewExercise').data('disabled', false);
+ };
+
+ UI.prototype.showAlarmInMonitor = function (data) {
+ var notice = '';
+ function formatNN(val) {
+ return (val < 10) ? ('0' + val) : val;
+ }
+
+ if (data && data.alarm && this.app.config.trainingEnabled) {
+ this.app.currentAlarm = this.app.findCurrentAlarm();
+ if (this.app.currentAlarm.length > 0) {
+ notice += 'Go... go... go...!<br>' + data.exerciseName + ' x '
+ + data.numberOfTimes;
+ } else {
+ notice += 'Next exercises set at: '
+ + formatNN(data.alarm.getHours()) + ':'
+ + formatNN(data.alarm.getMinutes()) + '<br>'
+ + data.exerciseName + ' x ' + data.numberOfTimes;
+ }
+ } else {
+ notice += '<br/>You have no workouts scheduled for now.<br/>';
+ }
+ this.showNoticeInMonitor(notice, false);
+ };
+
+ UI.prototype.getSentence = function UI_getSentence(type) {
+ return (this.sentence[type] || {
+ text : 'No sentence',
+ signature : 'anonymous'
+ });
+ };
+
+ UI.prototype.setSentence = function (type) {
+ var sentence = this.getSentence(type);
+ $('#sentence').html('"' + sentence.text + '"');
+ $('#signature').html('- ' + sentence.signature);
+ };
+
+ UI.prototype.showWaitOk = function () {
+ $('#mainControl').hide();
+ $('#one .ui-btn-back').hide();
+
+ $('#onAlertControl').tabbar();
+ $('#onAlertControl').show();
+ $('#onAlertControl').css('width', '');
+ };
+
+ UI.prototype.setStatusRun = function (bool) {
+ if (bool) {
+ // icon;
+ $('#status').removeClass('lazy').addClass('run');
+ // sentence;
+ this.setSentence('run');
+ // button in control bar;
+ $('#startStop .ui-btn-text').html('Stop Training');
+ } else {
+ $('#status').removeClass('run').addClass('lazy');
+ this.setSentence('lazy');
+ $('#communicate').html('');
+ $('#startStop .ui-btn-text').html('Start Training');
+ }
+ };
+
+ UI.prototype.bindEvents = function bindEvents() {
+ var self = this;
+
+ // bind events;
+ $("#popup").popup();
+
+ $('#one .ui-btn-back').on('click', this.app.exit.bind(this.app));
+
+ $('#ok').on('click', self.app.ok.bind(self.app));
+ $('#wait').on('click', self.app.wait.bind(self.app));
+ $('#todayOffAll').on('click', self.app.todayOffAll.bind(self.app));
+
+ $('[data-role = "tabbar"] li > a').on('click', function () {
+ self.clearTabbars();
+ });
+
+ $('#startStop').on('click', function () {
+ self.app.appStartStop();
+ });
+
+ window.addEventListener('tizenhwkey', function(e) {
+ if (e.keyName == 'back') {
+ if ($.mobile.popup.active) {
+ $.mobile.popup.active.close();
+ } else if ($.mobile.activePage.attr('id') === 'one') {
+ tizen.application.getCurrentApplication().exit();
+ } else {
+ history.back();
+ }
+ }
+ });
+
+ $('#one').on(
+ 'pageshow',
+ function (page, options) {
+ if (self.graphSchedule.ui) {
+ $('#one .schedule').append(self.graphSchedule.ui);
+ self.app.updateGraph();
+ self.graphSchedule.refresh();
+ self.graphSchedule.setVisibleWeekend(!self.app
+ .todayIsWorkday());
+ self.graphSchedule.setVisibleWorkdays(self.app
+ .todayIsWorkday());
+ }
+ $('#one .schedule').on('touchstart', function (ev) {
+ ev.stopPropagation();
+ });
+
+ // workaround for scroll lock;
+ $.mobile.activePage.css('position', 'fixed');
+
+ if ($('a.ui-btn-back').is(':hidden')) {
+ $('div#mainControl').removeClass('ui-tabbar-margin-back');
+ }
+ }
+ );
+
+ $('#two').on('pageshow', function (page, options) {
+ self.fixPageHeight('#two');
+
+ if (self.graphSchedule.ui) {
+ $('#two .scheduleOptions').append(self.graphSchedule.ui);
+ self.graphSchedule.refresh();
+ self.graphSchedule.setVisibleWeekend(true);
+ self.graphSchedule.setVisibleWorkdays(true);
+ }
+
+ if ($('a.ui-btn-back').is(':hidden')) {
+ $('div#selectExercisesBar').removeClass('ui-tabbar-margin-back');
+ }
+ });
+
+ $('#two').on('pageinit', function (page, options) {
+ $('.ui-radio input', $('#frequency')).change(function (ev) {
+ var that = this;
+ self.startProgress();
+ setTimeout(function (){
+ self.app.setFrequency(that.value);
+ self.updateMainUI();
+ self.endProgress();
+ }, 100);
+ });
+
+ $('.ui-radio input', $('#strength')).change(function (ev) {
+ self.app.setStrength(this.value);
+ self.updateMainUI();
+ });
+
+ $('#frequency')[0].select(self.app.config.frequency);
+ $('#strength')[0].select(self.app.config.strength);
+
+ $('#two .scheduleOptions').append(self.graphSchedule.ui);
+ $('#two .scheduleOptions').on('touchstart', function (ev) {
+ ev.stopPropagation();
+ });
+
+ $('#workdaysType').on('click', function (ev) {
+ var that = $(this).children("a");
+ setTimeout(function(){
+ that.removeClass("ui-btn-active");
+ }, 400);
+
+ self.app.changeTypeOfPeriods('workday');
+ });
+
+ $('#weekendType').on('click', function (ev) {
+ var that = $(this).children("a");
+ setTimeout(function(){
+ that.removeClass("ui-btn-active");
+ }, 400);
+
+ self.app.changeTypeOfPeriods('weekend');
+ });
+
+ $('#addTimeRange').on('click', function (e) {
+ if (self.app.config.trainingEnabled) {
+ self.popup('You should stop the training first.');
+ } else {
+ self.editTimeRange(-1, e);
+ }
+ });
+
+ self.app.updateTimesRanges();
+ self.configToUI();
+ });
+
+ $('#selectExercises').on('pageinit', function (page, options) {
+ self.app.updateExercises();
+ self.configToUI();
+ });
+
+ $('#selectExercises').on('pageshow', function (page, options) {
+ self.fixPageHeight('#selectExercises');
+ });
+
+ $('#customExercises').on('pageinit', function (page, options) {
+ $('#btnNewExercise').on('click', function (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ if ($(this).data('disabled') !== true) {
+ $(this).data('disabled', true);
+ self.addExercise();
+ }
+ });
+ });
+
+ $('#customExercises').on('pageshow', function (page, options) {
+ self.unblockButtons();
+
+ $('#newExerciseName').val('');
+ });
+
+ $('#rangesOfTimes').on('pageinit', function (page, options) {
+ $("#updateTime").on("click", function (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ self.startProgress('Saving');
+ self.editTimeRangeAction(self.app.currentEditingTimePeriodId);
+ });
+ });
+
+ $('#rangesOfTimes').on('pageshow', function (page, options) {
+ self.fixPageHeight('#rangesOfTimes');
+
+ $('#updateTime').data('button').refresh();
+ self.fillTimeRangeForm(self.app.currentEditingTimePeriod);
+ });
+
+ $('#increasingStrength').on('change', function () {
+ self.app.config.increasingStrength = this.checked;
+ self.app.saveConfig();
+
+ self.configToUI();
+ });
+
+ $('#add_custom_workout_btn').on('click', function (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ $.mobile.changePage('#customExercises');
+ });
+ };
+
+ UI.prototype.onGraphSchedule = function onGraphSchedule(onInitEnd) {
+ this.updateMainUI();
+
+ $('#one .schedule').append(this.graphSchedule.ui);
+ this.app.updateGraph();
+ this.graphSchedule.refresh();
+ this.graphSchedule.setVisibleWeekend(!this.app.todayIsWorkday());
+ this.graphSchedule.setVisibleWorkdays(this.app.todayIsWorkday());
+
+ if (typeof onInitEnd === 'function') {
+ onInitEnd();
+ }
+ };
+
+ UI.prototype.initialize = function (onInitEnd) {
+ $.mobile.tizen.disableSelection(document);
+
+ this.bindEvents();
+
+ $('html, body').css('font-size', '');
+ $('[data-role=footer]').height('');
+
+ this.graphSchedule = new GraphSchedule({
+ onSuccess : this.onGraphSchedule.bind(this, onInitEnd)
+ });
+
+ this.fixContentHeight();
+ };
+
+ UI.prototype.fixPageHeight = function (element) {
+ //FIXME (two scrollbar workaround)
+ setTimeout(
+ function () {
+ var newHeight = $(element).find('[data-role="content"]').prop('style').height;
+ $(element).css({'min-height': newHeight, 'height': newHeight});
+ },
+ 0
+ );
+ };
+
+ UI.prototype.fixContentHeight = function () {
+ var contentHeight = screen.availHeight - $('div[data-role="header"]').outerHeight() - $('div[data-role="footer"]').outerHeight();
+ $('div[data-role="content"]').css('height', contentHeight);
+ };
+
+ UI.prototype.startProgress = function (title) {
+ title = title || "Updating schedule";
+ $("#progress").show();
+ $("#progresstitle").text(title);
+ $("#progressbar").progressbar({value: false});
+ };
+
+ UI.prototype.endProgress = function () {
+ $("#progress").fadeOut();
+ };
+}());