var cssTpl = 
    '<link rel="stylesheet" type="text/css" href="#STYLE_SHEET#" />' + 
    '<!--[if lt IE 7]>' + 
    '<style type="text/css">' + 
    '#rambler-toggle .active .rambler-active-left {' + 
    '    background: none;' + 
    '    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://rs.begun.ru/tab.png", sizingMethod="crop");' + 
    '    }' + 
    '#rambler-toggle .active .rambler-active-right {' + 
    '   background: none;' + 
    '   filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://rs.begun.ru/tab-right.png", sizingMethod="crop");' + 
    '   }' + 
    '</style>' + 
    '<![endif]-->' + 
    '<link rel="stylesheet" type="text/css" href="#RAMBLER_STYLE_SHEET#" />';
   
var formTpl =
    '<div class="rambler-search-page" id="begun_rambler_searchform-out">' +
    '<div id="begun_rambler_sform">' +
    '<form onsubmit="return BEGUN_RAMBLER.search()" class="ramlerSbegun" name="#FORM_NAME#">' +
    '    <table class="ramblersbox">' +
    '        <tr class="row-0">' +
    '            <td class="left">' +
    '                <label for="q">#LABLE_TEXT#,&nbsp;</label>' +
    '            </td>' +
    '            <td class="center">' +
    '                <input type="text" class="search" value="" name="query" id="q" required>' +
    '                <div class="spacer"><!-- --></div>' +
    '            </td>' +
    '            <td class="right">' +
    '                <input type="submit" #STYLE# value="#SEARCH_TEXT#!">' +
    '            </td>' +
    '        </tr>' +
    '    </table>' +
    '</form>' +
    '</div>' +
    '</div>';
var tabsTpl =
    '<ul id="rambler-toggle">' +
    '   #TABS#' +
    '</ul>';
var activeTabTpl = 
    '<li class="tab active">' +
    '   <span class="rambler-active-left"></span>' +
    '   <strong>#LABLE# (#COUNT#)</strong>' +
    '   <span class="rambler-active-right"></span>' +
    '</li>';
var nonActiveTabTpl = 
    '<li class="tab">' +
    '   <a class="begun" href="#URL#">#LABLE# (#COUNT#)</a>' +
    '</li>'; 
var searchTpl = 
    '<ol start="#START#" class="more">' +
    '   #LINK_LIST#' +
    '</ol>';
var linkTpl = 
    '<li>' +
    '   <div class="ttl">' +
    '       <a class="begun" href="#URL#" target=_blank>#TITLE#</a>' +
    '   </div>' +
    '   <div class="text">#DESC#' +
    '   </div>' +
    '   <div class=info>http://#DOMAIN#/ - ' +
    '       <b class="green">' +
    '           <a class="begun" href="http://#DOMAIN#" target=_blank>#DOMAIN#</a>' +
    '       </b>' +
    '   </div>' +
    '</li>';
var bannersTpl = 
    '<table cellspacing="0" cellpadding="0" border="0">' +
    '   <tbody>' +
    '       <tr>' +
    '           <td>' +
    '               <span id="begunSpanTop">' +
    '                   <h1 class="begun_head">#HEADER1#</h1>' +
    '                   <table cellspacing="4" cellpadding="0" border="0">' +
    '                       <tbody>' +
    '                          #BANNER_LIST#' +         
    '                       </tbody>' +
    '                   </table>' +
    '                   <h1 class="begun_head">#HEADER2#</h1>' +
    '               </span>' +
    '           </td>' +
    '       </tr>' +
    '   </tbody>' +
    '</table>';
var bannerTpl = 
    '<tr valign="top">' +
    '   <td width="4" nowrap="nowrap" />' +
    '   <td />' +
    '   <td style="padding-left: 24px;">' +
    '       <ul style="margin: 0px; padding: 0px; list-style-type: disc;">' +
    '           <li style="color: rgb(0, 51, 153);">' +
    '               <div style="font-size: 100%;" class="text">' +
    '                   <a class="begun" target="_blank" href="#URL#">#TITLE#</a>' +
    '                   <div style="color: rgb(0, 0, 0);" class="text">' +
    '                       <a class="begun" style="text-decoration: none; color: rgb(0, 0, 0);" target="_blank" href="#URL#">' +
    '                           #DESC#' +
    '                       </a>  -   ' +
    '                       <span><a class="begun BegunAGreen" target="_blank" href="#URL#" style="white-space: nowrap;"><b>#DOMAIN#</b></a></span>' +
    '                   </div>' +
    '               </div>' +
    '           </li>' +
    '       </ul>' +
    '   </td>' +
    '   <td width="15" />' +
    '</tr>';
