var link, user, privat, privatid, sessionid, tid, ssid;
var cf = {
text: {defaultValue: 'Введите сюда Ваше сообщение',send:'Отправить',save:'Сохранить'},
    save: function (a, b) {
        var d = $('#text'),
            iText = d.val(),
            send = $('#cf_send');
        send.attr('onclick', 'cf.send()');
        send.val(cf.text.send);
        $('#id' + b).find('#editmess' + b).html('<img src="/img/ajax.gif" align="absmiddle" />').end().css({background:'#FFFFFF'});
        d.val(cf.text.defaultValue);
        d.attr('class','cf_focus');
        $.get(a, function (c) {
                $.post('/forum/', {
                    jkd498: 1,
                    jkd428: 1,
                    message: iText,
                    smiles_on: 1,
                    signature_on: 1,
                    ssid: $('input[name="ssid"]', c).val(),
                    pn: 1,
                    fid: sessionid,
                    tid: tid,
                    p: b,
                    a: 10
                }, function () {
                    cf.reload(false, true, false);
                    reload = setInterval('cf.reload(true,false,false)', 2000)
                })
            })
        d.attr('onkeypress', 'cf.post(event,this)');
    },
    getCaretPos: function (a) {
        a.focus();
        if (a.selectionStart) return a.selectionStart;
        else if (document.selection) {
            var b = document.selection.createRange();
            var c = b.duplicate();
            b.collapse(true);
            c.moveToElementText(a);
            c.setEndPoint('EndToEnd', b);
            return c.text.length
        }
        return 0
    },
    scroll: function () {
        return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop)
    },
    documentHeight: function () {
        return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight
    },
    saveEdit: function (a, d, e, f) {
        var g = $('#text'),
            iText = g.value,
            send = $('#cf_send');
        if ((e == 1) && (cf.cookie.get('enter') == 'true') && (f.ctrlKey) && ((f.keyCode == 0xA) || (f.keyCode == 0xD))) {
                var h = document.getElementById('text').value;
                b.value = h.substring(0, cf.getCaretPos(document.getElementById('text'))) + '\n' + h.substring(cf.getCaretPos(document.getElementById('text')))
            } else {
                if ((e == 1) && (cf.cookie.get('enter') == 'true' ? (f.keyCode == 0xA) || (f.keyCode == 0xD) : (f.ctrlKey) && ((f.keyCode == 0xA) || (f.keyCode == 0xD)))) {
                    setTimeout(function () {
                        g.val('');
                    }, 100);
                    send.attr('onclick', 'cf.send()');
                    send.val(cf.text.save);
        $('#id' + d).find('#editmess' + d).html('<img src="/img/ajax.gif" align="absmiddle" />').end().css({background:'#FFFFFF'});
        g.val(cf.text.defaultValue);
        g.attr('class','cf_focus');
                    $.get(a, function (c) {
                        $.post('/forum/', {
                            jkd498: 1,
                            jkd428: 1,
                            message: iText,
                            smiles_on: 1,
                            signature_on: 1,
                            ssid: $('input[name="ssid"]', c).val(),
                            pn: 1,
                            fid: sessionid,
                            tid: tid,
                            p: d,
                            a: 10
                        }, function () {
                            cf.reload(false, true, false);
                            reload = setInterval('cf.reload(true,false,false)', 2000)
                        })
                    })
                    g.attr('onkeypress','cf.post(event,this)');
                }
            }
    },
    edit: function (a, b, c) {
        clearInterval(reload);
        var e = '\/forum\/' + a + '-' + b + '-' + c + '-9-1',
            elem = document.getElementById('elemEdit'),
            send = document.getElementById('cf_send'),
            texts = document.getElementById('text');
        if (!elem.innerHTML) elem.innerHTML = c;
        if (elem.innerHTML == c) {
                document.getElementById('id' + c).style.background = '#dff6ff'
            } else {
                document.getElementById('id' + elem.innerHTML).style.background = '#FFFFFF';
                document.getElementById('id' + c).style.background = '#dff6ff';
                elem.innerHTML = c
            };
        texts.value = '...';
        $.get(e, function (d) {
                texts.value = $('#message', d).val();
                texts.focus()
            });
        send.value = 'Сохранить';
        send.setAttribute('onclick', 'cf.save(\'' + e + '\',\'' + c + '\')');
        texts.setAttribute('onkeypress', 'cf.saveEdit(\'' + e + '\',\'' + c + '\',1,event)');
        texts.className = 'cf_blur'
    },

    smile: function (a) {
        var b = document.getElementById('text');
        b.focus();
        if (b.value == b.defaultValue) {
            b.value = '' + a + ' ';
            b.className = 'cf_blur'
        }
        if (b.value != b.defaultValue) b.value += ' ' + a + ' '
    },
    time: function (a) {
        var b = Math.abs(Math.round(((new Date() / 1000).toFixed(0) - a) / 60)),
            sec = Math.abs(Math.round(((new Date() / 1000).toFixed(0) - a)));
        return (sec >= 0 && sec <= 60) ? sec + ' сек.' : (b >= 0 && b <= 60) ? b + ' мин.' : (b >= 46 && b <= 90) ? 'около часа' : (b >= 90 && b <= 1440) ? 'около ' + Math.round(b / 60) + ' час.' : (b >= 1441 && b <= 2880) ? '1 дн.' : Math.round(b / 1440) + ' дн.'
    },
    deletes: function (a, b, c) {
        if (confirm('Вы уверены?')) $.get('/forum/' + a + '-' + b + '-' + c + '-8-0-' + ssid, function () {
            document.getElementById('id' + c).style.display = 'none'
        })
    },
    reloaduserlist: function () {
        $.get('/forum/' + sessionid, function (d) {
            var a = [];
            $('.forumOnlineBar a', d).each(function () {
                a.push('<a href="javascript://" onclick="cf.insertnick(this)">' + this.innerHTML + '</a>, ')
            });
            var c = $('#cf_online');
            c.html(a.join(''));
            c.html(c.html().substring(0, c.html().length - 2));
            document.getElementById('cf_lenuser').innerHTML = document.getElementById('cf_online').getElementsByTagName('a').length
        })
    },
    openap: function (a) {
        sessionid = a;
        location.href = '?f=1;m=' + a
    },
    insertnick: function (a) {
        var b = document.getElementById('text');
        if (b.value == b.defaultValue) {
            b.value = a.innerHTML + ', ';
            b.className = 'cf_blur';
            b.focus()
        } else {
            b.value += a.innerHTML + ', ';
            b.focus()
        }
    },
    start: function () {
        $(document.body).find('#cf_start').hide().end().find('#cf_body').show()
    },
    ctrlEnter: function (a) {
        a == true ? cf.cookie.set('enter', a, 365) : cf.cookie.del('enter')
    },
    reload: function () {
        var b = [];
        $.get(link, function (a) {
            ssid = $('#ssid', a).text();
            if ($('.switchDigit:last', a).text() > link.split('-')[2]) {
                cf.data();
                $('#cf_prev').show()
            }; 
            $('#mess', a).each(function () {
                b.push(this.innerHTML)
            });
            if ($('.cf_cormess:last', a).attr('id').substring(2) != $('#cf_messages').find('.cf_cormess:last').attr('id').substring(2)) {
                if ($('.cf_cormess:last #user', a).html() != user) cf.sound('add');
$(document.body).scrollTo('.cf_cormess:last', 500);
                document.getElementById('cf_messages').innerHTML = b.join('');
                $('#cf_messages span.timestamp').each(function () {
                    this.innerHTML = cf.time(this.innerHTML) + ' назад'
                });
                /*$("div.cf_messages img").each(function () {
                    if ($(this).height() > 40 && $(this).width() > 40) {
                        $(this).replaceWith('<img onclick="window.open(\'' + this.src + '\')" src="http://www.eserv.ru/e4a/icons/folder_picture.png" alt="image" />')
                    }
                })*/
            }
        })
    },
    post: function (a, b) {
        var d = new Date(),
            val = b.value.replace(/\:\*/ig, ':kiss:');
        if (!val) return;
        if ((cf.cookie.get('enter') == 'true') && (a.ctrlKey) && ((a.keyCode == 0xA) || (a.keyCode == 0xD))) {
                var e = document.getElementById('text').value;
                b.value = e.substring(0, cf.getCaretPos(document.getElementById('text'))) + '\n' + e.substring(cf.getCaretPos(document.getElementById('text')))
            } else {
                if (cf.cookie.get('enter') == 'true' ? (a.keyCode == 0xA) || (a.keyCode == 0xD) : (a.ctrlKey) && ((a.keyCode == 0xA) || (a.keyCode == 0xD))) {
                    setTimeout(function () {
                        b.value = ''
                    }, 100);
                    document.getElementById('cf_messages').innerHTML += '<div class="cf_cormess"><div class="users"><a href="javascript://" style="color:#999999" class="bold" onclick="cf.insertnick(this)">' + user + '</a></div><div class="cf_messages">' + val + ' <img src="/img/ajax.gif" align="absmiddle" /></div></div>';
$(document.body).scrollTo('.cf_cormess:last', 500);
                    $.get(link, function (c) {
                        $.post('/forum/', {
                            jkd498: 1,
                            jkd428: 1,
                            message: val,
                            smiles_on: 1,
                            signature_on: 1,
                            ssid: $('input[name="ssid"]', c).val(),
                            fid: sessionid,
                            tid: tid,
                            p: 0,
                            a: 7
                        }, function () {
                            cf.reload(true, false, false)
                        })
                    })
                }
            }
    },
    load: function () {
//$(window).bind('scroll',function(){
//alert('winH: ' + $(window).height() + '; docH: ' + $(document.body).height() + '; sT: ' + $(window).scrollTop());
//});
        var f;
        setInterval(function () {
            if (!$('#cf_body').is(':visible')) {
                var a = document.getElementById('cf_start').innerHTML.length,
                    innerElem = document.getElementById('cf_start');
                innerElem.innerHTML = (a == 0 ? '.' : a == 1 ? '..' : a == 2 ? '...' : a == 3 ? '' : false)
            }
        }, 300);
        if (location.href == 'http://symbian9.org/conference/') {
            location.href = '?f=1;m=14';
            var g = [];
            $.get('/forum/11', function (d) {
                $('td.forumNameTd', d).each(function (i) {
                    g.push('<div class="ap" onclick="cf.openap(\'' + $(this).find('a.forum').attr('href').split('/')[4] + '\')"><div class="aps"><h3><img src="icon/user-group-icon.png"  alt="icon" align="absmiddle" /> <a href="javascript://" onclick="cf.openap(\'' + $(this).find('a.forum').attr('href').split('/')[4] + '\')">' + $(this).find('a.forum').text() + '</a></h3></div></div>');
                });
                document.getElementById('cf_ap').innerHTML = g.join('')
                $(document.body).find('#cf_start').hide().end().find('#cf_ap').show()
            })
        }
        if (location.href == 'http://symbian9.org/conference/') return;
        if (location.href != 'http://symbian9.org/conference/') sessionid = document.location.search.split('?')[1].split('=')[2];
        if (document.location.search.split('=')[1].substring(0, 1) != 'undefined') {
            $.get('/forum/' + sessionid, function (d) {
                if ($('#loggen', d).text() != '1') {
                    $('#cf_body').html('<h1 style="text-align:center">Приносим свои извинения, но вход в конференцию доступен только авторизованным пользователям.</h1><br><h3 style="text-align:center"><a href="/index/0-5">Авторизация</a></h3>');
                    cf.start()
                } else {
                    var e = [],
                        online = [];
                    f = (typeof $('.threadNametd:first', d).find('.postpSwithces a:last').attr('href') == 'undefined') ? 1 : 0;
                    link = (typeof $('.threadNametd:first', d).find('.postpSwithces a:last').attr('href') == 'undefined') ? $('.threadLink:first', d).attr('href') : $('.threadNametd:first', d).find('.postpSwithces a:last').attr('href');
                    user = $('.navis a.bold', d).text();
                    document.getElementById('cf_users').innerHTML = user;
                    if (f == true) $('#cf_prev').hide();
                    $('.forumOnlineBar a', d).each(function () {
                            online.push('<a href="javascript://" onclick="cf.insertnick(this)">' + this.innerHTML + '</a>, ')
                        });
                    var c = $('#cf_online');
                    c.html(online.join(''));
                    c.html(c.html().substring(0, c.html().length - 2));
                    document.getElementById('cf_lenuser').innerHTML = document.getElementById('cf_online').getElementsByTagName('a').length;
                    $.get(link, function (a) {
                            ssid = $('#ssid', a).text();
                            tid = link.split('-')[1];
                            $('#mess', a).each(function () {
                                e.push(this.innerHTML)
                            });
                            document.getElementById('cf_messages').innerHTML = e.join('');
                            $('#cf_messages span.timestamp').each(function () {
                                this.innerHTML = cf.time(this.innerHTML) + ' назад'
                            });
                            /*$("div.cf_messages img").each(function () {
                                if ($(this).height() > 40 && $(this).width() > 40) {
                                    $(this).replaceWith('<img onclick="window.open(\'' + this.src + '\')" src="http://www.eserv.ru/e4a/icons/folder_picture.png" alt="image" />')
                                }
                            });*/
$(document.body).scrollTo('.cf_cormess:last', 500);
                            ureload = setInterval('cf.reloaduserlist()', 30000),reload = setInterval('cf.reload(true,false,false)', 2000);
                            if (cf.cookie.get('enter') == 'true') $('#enter').attr('checked', true);
                            $(document.body).find('#cf_start').hide().end().find('#cf_body').show()
                        })
                }
            })
        } else {
            location.href = '/conference/'
        }
    },
    focus: function (a) {
        if (a.value == a.defaultValue) {
            a.value = '';
            a.className = 'cf_blur'
        }
    },
    blur: function (a) {
        if (!a.value) {
            a.value = a.defaultValue;
            a.className = 'cf_focus'
        }
    },
    send: function () {
        var a = document.getElementById('text'),
            time = new Date();
        val = a.value.replace(/\|/ig, '').replace(/\:\*/ig, ':kiss:');
        if (a.value == a.defaultValue) return;
        document.getElementById('cf_messages').innerHTML += '<div class="cf_cormess"><div class="users"><a href="javascript://" style="color:#999999" class="bold" onclick=cf.insertnick(this)">' + user + '</a></div><div class="cf_messages">' + val + ' <img src="/img/ajax.gif" align="absmiddle" /></div></div>';
        window.scrollTo(0, 1800);
        a.value = '';
        $.get(link, function (c) {
                $.post('/forum/', {
                    jkd498: 1,
                    jkd428: 1,
                    message: val,
                    smiles_on: 1,
                    signature_on: 1,
                    ssid: $('input[name="ssid"]', c).val(),
                    fid: sessionid,
                    tid: tid,
                    p: 0,
                    a: 7
                }, function () {
                    cf.reload(true, false, false)
                })
            })
    },
    data: function () {
        $.get('/forum/' + sessionid, function (d) {
            link = (typeof $('.threadNametd:first', d).find('.postpSwithces a:last').attr('href') == 'undefined') ? $('.threadLink:first', d).attr('href') : $('.threadNametd:first', d).find('.postpSwithces a:last').attr('href')
        })
    },
    prev: function (b) {
        $('.cf_prevlink').remove();
        var c = [],
            links = parseInt(link.split('-')[2] - 1);
        $.get('/forum/' + sessionid + '-' + tid + '-' + (b ? b : links), function (a) {
                $('#mess', a).each(function () {
                    c.push(this.innerHTML)
                });
                document.getElementById(b ? 'cf_prev' + b : 'cf_prev').innerHTML = c.join('');
                $(b ? '#cf_prev' + b + ' span.timestamp' : '#cf_prev span.timestamp').each(function () {
                    this.innerHTML = cf.time(this.innerHTML) + ' назад'
                });
                /*$(b ? '#cf_prev' + b + ' img' : '#cf_prev img').each(function () {
                    if ($(this).height() > 40 && $(this).width() > 40) {
                        $(this).replaceWith('<img onclick="window.open(\'' + this.src + '\')" src="http://www.eserv.ru/e4a/icons/folder_picture.png" alt="image" />')
                    }
                });*/
                if (b == 1) return;
                $(b ? '#cf_prev' + b : '#cf_prev').before('<div id="cf_prev' + ((b ? b : links) - 1) + '"><div class="cf_prevlink"><a href="javascript://" onclick="cf.prev(' + ((b ? b : links) - 1) + ')">Еще раньше</a></div></div>');
                $(b ? '#cf_prev' + b + '  .cf_cormess:last' : '#cf_prev .cf_cormess:last').after('<div class="cf_prev"></div>')
            })
    },
    sound: function (a) {
        a = 'sound\/' + a + '.swf';
        document.getElementById('cf_sound').innerHTML = $.browser.msie ? '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" height="0" width="0" type="application/x-shockwave-flash"><param name="movie" value="' + a + '"></object>' : '<embed src="' + a + '" width="0" height="0" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>'
    },
    cookie: {
        set: function (a, b, c) {
            if (c) {
                var d = new Date();
                d.setTime(d.getTime() + (c * 24 * 60 * 60 * 1000));
                var e = "; expires=" + d.toGMTString()
            } else {
                var e = ""
            }
            document.cookie = a + "=" + b + e + "; path=/"
        },
        get: function (a) {
            var b = a + "=";
            var d = document.cookie.split(';');
            for (var i = 0; i < d.length; i++) {
                var c = d[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(b) == 0) return c.substring(b.length, c.length)
            }
            return null
        },
        del: function (a) {
            cf.cookie.set(a, "", -1)
        }
    }
};
