var RBjs = new function()
{
    var me = this;
    this.cache = {};
    
    this.className = 'RBjs';
    
    /**
    Based on http://www.tigir.com/addbookmark.htm (Tigirlas Igor)
    Thx
    **/
    this.addBookmark = function(url, title) 
    {
        if (!url) url = location.href;
        if (!title) title = 'RB.ru – бизнес-информация и деловое сообщество';//document.title;

        //Gecko
        if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
            window.sidebar.addPanel (title, url, "");
            
        }
        // Chrome
        else if( window.navigator.userAgent.indexOf( 'Chrome' ) > -1 ) {
            alert('Ваш браузер не поддерживает автоматическое добавление закладок.')
            return false;
        }
        //IE4+
        else if (typeof window.external == "object") {
            window.external.AddFavorite(url, title);
        }
        //Opera7+
        /*
        else if (window.opera && document.createElement) {
            var a = document.createElement('A');   
            if (!a) return false; //IF Opera 6
            a.setAttribute('rel','sidebar');
            a.setAttribute('href',url);
            a.setAttribute('title',title);
            alert( a.title );
            //a.click();
        }
        */
        else {
            alert('Ваш браузер не поддерживает автоматическое добавление закладок.')
            return false;
        }

        return true;
    }
    
    this.setStartPage = function( obj )
    {
        try {
            if (document.all)  {
                obj.style.behavior='url(#default#homepage)';
                obj.setHomePage('http://www.rb.ru/');
            } else if(!document.layers) {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesWrite");
                navigator.preference("browser.startup.homepage", "http://www.rb.ru/"); 
            } else {
                alert('Ваш браузер не поддерживает автоматическое изменение cтартовой страницы.');
            }
        } catch(e) {
            alert('Ваш браузер не поддерживает автоматическое изменение cтартовой страницы.');
        }
    }
    
    this.Session = new function()
    {
        this.success_callback = 0;
        this.error_callback = 0;
        this.is_admin = 0;
    
        this.Close = function()
        {
            this.displayname = '';
            this.member_id = '';
            this.pass_hash = '';
            this.pass_hash_expire = '';
            this.is_admin = 0;
        }
        
        this.reloadPage = function( hard )
        {
            if( hard ) {
               setTimeout( "window.location.reload(true)", 500 );
            } else {
                /*
                здесь будет логика определения будет перезагружаться страница или нет.
                
                if( document.location.pathname.indexOf("/community/") == 0 || 
                    document.location.pathname.indexOf("/blog/")==0 )
                {
                    setTimeout( "window.location.reload(true)", 500 );
                }
                */
            }
        }

        this.logIn = function( form_id )
        {    
            if(this.process) return false;
            this.process = 1;
            
            var form = $j( '#' + form_id);
            var form_data = form.serialize();            
                        
            if(form[0] && typeof(form[0].openid_identifier) != 'undefined')
            {                 
                if(form[0].openid_identifier.value)
                {
                    window.location.href = '/openid/index.php?openid_identifier=' + form[0].openid_identifier.value + '&' + Math.random();
                    return false;
                }
            }
            
            $j.ajax({                
                url: '/profile/index/login',
                global: false,
                type: 'POST',                
                data: form_data,
                dataType: 'json',
                success: function( reply ) {                
                    me.Session.process = 0;
                    if(reply['error'])
                    {
                        $j('#impulse_register_form').hide();
                        $j('.form_error', form).removeClass('show');
                        $j('.vh', form).removeClass('error');
                        
                        var count = reply['fields'].length;
                        for(i = 0; i < count; i++)
                        {
                            $j("input[name='"+ reply['fields'][i] +"']", form).toggleClass('error');
                        }
                        
                        $j('.form_error.loginerr', form).html(reply['error']).toggleClass('show');
                    }
                    else
                    {
                        me.Session.setSessionPrms({'member_id': reply['i'],'displayname': reply['n'], 'pass_hash': reply['p']});
                        $j( '.name_in_comments_form' ).html( 'Вы вошли как: ' + me.Session.displayname );                        
                        RBjs.ModalPopUp.execSuccesCallback();                        
                    }            
                },
                error: function() {
                    me.Session.process = 0;
                }
            });   
        }
                
        this._logIn = function( form_id )
        {    
            var form = $j( '#' + form_id);
            var form_data = form.serialize();            
            
            if(form[0].openid_identifier)
            { 
                window.location.href = '/openid/index.php?openid_identifier=' + form[0].openid_identifier.value + '&' + Math.random();
                return false;
            }
            
            $j.ajax({
                url: '/community/index.php',
                //url: '/profile/index/login',
                global: false,
                type: 'POST',
                data: 'CODE=011&act=Login&' + form_data,
                //data: form_data,
                dataType: "html",
                success: function( text ) {  
                    var loginXML = me.getXml_IPB( text );

                    var errors = loginXML.getElementsByTagName("error");
                    for( var i=0; errors.length>i; i++ ) {
                        alert( errors[i].firstChild.data );
                    }

                    if( errors.length == 0 ) {
                        me.Session.loadSessionByXml_IBP( loginXML );
                    
                        //TODO прорисовывваем вверху палашку
                        me.Session.repaintLoginBox( 1 );
                        
                        // Для коментариев. 
                        // во всех формах ответов прописываем строчку "вы вошли как .." 
                        $j( '.name_in_comments_form' ).html( 'Вы вошли как: ' + me.Session.displayname );

                        //me.Session.reloadPage(1);

                        // callback функция вызываемая при удачном логине
                        RBjs.ModalPopUp.execSuccesCallback();
                    } 
                }
            });   
        }
       
        this.loadSessionByXml_IBP = function( xml_obj )
        {   
            me.Session.displayname = unescape(decodeURI(me.Session.getSimpleXmlValue( xml_obj, 'displayname' )));
            me.Session.member_id = me.Session.getSimpleXmlValue( xml_obj, 'member_id' );
            me.Session.pass_hash = me.Session.getSimpleXmlValue( xml_obj, 'pass_hash' );
            me.Session.pass_hash_expire = me.Session.getSimpleXmlValue( xml_obj, 'pass_hash_expire' );
        }
       
        this.getSimpleXmlValue = function( xml_obj, tagname )
        {
            var tags = xml_obj.getElementsByTagName(tagname);
            if( tags.length>0 ) return tags[0].firstChild.data;
            else return "";
        }
        
        this.logOut = function()
        {
            RBjs.Freezer.freezeAll();
            $j.ajax({
                url: '/community/index.php',
                global: false,
                type: 'POST',
                data: 'act=Login&CODE=033',
                dataType: "html",
                success: function( loginXML ){
                    // TODO прорисовка в верхней плашки того что юзер незалогинен.
                    me.Session.repaintLoginBox( 0 );
                    
                    me.Session.Close();
                    me.Session.reloadPage(1);    
                }
            });
        }
        
        this.repaintLoginBox = function( now_loginned )
        {
            if( now_loginned ) {
                $j( '#head_login_box_display_name' ).html( me.Session.displayname );
            
                $j( '#head_login_box_n' ).hide();
                $j( '#head_login_box_y' ).show();
            } else {
                $j( '#head_login_box_display_name' ).html( '-' );
            
                $j( '#head_login_box_y' ).hide();
                $j( '#head_login_box_n' ).show();
            } 
        }
        
        this.setSessionPrms = function( prms )
        {
            me.Session.member_id        = prms['member_id'] != null ? prms['member_id'] : ''; 
            me.Session.pass_hash        = prms['pass_hash'] != null ? prms['pass_hash'] : '';
            me.Session.pass_hash_expire = prms['pass_hash_expire'] != null ? prms['pass_hash_expire'] : '';
            me.Session.is_admin         = prms['is_admin'] != null && prms['is_admin'] ? 1 : 0;
            
            try{
                me.Session.displayname  = prms['displayname'] != null ? unescape(decodeURI( prms['displayname'] ) ) : '';
            } catch(e) {
                me.Session.displayname  = '';
            }
            
            if( me.Session.member_id ) { me.Session.repaintLoginBox( 1 ) };
        }
        
        this.isAdmin = function()
        {
            return ( me.Session.is_admin ? 1 : 0 );
        }
        
        this.Close();
    
    } // END CLASS SESSION
    
    
    this.getXml_IPB = function( xmlString )
    {
        var xmlString = xmlString.replace('<?xml version="1.0" encoding="UTF-8" ?>','<?xml version="1.0" encoding="UTF-8" ?><xml>')+'</xml>';
        
        // code for IE  
        if( window.ActiveXObject ) {
            var nXML=new ActiveXObject("Microsoft.XMLDOM");
            nXML.async="false";
            nXML.loadXML(xmlString);
        } 
        // code for Mozilla, Firefox, Opera, etc.
        else {
            var parser=new DOMParser();
            var nXML=parser.parseFromString(xmlString,"text/xml");
        }
        return nXML; 
    }

    /*in old code - function rb_getNewsAnons()*/
    this.setMainTopStory = function()
    {    
        var re = new RegExp('^#[0-9]{1,10}$','i');
        var s = document.location.hash;
        
        if (!re.test(s)) {
            try {
            if (me.Cookie.get('index_news')) {
                var s = '#'+me.Cookie.get('index_news');
                me.Cookie.reset('index_news');
            if (!re.test(s)) return;
                } else return;
            } catch(e) { return; }
        }

        var link = "/__new_static/for_material_09/anons/";
        link+= s.substring(1,2)+"/";
        link+= s.substring(2,3)+"/"; 
        link+= s.substring(3,4)+"/"; 
        link+= s.substring(1)+".htm";  
        
        $j.ajax({
            url: link,
            global: false,
            type: "GET",
            dataType: "text",
            success: function( res ){
                $j('#topstory_main_div').html( res );
            }
        });
    }
    
    this.intval = function( data )
    {
        var r = parseInt( data );
        return ( isNaN(r) ? 0 : r ); 
    }
    
    this.empty = function( mix )
    {
        switch( typeof mix ) { 
            case 'object': 
            case 'array': 
                if( mix.length == null ) {
                    for (var i in mix) { return false } 
                    return true;
                } else {
                    return (mix.length == 0);
                }
            default: return !mix;
        } 
    }
    
    this.ComplaintForm = function (object_id, type)
    {
        me.cache['complaint_id'] = object_id;
        me.cache['complaint_type'] = type;
        tb_show('', '/common/complaint_form?height=300&width=442&modal=true&type=' + type, '');    
    }
    this.ComplaintSend = function()
    {
        if(me.cache['complaint_id'] && me.cache['complaint_type'])
        {
            var message = document.forms['comment_bad_form'].text.value;
            if(message.length < 4)
            {
                alert('Слишком короткое сообщение');
                return false;
            }
            
            me.cache['modal_window_id'] = $j('#TB_ajaxContent');
            
            document.forms['comment_bad_form'].sender.disable = true;
            
            $j.ajax({
                  type: "POST",
                  url: "/common/complaint_add",
                  data: {id: me.cache['complaint_id'], txt: message, type: me.cache['complaint_type']},
                  success: function(data)
                  {
                        if(data == '1')
                        {
                            $j('#form_sender', me.cache['modal_window_id']).toggleClass('hiddener');
                            $j('#success_sender', me.cache['modal_window_id']).toggleClass('hiddener');
                        }
                        document.forms['comment_bad_form'].sender.disable = false;
                  },
                  error: function()
                  {
                        document.forms['comment_bad_form'].sender.disable = false;
                  }
                });
        }
        
    }
    
    this.LoginByEnter = function(e, id)
    {
           e = (e) ? e : window.event;
           if( e.keyCode == 13 )
           {
                RBjs.Session.logIn( id );
           }           
    }
    
    this.showLoginForm = function()
    {
        tb_show('', '#TB_inline?height=380&width=270&inlineId=pupup_content&modal=true', '');
    }  
    
    
    /* from prototype 1.6 
       source: http://www.prototypejs.org/
    */
    this.cumulativeOffset = function(element)
    {
        var valueT = 0, valueL = 0;
        do {
          valueT += element.offsetTop  || 0;
          valueL += element.offsetLeft || 0;
          element = element.offsetParent;
        } while (element);
        return {'top': valueT, 'left': valueL};
    }
    
    
    
    /*  
    Opera special Fix
    Get the selected text at onmouseup, and save it. then use it later.
    */
    this.operaFixSelectedText = '';
    this.isOpera = 0;
    if( /opera/.test( navigator.userAgent.toLowerCase() ) ) {
        this.isOpera = 1;
        window.addEventListener( 
            'load',
            function() {
                if( window.getSelection || ( document.selection && document.selection.createRange ) ) {
                    document.addEventListener( 
                        'mouseup', 
                        function() {
                            var txt = window.getSelection ? window.getSelection().toString() : document.selection.createRange().text;
                            if( txt.length > 0 ) {
                                me.operaFixSelectedText = txt; 
                            } else {
                                me.operaFixSelectedText = '';
                            }
                        },
                        false
                    );
                }
            },
            false
        );
    }        
    
    this.getSelectionText = function()
    {
        if( me.isOpera ) {
            return me.operaFixSelectedText;
        } else if( window.getSelection ) {
            return window.getSelection().toString();
        } else if( document.getSelection ) {
            return document.getSelection();
        } else if (document.selection && document.selection.createRange) {
            return document.selection.createRange().text;
        } else {
            return '[bad selection]';
        }
    }
        
    this.last_sel_text = '';
    this.showMisprintForm = function()
    {
        me.last_sel_text = '' + me.getSelectionText();
        if( me.last_sel_text == '' ) {
            alert( 'Пожалуйста, выделите текст с опечаткой' );
        } else if( me.last_sel_text == '[bad selection]' ) {
            alert( 'Ваш браузер не поддерживает эту функцию.' );
        } else {
            if( me.last_sel_text.length > 300 ) {
                alert( 'Вы выделили слишком большой фрагмент текста' );
            } else {
                $j( '#misprint_seltext' ).html( me.last_sel_text );
                tb_show('', '#TB_inline?height=380&width=270&inlineId=pupup_content_misprint&modal=true', '');
            }
        }
    } 
    
    this.sendMisprintForm = function()
    {
        var data = $j( '#misprint_form').serialize();
        me.hideMisprintForm();
        data += '&misprint_sel_text=' + me.last_sel_text;
        $j.ajax({
              type: "POST",
              url: "/material/standart/misprint",
              data: data,
              success: function(data)
              { 
                if(data == 'ok') {
                    alert( 'Спасибо. Информация принята к сведению.' );
                } else {
                    alert( 'Ошибка. Попробуйте позже.' );
                }
              },
              error: function()
              {     
                alert( 'Неизвестная ошибка.' );
              }
        });
    } 
    
    this.hideMisprintForm = function()
    {
        tb_remove();
    }
}