var pagesTpl =
    '<div class="groups">' +
    '   <span class="red">#PAGES_LABLE#:</span> &nbsp;' +
    '   #PAGES_LIST#' +
    '</div>';
var curPageTpl = 
    '<span class="current"> #PAGE_NUM# </span> &nbsp;';
var pageTpl = 
    ' <a class="begun" href="##PAGE_NUM#" onClick="return BEGUN_RAMBLER.goToPage( #TO_PAGE# )">#PAGE_NUM#</a> &nbsp;';

var BEGUN_RAMBLER = new BEGUN_RAMBLER(begun_rambler_pad_id);

//------------------------------------------------------------------------------
// Coonfiguration
//------------------------------------------------------------------------------

if (typeof begun_rambler_stylesheet != 'undefined' && begun_rambler_stylesheet) {
    BEGUN_RAMBLER.styleSheetUrl = begun_rambler_stylesheet;
}

if (typeof begun_rambler_result_div != 'undefined' && begun_rambler_result_div) {
    BEGUN_RAMBLER.htmlObjects.search_result_div = begun_rambler_result_div;
}

var colorReg = new RegExp('^#[0-9a-fA-F]{6}$');

if (typeof(begun_search_background) != 'undefined' && colorReg.test(begun_search_background)) {
    BEGUN_RAMBLER.htmlObjects.search_background = begun_search_background;
}

if (typeof(begun_search_font_color) != 'undefined' && colorReg.test(begun_search_font_color)) {
    BEGUN_RAMBLER.htmlObjects.search_font_color = begun_search_font_color;
}

BEGUN_RAMBLER.start();

