/*
 * Copyright (c) 2012 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*jslint devel: true*/
/*global $, app, document, history, tizen, TemplateManager, window, tau*/

/**
 * @class Ui
 */

function Ui() {
    'use strict';
    return false;
}

(function strict() { // strict mode wrapper
    'use strict';
    Ui.prototype = {

        templateManager: null,

        /**
         * UI module initialisation.
         */
        init: function UI_init(app, exerciseId) {
            this.app = app;
            this.currentExercise = (exerciseId !== undefined &&
                this.app.getExercise('id', exerciseId)) || null;
            this.templateManager = new TemplateManager();
            $(document).ready(this.domInit.bind(this));

            // init inner objects
            this.home.context = this;
            this.new_exercise.context = this;
            this.notification.context = this;
        },

        /**
         * When DOM is ready, initialise it
         */
        domInit: function UI_domInit() {
            this.templateManager.loadToCache(
                [
                    'home',
                    'exercise',
                    'new_exercise',
                    'notification',
                    'exerciseNotification'
                ],
                this.initPages.bind(this)
            );
            // Disable text selection
            $.mobile.tizen.disableSelection(document);
        },

        /**
         * Appends pages to body and initialises them.
         */
        initPages: function UI_initPages() {
            var pages = [];

            pages.push(this.templateManager.get('home'));
            pages.push(this.templateManager.get('new_exercise'));
            pages.push(this.templateManager.get('notification'));

            $('body').append(pages.join(''));

            this.home.init();
            this.new_exercise.init();
            this.notification.init();

            window.addEventListener('tizenhwkey', function (e) {
                var activePageId = $.mobile.activePage.attr('id');
                if (e.keyName === 'back') {
                    if (activePageId === 'home') {
                        app.exit();
                    } else if (activePageId === 'notification') {
                        app.exit();
                    } else if (activePageId === 'new_exercise') {
                        $.mobile.changePage('#home');
                    } else {
                        history.back();
                    }
                }
            });

            $('input[type=checkbox]').change(function () {
                $('#name').blur();
            });

            $('#name').on('keyup change', function () {
                var checked = $('#newExerciseDays input:checkbox:checked');
                if (checked.length > 0) {
                    $('#add-exercise-btn').removeClass('ui-disabled');
                } else {
                    $('#add-exercise-btn').addClass('ui-disabled');
                }
            });

            if (this.currentExercise) {
                // app run from alarm
                $.mobile.changePage('#notification', 'pop', false, true);
            } else {
                $.mobile.changePage('#home', 'pop', false, true);
            }
        },

        /**
         * Contains methods related to the home page.
         * @namespace
         */
        home: {

            /**
             * Initializes home page.
             */
            init: function UI_home_init() {
                this.addEvents();
            },

            /**
             * Binds events to the home page.
             */
            addEvents: function () {
                var self = this;

                $('#home').on('pagebeforeshow', function () {
                    this.displayList();
                    $('.removeExercise').on('click', function () {
                        var exerciseId = $(this).data('exerciseid');
                        app.ui.popup('Are you sure?', {
                            'No': function () {
                                $('#popup').popup('close');
                            },
                            'Yes': function () {
                                self.context.app.removeExercise(
                                    exerciseId,
                                    self.removeElement.bind(self, exerciseId)
                                );
                                $('#popup').popup('close');
                            }
                        });
                    });
                }.bind(this));
            },

            /**
             * Removes exercise from list
             * @param {number} exerciseId ExerciseId of the element to remove
             */
            removeElement: function (exerciseId) {
                var i = 0,
                    data = 0,
                    alarmList = document.getElementById('alarms_list'),
                    alarms = alarmList.children;

                for (i = 0; i < alarms.length; i += 1) {
                    data = alarms[i].getAttribute('data-exerciseid');
                    if (data == exerciseId) {
                        alarmList.removeChild(alarms[i]);
                    }
                }
            },

            /**
             * Builds exercises HTML list and adds it to page.
             * @param {Array|undefined} exercises list
             */
            displayList: function (exercises) {
                var len, list = '', exercise,
                    alarmList = document.getElementById('alarms_list');
                exercises = exercises || this.context.app.getAllExercises();
                len = exercises.length - 1;
                while (len >= 0) {
                    exercise = $.extend({}, exercises[len]); // copy object
                    exercise.startTime = exercise
                        .startTime
                        .match(/.+T([0-9]+\:[0-9]+)\:[0-9]+/)[1];
                    list += this.context.templateManager.get(
                        'exercise',
                        exercise
                    );
                    len -= 1;
                }
                alarmList.innerHTML = list;
                tau.engine.createWidgets(alarmList);
            }

        },

        /**
         * Contains methods related to the new exercise page.
         * @namespace
         */
        new_exercise: {

            /**
             * Initializes new exercise page.
             */
            init: function () {
                this.addEvents();
            },

            /**
             * Binds events to new exercise page.
             */
            addEvents: function () {
                var numberOfChecked = 0,
                    isName = false,
                    toggleSaveButton = function () {
                        var $button = $('#add-exercise-btn');
                        if (numberOfChecked && isName) {
                            $button.removeClass('ui-disabled');
                        } else {
                            $button.addClass('ui-disabled');
                        }
                    };

                $('#new_exercise').on('pagebeforeshow', function () {
                    var checked, len;
                    // clear everything
                    numberOfChecked = 0;
                    isName = false;
                    $('#name').val('');
                    $('#comment').val('');
                    checked = $('#newExerciseDays input:checkbox:checked');
                    len = checked.length - 1;
                    while (len >= 0) {
                        $(checked[len])
                            .attr('checked', false)
                            .data('checkboxradio')
                            .refresh();
                        len -= 1;
                    }
                    toggleSaveButton();
                });

                // bind buttons
                $('#add-exercise-btn').on('click', function () {
                    var exercise = {}, days, len;

                    days = $('#newExerciseDays input:checkbox:checked');
                    len = days.length - 1;
                    exercise.days = [];
                    while (len >= 0) {
                        exercise.days.unshift($(days[len]).data('day'));
                        len -= 1;
                    }

                    exercise.name = $('#name').val();
                    exercise.startTime = $('#startTime')
                        .datetimepicker('value');
                    exercise.comment = $('#comment').val();

                    this.app.addExercise(exercise, function () {
                        $.mobile.changePage('#home');
                    });

                }.bind(this.context));

                $('#add-exercise-cancel-btn').on('click', function () {
                    history.back();
                });

                $('#name').on('focusout', function () {
                    isName = ($(this).val().length > 0);
                    toggleSaveButton();
                });

                $('#newExerciseDays [type=checkbox]').on('change', function () {
                    if ($(this).is(':checked')) {
                        numberOfChecked += 1;
                    } else {
                        numberOfChecked -= 1;
                    }

                    toggleSaveButton();
                });
            }

        },

        /**
         * Contains methods related to the notification page.
         * @namespace
         */
        notification: {

            /**
             * Initializes notification page.
             */
            init: function () {
                this.addEvents();
            },

            /**
             * Binds events to notification page.
             */
            addEvents: function () {
                $('#notification').on('pagebeforeshow', function () {
                    var exercise, html;
                    // copy object
                    exercise = $.extend({}, this.context.currentExercise);
                    exercise.startTime = exercise
                        .startTime
                        .match(/.+T([0-9]+\:[0-9]+)\:[0-9]+/)[1];
                    html = this.context.templateManager.get(
                        'exerciseNotification',
                        exercise
                    );
                    $('.notificationContainer').html(html);
                }.bind(this));

                $('.exit').on('click', function () {
                    app.exit();
                });
            }

        }

    };

    /**
     * Creates and displays popup widget.
     * @param {String} text information
     * @param {Object} buttons template object
     */
    Ui.prototype.popup = function (text, buttons) {
        var i, popupNumber = Object.keys(buttons).length,
            popup = document.getElementById('popup'),
            popupButtons = document.getElementById('popupButtons'),
            popupText = document.getElementById('popupText'),
            tauPopup = tau.widget.Popup(popup);

        // if buttons template wasn't add,
        // use default template
        if (!buttons) {
            buttons = {
                'OK': function () {
                    tauPopup.close();
                }
            };
        }

        // clear popup
        popupButtons.innerHTML = '';

        popup.className = popup.className.replace(/\bcenter_basic.*?\b/g, '');
        popup.classList.add('center_basic_' + popupNumber + 'btn');

        // adds buttons to popup HTML element
        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)
                    );
                }
            }
        }
        // adds text to popup HTML element
        popupText.innerHTML = '<p>' + text + '</p>';

        tau.engine.createWidgets(popup);
        tau.widget.Popup(popup).open();
    };

}());