/*
 * 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 $, tizen, app, window, document, history*/

/**
 * @class UiEvents
 */
function UiEvents(parent) {
    'use strict';

    this.ui = parent;
}

(function strict() {
    'use strict';
    UiEvents.prototype = {

        /**
         * Initializes UiEvents object.
         */
        init: function UiEvents_init() {
            this.addPageEvents();
            this.enableFooterOnSoftKeyboard();
        },

        /**
         * Binds events to pages.
         */
        addPageEvents: function UiEvents_addPageEvents() {
            var self = this;

            $('#main-header .ui-btn-back').on(
                'vclick',
                function onMainHeaderBackBtnClick(event) {
                    event.preventDefault();
                    event.stopPropagation();
                    app.exit();
                }
            );

            $('#chat-header').on(
                'vclick',
                '.ui-btn-back',
                function onChatHeaderBackBtnClick(event) {
                    event.preventDefault();
                    event.stopPropagation();
                    $.mobile.changePage('#main');
                }
            );

            $('#contactSelect-header').on(
                'vclick',
                '.ui-btn-back',
                function onContactSelectHeaderBackBtnClick(event) {
                    event.preventDefault();
                    event.stopPropagation();
                    $.mobile.changePage('#main');
                }
            );

            $('#contactSelect-button').on(
                'vclick',
                function onContactSelectBtnClick(event) {
                    event.preventDefault();
                    event.stopPropagation();
                    app.loadContacts();
                }
            );

            $('#chat, #main').on('pageshow', function onMessagePageShow() {
                app.fillUpMessagePage();
            });

            $('#chat').on('pagebeforeshow', function onChatPageBeforeShow() {
                app.resetPages();
                self.ui.clearChatList();
            });

            $('#contactSelect').on(
                'pageshow',
                function onContactSelectPageShow() {
                    app.showContactsLoaded();
                }
            );

            $('#text').on('input', function onTextInput() {
                // Update character counter.
                self.ui.setChatCounterValue($(this),
                    app.model.getTextEncoding($(this).val()));
                // Enable/disable send button if necessary.
                self.ui.checkChatSendButtonState();
            });

            $('#enterNumber').on('vclick', function onEnterNumberClick(event) {
                event.preventDefault();
                event.stopPropagation();
                $('#number').val('');
                $('#enterNumber-popup').popup('open', {positionTo: 'window'});
            });

            $('#enterNumberCreate').on(
                'vclick',
                function onEnterNumberCreateClick() {
                    $('#enterNumber-popup').popup('close');
                }
            );

            $('#enterNumber-popup').on(
                'popupafterclose',
                function onPopupAfterClose() {
                    if ($('#number').val().trim() !== '') {
                        self.ui.createChatByNumber();
                        $('#number').val('');
                        $('#enterNumberCreate')
                            .addClass('ui-disabled')
                            .attr('tabIndex', '-1')
                            .blur();
                    }
                }
            );

            $('#number').on('keydown', function onKeyDown(e) {
                if (e.keyCode === 13) {
                    if ($('#number').val().length > 0) {
                        $('#enterNumber-popup').popup('close');
                    } else {
                        $('#number').blur();
                    }
                } else if (e.keyCode !== 0 &&
                        $.inArray(e.keyCode, app.allowKeys) === -1 &&
                        new RegExp('([^0-9])').test(
                            String.fromCharCode(e.keyCode)
                        )
                        ) {
                    e.preventDefault();
                }
            });

            $('#number').on('keyup focusout input', function onInputEnd(e) {
                if ($.inArray(e.keyCode, app.allowKeys) === -1) {
                    var newvalue = $(this).val()
                        .replace(app.notNumberChars, '');
                    if (newvalue !== $(this).val()) {
                        $(this).val(newvalue);
                    }
                }
                if ($(this).val().length === 0) {
                    $('#enterNumberCreate')
                        .button('disable')
                        .attr('tabIndex', '-1')
                        .blur();
                } else {
                    $('#enterNumberCreate')
                        .button('enable')
                        .attr('tabIndex', '0');
                }
            });

            $('#send').on('vclick', function onSendClick(event) {
                var text = $('#text').blur().val();
                event.stopPropagation();
                self.ui.resetTextAreas();
                self.ui.setChatCounterValue();
                self.ui.checkChatSendButtonState();
                app.sendMessage(text, [app.getCurrentNumber()]);
            });

            $('#main-content .ui-listview').on(
                'vclick',
                'li.ui-li-has-multiline',
                function onLiClick(event) {
                    self.ui.onCallerListElementTap(event, $(this));
                }
            );

            $('#text').on('blur', function onTextBlur() {
                app.ui.scrollToBottom();
            });

            window.addEventListener('tizenhwkey', function onTizenHwKey(e) {
                if (e.keyName === 'back') {
                    if ($.mobile.popup.active) {
                        $.mobile.popup.active.close();
                    } else if ($.mobile.activePage.attr('id') === 'main') {
                        tizen.application.getCurrentApplication().exit();
                    } else if ($.mobile.activePage.attr('id') === 'chat') {
                        $.mobile.changePage('#main');
                    } else {
                        history.back();
                    }
                }
            }, true);

            document.addEventListener(
                'webkitvisibilitychange',
                function onVisibilityChange() {
                    // If the app became visible, reload contacts and messages.
                    if (document.webkitVisibilityState === 'visible') {
                        app.model.loadContacts(app.fillUpMessagePage.bind(app));
                        app.model.prepareMessages(function onPrepared() {
                            app.fillUpMessagePage();
                            app.model.prepareMessages();
                        });
                    }
                }
            );

            $(window).on('resize', function onResize() {
                $.mobile.activePage.page('refresh');
            });

            $('.ui-page').css('min-height', 0);
        },

        enableFooterOnSoftKeyboard: function enableFooterOnSoftKeyboard() {
            window.addEventListener(
                'softkeyboardchange',
                function onSoftKeyboardChange(event) {
                    event.stopPropagation();
                    app.ui.scrollToBottom();
                    app.ui.clearSendButton();
                }
            );
        }
    };
}());