//------------------------------------------------------------------------------
// BEGUN_RAMBLER
//------------------------------------------------------------------------------
function BEGUN_RAMBLER(pad_id)
{
    this.pad_id             = pad_id;
    this.siteLinksList      = null;
    this.ramblerLinksList   = null;
    this.bannersList        = null;
    this.siteFoundTotal     = null;
    this.ramblerFoundTotal  = null;
    this.ramblerPage        = 0;
    this.sitePage           = 0;
    this.timeout            = 60;
    this.linksLimit         = 15;
    this.bannersLimit       = 5;
    this.pageGroupSize      = 10;
    this.timeoutFeedFail    = false;
    this.intervalShowFeed   = false;
    this.ramblerStyleSheet  = 'http://rs.begun.ru/rambler.css';
    this.styleSheetUrl      = 'http://rs.begun.ru/search.css';
    this.searchFeedUrl      = 'http://rs.begun.ru/rambler_search.php';
    this.ramblerImageSmall  = 'http://rs.begun.ru/rambler_small.gif';
    this.currentQuery       = null;
    this.currentReferer     = window.location.hostname + window.location.pathname;
    this.currentSelection   = 'both';
    this.messages           = {
        //zakodirovannie russkie slova
        //...<zagruzka>...
        proccess:               '...' + decodeURIComponent('%D0%B7%D0%B0%D0%B3%D1%80%D1%83%D0%B7%D0%BA%D0%B0') + '...',
        //<Net zaprosa.>
        emptyQuery:             decodeURIComponent('%D0%9D%D0%B5%D1%82%20%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81%D0%B0.'),
        //<Ne naideno ni odnogo documenta, polnostyu sootvetstvuyushego zaprosu>
        emptyResult:            decodeURIComponent('%D0%9D%D0%B5%20%D0%BD%D0%B0%D0%B9%D0%B4%D0%B5%D0%BD%D0%BE%20%D0%BD%D0%B8%20%D0%BE%D0%B4%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%2C%20%D0%BF%D0%BE%D0%BB%D0%BD%D0%BE%D1%81%D1%82%D1%8C%D1%8E%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D1%8E%D1%89%D0%B5%D0%B3%D0%BE%20%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81%D1%83.'),
        //<Poprobuite eshe raz.>
        feedFail:               decodeURIComponent('%D0%9F%D0%BE%D0%BF%D1%80%D0%BE%D0%B1%D1%83%D0%B9%D1%82%D0%B5%20%D0%B5%D1%89%D0%B5%20%D1%80%D0%B0%D0%B7.'),
        error:                  {
            //<Neizvestnaya oshibka>
            0:  decodeURIComponent('%D0%9D%D0%B5%D0%B8%D0%B7%D0%B2%D0%B5%D1%81%D1%82%D0%BD%D0%B0%D1%8F%20%D0%BE%D1%88%D0%B8%D0%B1%D0%BA%D0%B0.'),
            //<Oshibka polycheniya dannih>
            1:  decodeURIComponent('%D0%9E%D1%88%D0%B8%D0%B1%D0%BA%D0%B0%20%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85.')
        }
    }
    this.htmlObjects        = {
        logo:                   'begun_rambler_logo',
        form:                   'begun_rambler_search_form',
        search_form_div:        'begun_rambler_search_form_div',
        search_query:           'begun_rambler_search_query',
        search_button:          'begun_rambler_search_button',
        everywhere_button_ok:   'begun_rambler_everywhere_button_ok',
        everywhere_button_no:   'begun_rambler_everywhere_button_no',
        search_result_div:      'begun_rambler_search_result_div',
        banners_header:         'begun_rambler_banners_header',
        banners_list:           'begun_rambler_banners_list',
        result_header:          'begun_rambler_result_header',
        result_list:            'begun_rambler_result_list',
        pager:                  'begun_rambler_pager',
        message:                'begun_rambler_message',
        empty_result:           'begun_rambler_empty_result',
        prev_page:              'begun_rambler_prev_page',
        next_page:              'begun_rambler_next_page',
        search_background:      '#D4D0C7',
        search_font_color:      '#777777'
    }
    
    
    //--------------------------------------------------------------------------
    // Start
    //--------------------------------------------------------------------------
    this.start = function()
    {
        var paramQuery = false;
        var paramReferer = false;
        var parameters = window.location.search.split( '&' );
        for ( var i in parameters ) {
            var value = parameters[ i ];
			if (typeof value != "string") continue;
            if ( i == 0 ) {
                value = value.substr( 1 );
            }
            var pair = value.split( '=', 2 );
            if ( pair[ 0 ] == 'query' ) {
                paramQuery = this.urlDecode( pair[ 1 ] );
            }
            if ( pair[ 0 ] == 'selection' ) {
                this.currentSelection = pair[1];
            }
        }
        this.showForm();
        var queryTpl = new RegExp( '^[\\s]*$' );
        if ( paramQuery && ! queryTpl.test( paramQuery ) ) {
            this.currentQuery = unescape(paramQuery);
            this.query();
        }
    }

    //--------------------------------------------------------------------------
    // Show form
    //--------------------------------------------------------------------------
    this.showForm = function()
    {
        var search_text = decodeURIComponent('%D0%B8%D1%89%D0%B8');
        var lable_text = decodeURIComponent('%D0%A0%D0%B0%D0%BC%D0%B1%D0%BB%D0%B5%D1%80');
        
        
        var cssTemplate = new BEGUN_Template(cssTpl);
        cssTemplate.assign('STYLE_SHEET', this.styleSheetUrl);
        cssTemplate.assign('RAMBLER_STYLE_SHEET', this.ramblerStyleSheet);
        cssTemplate.display();
        if (window.opera && ("BackCompat" == document.compatMode)) {
            var style = 'style="position:relative; margin-left: -24px;"';
            
        } else {
            var style = '';
        }
        
        var formTemplate = new BEGUN_Template(formTpl);
        formTemplate.assign('FORM_NAME', this.htmlObjects.form);
        formTemplate.assign('SEARCH_BACKGROUND', this.htmlObjects.search_background);
        formTemplate.assign('LABLE_TEXT', lable_text);
        formTemplate.assign('STYLE', style);
        formTemplate.assign('RAMBLER_IMG', this.ramblerImageSmall);
        formTemplate.assign('SEARCH_TEXT', search_text);
        formTemplate.display();
    }

    //--------------------------------------------------------------------------
    // On submit
    //--------------------------------------------------------------------------
    this.search = function()
    {
        this.sitePage       = 0;
        this.ramblerPage    = 0;
        this.currentQuery   = null;
        this.currentSelection = 'both';
        var form = window.document.forms[ this.htmlObjects.form ];
        if ( form ) {
            var queryTpl = new RegExp( '^[\\s]*$' );
            var paramQuery = form.elements.query.value;
            if ( queryTpl.test( paramQuery ) ) {
                this.showMessage( this.messages.emptyQuery );
                return false;
            }
            this.currentQuery = paramQuery;
            this.query();
        }
        return false;
    }
    //--------------------------------------------------------------------------
    // On tab click
    //--------------------------------------------------------------------------
    this.tabSearch = function(type)
    {
        this.sitePage           = 0;
        this.ramblerPage        = 0;
        this.currentSelection   = type; 
        var form = window.document.forms[ this.htmlObjects.form ];
        this.query();
    }
    //--------------------------------------------------------------------------
    // Get feed and show result
    //--------------------------------------------------------------------------
    this.query = function()
    {
        var thisObject = this;
        var url = this.searchFeedUrl;
        url += '?pad_id=' + this.pad_id;
        url += '&query=' + escape(this.currentQuery);
        url += '&rambler_page=' + this.ramblerPage;
        url += '&site_page=' + this.sitePage;
        url += '&begun_limit=' + this.bannersLimit;
        url += '&rambler_limit=' + this.linksLimit;
        url += '&site_limit=' + this.linksLimit;
        url += '&referer=' + this.currentReferer;
        if ( this.timeoutFeedFail ) {
            clearTimeout( this.timeoutFeedFail );
            this.timeoutFeedFail = false;
        }
        this.showMessage( this.messages.proccess );
        this.ramblerLinksList   = new Array();
        this.siteLinksList      = new Array();
        this.bannersList        = new Array();
        this.siteFoundTotal     = 0;
        this.ramblerFoundTotal  = 0;
        this.getFeed( url );
        this.timeoutFeedFail = setTimeout(
            function(){ thisObject.feedFail() },
            this.timeout * 1000
        );
        return true;
    }

    //--------------------------------------------------------------------------
    // Show message
    //--------------------------------------------------------------------------
    this.showMessage = function( text )
    {
        var divResult = document.getElementById( this.htmlObjects.search_result_div );
        if ( divResult ) {
            while ( divResult.firstChild ) {
                divResult.removeChild( divResult.firstChild );
            }
            divResult.appendChild( this.createHTMLElement( 'DIV', this.htmlObjects.message, text ) );
        }
    }

    //--------------------------------------------------------------------------
    // Feed failed event
    //--------------------------------------------------------------------------
    this.feedFail = function()
    {
        if ( this.timeoutFeedFail ) {
            clearTimeout( this.timeoutFeedFail );
            this.timeoutFeedFail = false;
        }
        this.showMessage( this.messages.feedFail );
    }

    //--------------------------------------------------------------------------
    // Data loaded event
    //--------------------------------------------------------------------------
    this.load = function()
    {
        if ( this.timeoutFeedFail ) {
            clearTimeout( this.timeoutFeedFail );
            this.timeoutFeedFail = false;
        }
        if ( this.error != 0 ) {
            if ( this.messages.error[ this.error ] != null ) {
                this.showMessage( this.messages.error[ this.error ] + ' ' + this.messages.feedFail );
            } else {
                this.showMessage( this.messages.error[ 0 ] + ' ' + this.messages.feedFail );
            }
            return false;
        }

        this.trySetForm();
        this.tryShowFeed();
    }

    //--------------------------------------------------------------------------
    // Try show feed
    //--------------------------------------------------------------------------
    this.tryShowFeed = function()
    {
        var thisObject = this;
        this.intervalShowFeed = setInterval(
            function()
            {
                var container = document.getElementById( thisObject.htmlObjects.search_result_div );
                if ( container ) {
                    clearInterval( thisObject.intervalShowFeed );
                    thisObject.showFeed( container );
                }
            },
            100
        );
    }

    //--------------------------------------------------------------------------
    // Try set form fields
    //--------------------------------------------------------------------------
    this.trySetForm = function()
    {
        var form = window.document.forms[ this.htmlObjects.form ];
        if ( form ) {
            this.currentQuery = decodeURIComponent(this.currentQuery);
            form.elements.query.value = this.currentQuery;
        }
    }

    //--------------------------------------------------------------------------
    // Show feed
    //--------------------------------------------------------------------------
    this.showFeed = function( container )
    {
        container.innerHTML = '';
        //----------------------------------------------------------------------
        // tabs
        //----------------------------------------------------------------------
        
        var tabsTemplate = new BEGUN_Template(tabsTpl);
        var activTabTemplate = new BEGUN_Template(activeTabTpl);
        var nonActivTabTemplate = new BEGUN_Template(nonActiveTabTpl);
        if(this.currentSelection == 'site' || this.currentSelection == 'both') {
            activTabTemplate.assign('COUNT', this.siteFoundTotal);
            activTabTemplate.assignEncoded('LABLE', '%D0%9D%D0%B0%20%D1%81%D0%B0%D0%B9%D1%82%D0%B5');
            tabsTemplate.add('TABS', activTabTemplate.tpl);
            
            nonActivTabTemplate.assign('COUNT', this.ramblerFoundTotal);
            nonActivTabTemplate.assignEncoded('LABLE', '%D0%9D%D0%B0%20%D0%A0%D0%B0%D0%BC%D0%B1%D0%BB%D0%B5%D1%80%D0%B5');
            nonActivTabTemplate.assign('URL', 'javascript: BEGUN_RAMBLER.tabSearch(\'rambler\')');
            tabsTemplate.add('TABS', nonActivTabTemplate.tpl);
            
        } else {
            nonActivTabTemplate.assign('COUNT', this.siteFoundTotal);
            nonActivTabTemplate.assignEncoded('LABLE', '%D0%9D%D0%B0%20%D1%81%D0%B0%D0%B9%D1%82%D0%B5');
            nonActivTabTemplate.assign('URL', 'javascript: BEGUN_RAMBLER.tabSearch(\'site\')');
            tabsTemplate.add('TABS', nonActivTabTemplate.tpl);
            
            activTabTemplate.assign('COUNT', this.ramblerFoundTotal);
            activTabTemplate.assignEncoded('LABLE', '%D0%9D%D0%B0%20%D0%A0%D0%B0%D0%BC%D0%B1%D0%BB%D0%B5%D1%80%D0%B5');          
            tabsTemplate.add('TABS', activTabTemplate.tpl);
        }
        tabsTemplate.parse('TABS');
        container.innerHTML += tabsTemplate.tpl;
        //----------------------------------------------------------------------
        // banners
        //----------------------------------------------------------------------
        var bTopList = new BEGUN_Template(bannersTpl);
        var bBootomList = new BEGUN_Template(bannersTpl);
        if ( this.bannersList.length > 0 ) {
            //----------------------------------------------------------------------
            // banners top
            //----------------------------------------------------------------------
            
            bTopList.assignEncoded('HEADER1', '%D0%9A%D0%BE%D0%BD%D1%82%D0%B5%D0%BA%D1%81%D1%82%D0%BD%D1%8B%D0%B5%20%D0%BE%D0%B1%D1%8A%D1%8F%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F');
            bTopList.assignEncoded('HEADER2', '%D0%A0%D0%B5%D0%B7%D1%83%D0%BB%D1%8C%D1%82%D0%B0%D1%82%D1%8B%20%D0%BF%D0%BE%D0%B8%D1%81%D0%BA%D0%B0');
            for(var i =0; i < 3 && i < this.bannersList.length; i++) {
                bTopList.add('BANNER_LIST', this.bannersList[i].createHTML());
            }
            bTopList.parse('BANNER_LIST');
            //----------------------------------------------------------------------
            // banners bottom
            //----------------------------------------------------------------------
            if(this.bannersList.length > 3) {
                bBootomList.assignEncoded('HEADER1', '%D0%9A%D0%BE%D0%BD%D1%82%D0%B5%D0%BA%D1%81%D1%82%D0%BD%D1%8B%D0%B5%20%D0%BE%D0%B1%D1%8A%D1%8F%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F');
                bBootomList.assignEncoded('HEADER2', '');
                for(i = 3 ; i < this.bannersList.length ; i++) {
                    bBootomList.add('BANNER_LIST', this.bannersList[i].createHTML());
                }
                bBootomList.parse('BANNER_LIST');
            } else {
                bBootomList.tpl = '';
            }
            
        } else {
            bTopList.tpl = '';
            bBootomList.tpl = '';
        }
        
        //----------------------------------------------------------------------
        // rambler
        //----------------------------------------------------------------------
        var olLinks = new BEGUN_Template(searchTpl);
        var start = 0;
        if(this.currentSelection == 'site' || this.currentSelection == 'both') {
            start = this.sitePage * this.linksLimit + 1;
        } else {
            start = this.ramblerPage * this.linksLimit + 1;
        }
        olLinks.assign('START', start);
        
        if(this.currentSelection == 'rambler') {
            for ( var i in this.ramblerLinksList ) {
                if (this.ramblerLinksList[ i ] && this.ramblerLinksList.hasOwnProperty && this.ramblerLinksList.hasOwnProperty(i)) olLinks.add('LINK_LIST', this.ramblerLinksList[ i ].createHTML())
            }
        }
        if(this.currentSelection == 'site' || this.currentSelection == 'both') {
            for ( var i in this.siteLinksList ) {
                if (this.siteLinksList[ i ] && this.siteLinksList.hasOwnProperty && this.siteLinksList.hasOwnProperty(i)) olLinks.add('LINK_LIST', this.siteLinksList[ i ].createHTML())
            }
        }
        olLinks.parse('LINK_LIST');

        container.innerHTML += bTopList.tpl;
        if (
            this.currentSelection == 'both' && 
            this.siteLinksList.length
        ) {
            container.innerHTML += olLinks.tpl;
        } else if (
            this.currentSelection == 'rambler' && 
            this.ramblerLinksList.length
        ) {
            container.innerHTML += olLinks.tpl;
        } else if (
            this.currentSelection == 'site' && 
            this.siteLinksList.length
        ) {
            container.innerHTML += olLinks.tpl;
        } else {
            container.appendChild(
                this.createHTMLElement(
                    'DIV',
                    this.htmlObjects.empty_result,
                    this.messages.emptyResult
                )
            );
            return;
        }
        
        var topPager = this.createHTMLPager();
        if ( topPager ) {
            container.innerHTML +=topPager ;
        }
        container.innerHTML += bBootomList.tpl;
    }

    //--------------------------------------------------------------------------
    // Tag create with id and text
    //--------------------------------------------------------------------------
    this.createHTMLElement = function( tag, id, text )
    {
        var result = document.createElement( tag );
        if ( id ) {
            result.id = id;
        }
        if ( text ) {
            result.appendChild( document.createTextNode( text ) );
        }
        return result;
    }

    //--------------------------------------------------------------------------
    // Pager
    //--------------------------------------------------------------------------
    this.createHTMLPager = function()
    {
        var totalFound = 0;
        var page = 0;
        
        var pagesTemplate = new BEGUN_Template(pagesTpl);
        pagesTemplate.assignEncoded('PAGES_LABLE', decodeURIComponent('%D0%A1%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D1%8B'));
        
        if(this.currentSelection == 'both' || this.currentSelection == 'site') {
            totalFound = this.siteFoundTotal;
            page = this.sitePage;
            
        } else {
            page = this.ramblerPage;
            totalFound = this.ramblerFoundTotal;
        }
        var pagesCount = Math.ceil( totalFound / this.linksLimit );
        
        if ( totalFound < this.linksLimit ) {
            return false;
        }
        var pageGroup = Math.floor( page / this.pageGroupSize );
        var startPage = ( pageGroup ) * this.pageGroupSize;
        var lastPage  = ( pageGroup + 1 ) * this.pageGroupSize;
        if ( pagesCount < lastPage ) {
            lastPage = pagesCount;
        }
        
        if ( page > 0 ) {
            var prevPage = new BEGUN_Template(pageTpl);
            prevPage.assign('PAGE_NUM', '&lt;&lt;');
            prevPage.assign('TO_PAGE', page-1);
            pagesTemplate.add('PAGES_LIST', prevPage.tpl);
            
        }
        
        for ( var i = startPage; i < lastPage; i++ ) {
            if ( i == page ) {
                var cPage = new BEGUN_Template(curPageTpl);
                cPage.assign('PAGE_NUM', i+1);
                pagesTemplate.add('PAGES_LIST', cPage.tpl);
            } else {
                var cPage = new BEGUN_Template(pageTpl);
                cPage.assign('PAGE_NUM', i+1);
                cPage.assign('TO_PAGE', i);
                pagesTemplate.add('PAGES_LIST', cPage.tpl);
            }
        }
        
        if ( page < pagesCount-1) {
            var nextPage = new BEGUN_Template(pageTpl);
            nextPage.assign('PAGE_NUM', '&gt;&gt;');
            nextPage.assign('TO_PAGE', page+1);
            pagesTemplate.add('PAGES_LIST', nextPage.tpl);
        }
        
        pagesTemplate.parse('PAGES_LIST');
        
        return pagesTemplate.tpl;
    }

    //--------------------------------------------------------------------------
    // go to page
    //--------------------------------------------------------------------------
    this.goToPage = function( num )
    {
        if ( this.currentQuery ) {
            if(this.currentSelection == 'both' || this.currentSelection == 'site') {
                this.sitePage = num;
            } else {
                this.ramblerPage = num;
            }
            this.query();
        }
        return false;
    }

    //--------------------------------------------------------------------------
    // Add Banner
    //--------------------------------------------------------------------------
    this.addBanner = function( title, url, description, domain )
    {
        if(title != '') {
            title = decodeURIComponent(title);
        }
        if(description != '') {
            description = decodeURIComponent(description);
        }
        this.bannersList.push(
            new BEGUN_Banner(
                title,
                url,
                description,
                domain
            )
        );
    }

    //--------------------------------------------------------------------------
    // Add Rambler
    //--------------------------------------------------------------------------
    this.addLink = function( title, url, description, domain, type )
    {
        if(title != '') {
            title = decodeURIComponent(title);
        }
        if(description != '') {
            description = decodeURIComponent(description);
        }
        if(type == 'rambler') {
            this.ramblerLinksList.push(
                new BEGUN_Link(
                    title,
                    url,
                    description,
                    domain
                )
            );
        } else {
            this.siteLinksList.push(
                new BEGUN_Link(
                    title,
                    url,
                    description,
                    domain
                )
            );    
        }
        
    }

    //--------------------------------------------------------------------------
    // Get feed
    //--------------------------------------------------------------------------
    this.getFeed = function( url )
    {
        this.error = 0;
        if ( document.readyState != null && document.readyState != 'complete' )
        {
            // for IE (if document not loaded)
            var script = '';
            script += '<S' + 'CRIPT type="text/javascript"';
            script += 'src="' + url + '"></S' + 'CRIPT>';
            document.write( script );
        } else {
            var body, span, script, load;
            body = document.getElementsByTagName( 'BODY' )[ 0 ];
            if ( ! body ) {
                body = document.firstChild;
            }
            if ( body ) {
                span = document.createElement( 'SPAN' );
                span.style.display = 'none';
                span.innerHTML = 'BEGUN SCRIPT!<S' + 'CRIPT></S' + 'CRIPT>';
                script = span.getElementsByTagName( 'SCRIPT' )[ 0 ];
                script.language = 'JavaScript';
                load = function() {
                    if ( script.setAttribute ) {
                        script.setAttribute( 'src', url )
                    } else {
                        script.src = url;
                    }
                    setTimeout( function() { span.parentNode.removeChild( span ) }, 5 );
                }
                setTimeout( load, 5 );
                body.appendChild( span );
            }
        }
    }

    //--------------------------------------------------------------------------
    // Url decode
    //--------------------------------------------------------------------------
    this.urlDecode = function( value )
    {
        var result = '';
        var charMap = unescape(
            '%u0402%u0403%u201A%u0453%u201E%u2026%u2020%u2021%u20AC%u2030%u0409%u2039%u040A%u040C%u040B%u040F' +
            '%u0452%u2018%u2019%u201C%u201D%u2022%u2013%u2014%u0000%u2122%u0459%u203A%u045A%u045C%u045B%u045F' +
            '%u00A0%u040E%u045E%u0408%u00A4%u0490%u00A6%u00A7%u0401%u00A9%u0404%u00AB%u00AC%u00AD%u00AE%u0407' +
            '%u00B0%u00B1%u0406%u0456%u0491%u00B5%u00B6%u00B7%u0451%u2116%u0454%u00BB%u0458%u0405%u0455%u0457'
        )
        // From win-1251 to unicode
        var convert = function( code )
        {
            if( code >= 0xC0 && code <= 0xFF ) {
                return String.fromCharCode( code - 0xC0 + 0x0410 );
            }
            if( code >= 0x80 && code <= 0xBF ) {
                return charMap.charAt( code - 0x80 );
            }
            return String.fromCharCode( code );
        }
        value = unescape( value );
        for( var i = 0; i < value.length; i++ ) {
            result = result + convert( value.charCodeAt( i ) );
        }
        return result;
    }
}

