var DIALOG = {};

DIALOG._showDialog = function(settings){
    function doCancel(){
        settings.buttons.cancel();
        DIALOG._callNextShowFunction();
    };
    function doOK(){
        if(false === settings.buttons.ok()) return;
        DIALOG._callNextShowFunction();
    };
    /*
     * settings.title
     * settings.content
     * settings.buttons.ok
     * settings.buttons.cancel
     */
    DIALOG._remove();
    var parentDiv = $('<div>', {
        role: 'dialog',
        'aria-hidden': 'true',
        'aria-labelledby': 'modalDialogLabel',
        tabindex: -1,
        id: 'modalDialog',
    })
        .addClass('modal fade')
    ;
    var modalDialogDiv = 
        $('<div>').addClass('modal-dialog').appendTo(parentDiv);
    var modalDialogContent =
        $('<div>').addClass('modal-content').appendTo(modalDialogDiv);


    /* construct header */
    var modalDialogHeader =
        $('<div>').addClass('modal-header').appendTo(modalDialogContent);
    modalDialogHeader
        .append(
            $('<button>', {
                type: 'button',
                'data-dismiss': 'modal',
                'aria-hidden': 'true',
            })
                .addClass('close')
                .html('&times;')
                .click(doCancel)
        )
        .append(
            $('<h4>', {id: 'modalDialogLabel'})
                .addClass('modal-title')
                .text(settings.title)
        )
    ;

    /* construct body */
    var modalDialogBody =
        $('<div>').addClass('modal-body').appendTo(modalDialogContent);
    modalDialogBody.append(settings.content);

    
    /* construct footer */
    var modalDialogFooter = 
        $('<div>')
            .addClass('modal-footer')
            .appendTo(modalDialogContent)
    ;

    /* buttons */
    if(settings.buttons.cancel){
        modalDialogFooter.append(
            $('<button>', {
                type: 'button',
                'data-dismiss': 'modal'
            })
                .addClass('btn btn-default')
                .text('取消')
                .click(doCancel)
        );
    };
    modalDialogFooter.append(
        $('<button>', {
            type: 'button',
        })
            .addClass('btn btn-primary')
            .text('确定')
            .click(doOK)
    );

    
    parentDiv.appendTo('body');
    $('#modalDialog').modal({
        keyboard: false,
        backdrop: 'static',
    })
        .modal('show');
};

//////////////////////////////////////////////////////////////////////////////

DIALOG._showFunctionSequence = [];
DIALOG._showing = false;

DIALOG._callNextShowFunction = function(){
    // when possible, show the next modal dialog, and mark the showing flag.
    // if no next modal dialog, clear the flag.
    DIALOG._hide();
    var target = DIALOG._showFunctionSequence.shift();
    if(Boolean(target)){
        target();
        DIALOG._showing = true;
    } else
        DIALOG._showing = false;
};

DIALOG._show = function(){
    // if showing flag is marked, do nothing. the next show should be
    // initiated with each dialog itself. otherwise, call next show.
    if(!DIALOG._showing) DIALOG._callNextShowFunction();
};
DIALOG._hide = function(){
    $('#modalDialog').modal('hide');
};
DIALOG._remove = function(){
    $('#modalDialog').remove();
    $('.modal-backdrop').remove();
};

/****************************************************************************/

DIALOG.askPIN = function(callback, questionConfig){
    /*
     * questionConfig.doubleConfirm:
     *      when true, will display 2 boxes to ask for input.
     * questionConfig.originalPassword:
     *      when true, will specifically ask for origianl password.
     */
    DIALOG._showFunctionSequence.push((function(cb){
        // returns a function, when called, the modal box is shown.
        var content = $('<div>');

        var humanText = '';
        if(questionConfig.doubleConfirm){
            humanText = '请输入新密码，输入2次同样的值以便确认。';
        } else if(questionConfig.originalPassword){
            humanText = '请输入原始密码。';
        } else
            humanText = '请输入用于解密私钥的密码，以便验证您的身份。';
        content.text(humanText);

        content.append(
            $('<input>', {
                id: 'modalDialog-passphrase',
                type: 'password',
            })
                .addClass('form-control')
        );

        // deal with logic different with double-confirm and normal
        var okFunc = function(){
            cb(null, $('#modalDialog-passphrase').val());
        };

        if(questionConfig.doubleConfirm){
            content.prepend(
                $('<div>', {
                    id: 'modalDialog-passphrase-no-match',
                })
                    .text(' 两次输入的密码不一致。请重新输入。')
                    .prepend($('<span>').addClass('glyphicon glyphicon-remove'))
                    .addClass('alert alert-danger')
                    .hide()
            );
            content.append(
                $('<input>', {
                    id: 'modalDialog-passphrase-confirm',
                    type: 'password',
                }).addClass('form-control')
            );
            okFunc = function(){
                var pwd1 = $('#modalDialog-passphrase').val(),
                    pwd2 = $('#modalDialog-passphrase-confirm').val();
                if(pwd1 != pwd2){
                    $('#modalDialog-passphrase-no-match').show();
                    $('#modalDialog-passphrase-confirm').val('');
                    return false;
                };
                cb(null, pwd1);
            };
        };

        // config dialog
        var config = {
            title: '要求密码',
            content: content,
            buttons: {
                ok: okFunc,
                cancel: function(){ cb(true); },
            },
        };
        return function(){DIALOG._showDialog(config);};
    })(callback));
    DIALOG._show();
};

DIALOG.confirm = function(callback, dialogConf){
    DIALOG._showFunctionSequence.push((function(cb){
        var content = dialogConf.content || $('<div>');
        var funcOK = function(){cb(null);};

        // use a special way of confirming the user's purpose
        if(dialogConf.typecode){
            $('<div>')
                .append($('<div>')
                    .text('请完整输入如下字符串：')
                    .append($('<strong>').text(dialogConf.typecode))
                )
                .append($('<input>', {
                    'id': 'modalDialog-confirm-typecode',
                    'type': 'text',
                })
                .addClass('form-control'))
                .appendTo(content)
            ;
            funcOK = function(){
                if(
                    dialogConf.typecode !=
                    $('#modalDialog-confirm-typecode').val()
                )
                    return false;
                cb(null);
            };
        };
        
        var config = {  
            title: '确认',
            content: content,
            buttons: {
                ok: funcOK,
                cancel: function(){cb(true);},
            },
        };
        return function(){DIALOG._showDialog(config);}; 
    })(callback));
    DIALOG._show();
};
