var chat = {

    user_me_id: 0,
    user_to_id: 0,
    user_me_name: '',
    user_to_name: '',
    message: [],
    periodGetContacts: null,
    periodLoadDialog: null,

    content:
        '<div class="l">'+
            '<div class="field"><div class="corners"><div></div></div>'+
            '<h3></h3>'+
            '<div id="messages"></div>'+
            '<textarea id="message"></textarea>'+
            '<div class="button"><a href="javascript:chat.history();" id="chatHistoryButton">История сообщений</a>(Ctrl+Enter) <input type="button" name="submit" value="Отправить" id="chatSubmit"></div>'+
            '</div>'+
        '</div>'+

        '<div class="r">'+
            '<b>Контакты:</b>'+
            '<div id="contacts"></div>'+
        '</div>',


    historyContent:
            '<div class="field"><div class="corners"><div></div></div>'+
            '<select><option value="0"></option></select>'+
            '<div id="historyMessages"></div>'+
            '</div>',


    init: function(user_to, this_)
    {
        new Request.JSON({
            url: '/ajax.php?do=chatInit',
            onComplete: function(response)
            {   
                if (response['restrict']) 
                {                                  
                    user.restrictDialog(response, this_);
                }
                else if (response)
                {   
                    win.init('chat', 'Мой Дагестан → Моё общение', 750);
                    win.content('chat').set('html', chat.content);

                    $('chatSubmit').addEvent('click', function(){ chat.send(); });
                    win.gotoCenter('chat');

                    chat.user_to_id = user_to;
                    chat.user_me_id = chat.getIdFromLink($('logged_user').get('href'));
                    chat.user_me_name = $('logged_user').get('text');

                    chat.getContactsPeriodical();
                    chat.loadDialogPeriodical();
                    chat.initKeyPress();

                    $('chat').getElement('tr.top a').addEvent('click', chat.deinit);
                }
            }
        }).get({'user_to': user_to});
    },


    deinit: function() {
        chat.user_to_id = 0;
        chat.user_to_name = '';
        window.clearInterval(chat.periodGetContacts);
        window.clearInterval(chat.periodLoadDialog);
    },


    send: function()
    {
        chat.drawAjax('start');
        new Request.JSON({
            url: '/ajax.php?do=chatSend',
            onComplete: function(response) {
                chat.drawDialog(response);
                $('message').set('value', '');
                $('message').value = '';
                chat.drawAjax('stop');
        }}).post({'user_to': chat.user_to_id, 'message': $('message').value});
    },


    loadDialog: function()
    {
        chat.drawAjax('start');
        new Request.JSON({
            url: '/ajax.php?do=chatSend',
            onComplete: function(response) {
                chat.drawDialog(response);
                chat.drawAjax('stop');
        }}).post({'user_to': chat.user_to_id});
    },


    getContacts: function()
    {
        chat.drawAjax('start');

        if ($('contacts'))
        new Request.JSON({
            url: '/ajax.php?do=chatGetContacts',
            onComplete: function(response) {
                chat.drawContacts(response);
                chat.user_to_name = $('contacts').getElement('a[href$=/'+ chat.user_to_id +']').getElement('em').get('text');
                $('contacts').getElement('a[href$=/'+ chat.user_to_id +']').set('class', 'selected');
                $('chat').getElement('div.field > h3').set('text', chat.user_to_name);
                chat.drawAjax('stop');
        }}).get({'user_to': chat.user_to_id});
        else chat.deinit();
    },


    loadDialogPeriodical: function()
    {
        chat.loadDialog();
        var loadDialog = function(){ chat.loadDialog(); };
        chat.periodLoadDialog = loadDialog.periodical(25000);
    },


    getContactsPeriodical: function()
    {
        chat.getContacts();
        var getContacts = function(){ chat.getContacts(); };
        chat.periodGetContacts = getContacts.periodical(63000);
    },


    drawContacts: function(response)
    {
        var html = '';
        var status = '';

        response.each(function(elem){
            if (elem.newmsg == '0') status = ''; else status = 'class="new"';
            html += '<a href="/users/'+ elem.id +'" '+ status +' onClick="chat.selectContact(this); return false;">';
            html += '<span><b>'+ elem.counter +'</b></span>';
            html += '<em>'+ elem.username +'</em>';
            html += '</a>';
        });

        if ($('contacts')) $('contacts').set('html', html);
        else chat.deinit();
    },


    selectContact: function(this_)
    {
        if ($('contacts').getElement('a.selected')) $('contacts').getElement('a.selected').set('class','');
        chat.message[chat.user_to_id] = $('message').value; // сохраняем поле сообщения
        chat.user_to_id = chat.getIdFromLink($(this_).get('href'));
        chat.user_to_name = $(this_).getElement('em').get('text');
        $('message').value = '';
        chat.send();
        if (chat.message[chat.user_to_id]) $('message').value = chat.message[chat.user_to_id]; // возвращаем поле сообщения
        $(this_).set('class', 'selected');
        $('chat').getElement('div.field > h3').set('text', chat.user_to_name);
    },


    drawDialog: function(response)
    {
        var html = '';
        var title = '';
        var deliver = '';

        response.each(function(elem){
            if (!elem.delivered) deliver = ' undelivered'; else deliver = '';
            if (!elem.delivered) title = 'Сообщение не прочитано'; else title = 'Сообщение прочитано';

            if (elem.user_id_from.toInt() == chat.user_me_id) html += '<div class="out'+ deliver +'"><span title="'+ title +'"><a href="/users/'+ chat.user_me_id +'" target="_blank">'+ chat.user_me_name +'</a> '+ elem.ts_created +'</span>'+ elem.content +'</div>';
            if (elem.user_id_from.toInt() == chat.user_to_id) html += '<div class="in'+ deliver +'"><span title="'+ title +'"><a href="/users/'+ chat.user_to_id +'" target="_blank">' + chat.user_to_name +'</a> '+ elem.ts_created +'</span>'+ elem.content +'</div>';
        });

        if ($('messages'))
        {
            $('messages').set('html', html);
            new Fx.Scroll($('messages'), {offset: {x: 0, y:100000}}).toBottom();
        }
        else chat.deinit();
    },


    drawAjax: function(what)
    {
        if ($('chat'))
        {
            if (what == 'start') $('chat').getElement('div.field > h3').set('class','ajax');
            if (what == 'stop')  $('chat').getElement('div.field > h3').set('class','');
        }
    },


    getIdFromLink: function(link)
    {
        return link.replace('\/users\/','').toInt()
    },


    initKeyPress: function()
    {
        $('message').addEvent('keydown', function(event){
            if (event.control && event.key == 'enter' && $(event.target).get('value')) {
                chat.send();
            }
        });
    },

    
    history: function()
    {
        new Request.JSON({
            url: '/ajax.php?do=chatHistory',
            onComplete: function(response) 
            {
                win.init('chatHistory', 'История сообщений', 530);
                win.content('chatHistory').set('html', chat.historyContent);
                win.gotoCenter('chatHistory');
                var select = $('chatHistory').getElement('select');
                
                response.each(function(elem)
                {
                    var option = new Element('option', {'value': elem.id}).set('text', elem.username);
                    option.inject(select);

                });
                
                select.addEvent('change', function(){ chat.historyDialog(select); });
            }
        }).get({'user_to': chat.user_to_id});
        
    },
    
    
    historyDialog: function(select)
    {
        new Request.JSON({
            url: '/ajax.php?do=dialogHistory',
            onComplete: function(response) 
            {
                var html = '';
                var title = '';
                var deliver = '';

                response.each(function(elem)
                {
                    if (!elem.delivered) deliver = ' undelivered'; else deliver = '';
                    if (!elem.delivered) title = 'Сообщение не прочитано'; else title = 'Сообщение прочитано';

                    if (elem.user_id_from.toInt() == chat.user_me_id) html += '<div class="out'+ deliver +'"><span title="'+ title +'"><a href="/users/'+ chat.user_me_id +'" target="_blank">'+ chat.user_me_name +'</a> '+ elem.ts_created +'</span>'+ elem.content +'</div>';
                    if (elem.user_id_from.toInt() == chat.user_to_id) html += '<div class="in'+ deliver +'"><span title="'+ title +'"><a href="/users/'+ chat.user_to_id +'" target="_blank">' + chat.user_to_name +'</a> '+ elem.ts_created +'</span>'+ elem.content +'</div>';
                });
                $('historyMessages').set('html', html);
            }
        }).post({'user_to': select.value});


    }

}