//------------------------------------------------------------------------------
// BEGUN_Banner
//------------------------------------------------------------------------------
function BEGUN_Banner(title, url, description, domain )
{
    this.title          = title;
    this.url            = url;
    this.description    = description;
    this.domain         = domain;

    //--------------------------------------------------------------------------
    // Create HTML
    //--------------------------------------------------------------------------
    this.createHTML = function()
    {
        var bannerTemplate = new BEGUN_Template(bannerTpl);
        bannerTemplate.assign('TITLE', title);
        bannerTemplate.assign('URL', url);
        bannerTemplate.assign('DESC', description);
        bannerTemplate.assign('DOMAIN', domain);
        return bannerTemplate.tpl;
    }
}

//------------------------------------------------------------------------------
// BEGUN_Link
//------------------------------------------------------------------------------
function BEGUN_Link(title, url, description, domain )
{
    this.title          = title;
    this.url            = url;
    this.description    = description;
    this.domain         = domain;

    //--------------------------------------------------------------------------
    // Create HTML
    //--------------------------------------------------------------------------
    this.createHTML = function()
    {
        var linkTemplate = new BEGUN_Template(linkTpl);
        linkTemplate.assign('TITLE', title);
        linkTemplate.assign('URL', url);
        linkTemplate.assign('DESC', description);
        linkTemplate.assign('DOMAIN', domain);
        return linkTemplate.tpl;
    }
}
//---------------------------------------------------
// Templates
//---------------------------------------------------
function BEGUN_Template(tpl) {
    
    this.tpl    = tpl;
    this.vars   = new Array();
    
    this.assign = function(variable, value) {
        if(this.tpl != null) {
            var pattern = new RegExp('#' + variable + '#', 'g');
            this.tpl = this.tpl.replace(pattern, value);
        }
    }
    
    this.assignEncoded = function(variable, value) {
        if(this.tpl != null) {
            var pattern = new RegExp('#' + variable + '#', 'g');
            this.tpl = this.tpl.replace(pattern, decodeURIComponent(value));
        }
    }
    
    this.add = function(variable, value) {
        if(typeof this.vars[variable] == 'undefined') {
            this.vars[variable] = '';
        }
        this.vars[variable] += value; 
    }
    
    this.parse = function(variable) {
        if(this.tpl != null && typeof this.vars != 'undefined') {
            var pattern = new RegExp('#' + variable + '#', 'g');
            this.tpl = this.tpl.replace(pattern, this.vars[variable]);
        }     
    }
     
    this.display = function() {
        if(this.tpl != null) {
            document.write(this.tpl);
        }
    }
}
