﻿function addAttribute( to, name, value )
{
    switch( name.toLowerCase() )
    {
        case 'class':
            to.setAttribute( "class", value );
            to.className = value;
            return true;
        case 'for':
            to.htmlFor = value;
            return true;
		default: break;
    }

    if ( to.setAttribute ) to.setAttribute( name.toUpperCase(), value, false );
    else if ( document.createAttribute )
    {
        var newAttr = document.createAttribute();
        newAttr.nodeName = name.toUpperCase();
        newAttr.nodeValue = value;
        to.setAttributeNode( newAttr );
    }
}
function copyAttributes( from, to )
{
    for ( var i = 0; i < from.attributes.length; i++ )
    {
        var attr = from.attributes[ i ];
        if ( attr.nodeValue )
        {
            addAttribute( to, attr.nodeName, attr.nodeValue );
        }
    }
}

var Html =
{
    XMLtoDOM: function( from, to )
    {
        var node = null, elem = null;
        for( var i=0; i < from.childNodes.length; i++ )
        {
            elem = from.childNodes[i];			
            if ( elem.nodeType == 1 )
            {
                node = new Html.DOMNode( elem );
                this.XMLtoDOM( elem, node );
                to.appendChild( node );
            }
            else if (  elem.nodeType == 3 || elem.nodeType == 4 )
            {
				try{
                to.appendChild( document.createTextNode( elem.nodeValue ) );
				} catch( e ) {window.status = elem.nodeValue + elem.nodeName + elem;}
            }
        }
    }
};

Html.DOMNode = function( from )
{
    var node = document.createElement( from.nodeName );
    copyAttributes( from, node );

    return node;
};

var Imho = {};

Imho.Guestbook =
{
    form: null,
    formLayout: null,
    formContainer: null,
    formErrorContainer: null,

    messages: {}, // Cache
    messageCounter: 0,
    msgContainer: null,
    msgNewInformer: null,
    msgTotalCounter: null,

    formTextArea: null,
    timer: null,

    workerPath: Core.Guestbook.worker,
    getSelectedDate: function()
    {
        if( location.hash.length === 0 ) return '';
        var date = '';
        var hash = location.hash.substring(2);

        if( Imho.Guestbook.Search.isActive() ) return '';

        var hashArr = hash.split('/');
        if( hash.substring( hash.length - 1 ) != '/' ) hash += '/';

        // 2004/2/ || empty
        if( hashArr.length < 3 || hashArr.length === 0 ) return '';
        // 2004/03/02/2/
        if( hashArr.length == 5 )
        {
            Imho.Guestbook.Pager.currentPage = hashArr[3];
            return hashArr[0] + '/' + hashArr[1] + '/' + hashArr[2] + '/';
        }

        return hash;
    },

    load: function( from )
    {
        //var request = new Http.Request( '/netcat/add.php', {catalogue:1,sub:439,cc:520} );
        Imho.Guestbook.workerPath = Core.Guestbook.worker + Imho.Guestbook.getSelectedDate();

        var params = {getmessages:'true'};
        if( Imho.Guestbook.Search.isActive() )
        {
            Imho.Guestbook.Search.fillFormByParamsFromUri();
            params = Imho.Guestbook.Search.getSearchParams();
        }
        if ( !Imho.Guestbook.form ) params[ 'getform' ] = true;
        params['curPos'] = Imho.Guestbook.Pager.getParamValue();

        var request = new Http.Request( Imho.Guestbook.workerPath, params );
        request.onComplete = Imho.Guestbook.parseXML;
        request.send( true );

        if ( Imho.Guestbook.msgNewInformer ) Imho.Guestbook.msgNewInformer.style.display = 'none';
        if ( !Imho.Guestbook.timer ) Imho.Guestbook.timer = setInterval( Imho.Guestbook.sendNewMessagesTest, 30000 );
    },

    parseXML: function(  responce  )
    {
        Imho.Guestbook.Loading.hide();

        if ( !responce ) return false;

        var xml = responce.getXML();
        if ( !xml || !xml.getElementsByTagName( 'imho-responce' ) ) return false;

        Imho.Guestbook.showErrors( xml );

        if ( !Imho.Guestbook.form ) Imho.Guestbook.parseForm( xml );

        var total = xml.getElementsByTagName( 'total' )[0];
        if ( total && total.firstChild )
        {
            Imho.Guestbook.parseMessages( xml );
            Imho.Guestbook.showMessages();
        }

        Imho.Guestbook.Pager.build( xml );
    },
    parseForm: function(  xml  )
    {
        var root = xml.getElementsByTagName( 'message-form' )[0];
        if( root && !root.getElementsByTagName( 'error' )[0] )
        {
            this.form = document.createElement( 'DIV' );
            Html.XMLtoDOM( root, Imho.Guestbook.form );
        }
        if ( !this.form ) return false;
        this.showForm();
    },
    showForm: function()
    {
        if ( !this.formLayout ) this.formLayout = document.getElementById('gbFormLayout');
        if ( !this.formLayout ) return false;
        if ( !this.formContainer ) this.formContainer = document.getElementById('gbForm');
        if ( !this.formContainer ) return false;
        this.formLayout.style.display = ( this.form.firstChild ) ? 'block' : 'none';

        this.formTextArea = this.form.getElementsByTagName('TEXTAREA')[0];
        if ( this.formTextArea ) this.formTextArea.onkeydown = Imho.Guestbook.onTextareaKeyDown;
        this.formContainer.appendChild( this.form );
    },
    parseMessages: function( xml )
    {
        var messages = xml.getElementsByTagName( 'message' );
        var msg = null;

        this.messageCounter = xml.getElementsByTagName( 'total' )[0].firstChild.nodeValue;
        for( var i = messages.length - 1; i >= 0; i-- )
        {
            msg = new Imho.Guestbook.Message( messages[i] );
            if ( this.messages[ 'id_' + msg.id ] ) continue;
            this.messages[ 'id_' + msg.id ] = msg;
        }
    },
    showMessages: function()
    {
		if ( !this.msgContainer ) this.msgContainer = document.getElementById('gbMessages');
        if ( !this.msgContainer ) return false;

        if ( !this.msgTotalCounter ) this.msgTotalCounter = document.createElement( 'DIV' );
        this.msgTotalCounter.className = 'total';
        this.msgTotalCounter.innerHTML = 'Всего сообщений: ' + this.messageCounter.bold();
        //this.msgTotalCounter.appendChild( document.createTextNode( 'Всего сообщений: ' + this.messageCounter ) );

        if ( this.msgContainer.childNodes.length === 0 )
        {
            this.msgContainer.appendChild( this.msgTotalCounter );
        }

        for( var i in this.messages )
        {
            if( this.messages[i].shown ) continue;
            if( this.msgContainer.childNodes.length == 1 )
                this.msgContainer.appendChild( this.messages[i].getHTML() );
            else
            {
                this.msgContainer.insertBefore( this.messages[i].getHTML(), this.msgContainer.childNodes[1] );
            }
            this.messages[i].shown = true;
        }
    },

    addPost: function()
    {
		if ( !this.msgContainer ) this.msgContainer = document.getElementById('gbMessages');
        if ( !this.msgContainer ) return false;
        var params = {};
        var form = this.formContainer.parentNode;
        if( !form || form.nodeName != 'FORM' ) return false;

        for( var i = 0; i < form.elements.length; i++ )
        {
			if( form.elements[i].type != 'checkbox' || form.elements[i].checked )
			{
                params[ form.elements[i].name ] = form.elements[i].value;
            }
        }
        var request = new Http.Request( form.action, params, 'POST' );
        request.onComplete = Imho.Guestbook.checkPost;
        request.send( true );

        if ( !Imho.Guestbook.formTextArea ) Imho.Guestbook.formTextArea = Imho.Guestbook.form.getElementsByTagName('TEXTAREA')[0];
        if ( !Imho.Guestbook.formTextArea ) return false;

        Imho.Guestbook.formTextArea.value = '';
        document.getElementById('f4').checked = false;

        return false;
    },
    checkPost: function( responce )
    {
        var xml = responce.getXML().getElementsByTagName( 'imho-responce' )[0];
		if( !xml ) return false;

        Imho.Guestbook.showErrors( xml );

        location.href = Core.Guestbook.root + '#' + Imho.Guestbook.Today.toString();

        var status = xml.getElementsByTagName( 'status' )[0];

        if ( status )
        {
//            if( Imho.Guestbook.Pager.isShown() ) Imho.Guestbook.Pager.go( Imho.Guestbook.Pager.next, 0 );
            Imho.Guestbook.Pager.currentPage = 0;
            Imho.Guestbook.clear();
            Imho.Guestbook.load();
            Imho.Guestbook.Calendar.reload();
        }
    },

    showErrors: function( xml )
    {
        if( !this.formErrorContainer ) this.formErrorContainer = document.getElementById('gbFormError');
        if( !this.formErrorContainer ) return false;
        var error = xml.getElementsByTagName( 'error' )[0];
        if( error )
        {

            var errorContainer = document.createElement( 'DIV' );
            Html.XMLtoDOM( error, errorContainer );
            this.formErrorContainer.innerHTML = '';
            this.formErrorContainer.appendChild( errorContainer );
            this.formErrorContainer.style.display = 'block';
        }
        else
        {
            this.formErrorContainer.innerHTML = '';
            this.formErrorContainer.style.display = 'none';
        }
    },

    reply: function( to )
    {
        if ( !this.formTextArea ) this.formTextArea = this.form.getElementsByTagName('TEXTAREA')[0];
        if ( !this.formTextArea ) return false;

        this.formTextArea.focus();
        this.formTextArea.value += "Ответ на [" + to + "]:\n";

        return false;
    },
    collapseMsg: function( id )
    {
        var msg = this.getMessageById( id );
        if( msg ) msg.collapse();
        return false;
    },
    getMessageById: function( id )
    {
        return this.messages[ 'id_' + id ];
    },
    onTextareaKeyDown: function( e )
    {
        e = ( e ) ? e : window.event;
        if ( e.keyCode == 13 ) // Enter pressed
        {
            if( e.shiftKey )
            {
                document.getElementById( 'f4' ).checked = true;
                Imho.Guestbook.addPost();
                return false;
            }
            if( e.ctrlKey )
            {
                document.getElementById( 'f4' ).checked = false;
                Imho.Guestbook.addPost();
                return false;
            }
        }
        return true;
    },
    showKeyInfo: function( elem )
    {
        var div = elem.getElementsByTagName( 'DIV' )[0];
        if( !div ) return false;
        div.style.display = 'block';
        div.onmouseout = Imho.Guestbook.hideKeyInfo;
    },
    hideKeyInfo: function() { this.style.display = 'none'; },
    sendNewMessagesTest: function()
    {
        if( Imho.Guestbook.Today.toString() != '/' + Imho.Guestbook.getSelectedDate() && location.hash.length > 0 ) return false;
        var request = new Http.Request( Imho.Guestbook.workerPath, {informer:'total'} );
        request.onComplete = Imho.Guestbook.testNewMessages;
        request.send( true );
    },
    testNewMessages: function( responce )
    {
        var xml = responce.getXML();
        if ( !xml || !xml.getElementsByTagName( 'imho-responce' ) ) return false;
        var total = xml.getElementsByTagName( 'total' )[0];
        if( !total ) return false;
        total = parseInt( total.firstChild.nodeValue, 10 );

        if ( Imho.Guestbook.messageCounter >= total ) return false;
        if ( !Imho.Guestbook.msgContainer ) return false;

        if( !Imho.Guestbook.msgNewInformer )
        {
            Imho.Guestbook.msgNewInformer = document.createElement( 'DIV' );
            Imho.Guestbook.msgNewInformer.className = 'gbMessagesInformer';
            Imho.Guestbook.msgNewInformer.title = 'Обновить?';
            Imho.Guestbook.msgNewInformer.onclick = function()
            {
                location.href = Core.Guestbook.root + '#' + Imho.Guestbook.Today.toString();
                Imho.Guestbook.messageCounter = this.getAttribute( 'total' );
                Imho.Guestbook.Pager.currentPage = 0;
                Imho.Guestbook.clear();
                Imho.Guestbook.load();
            };
            addAttribute( Imho.Guestbook.msgNewInformer, 'total', total );
            Imho.Guestbook.msgContainer.parentNode.insertBefore( Imho.Guestbook.msgNewInformer, Imho.Guestbook.msgContainer );
        }
        Imho.Guestbook.msgNewInformer.setAttribute( 'total', total );
        var added = total - Imho.Guestbook.messageCounter;
        var text = ( added == 1 ) ? 'новое сообщение' : ( added > 5 ) ? 'новых сообщений' : 'новых сообщения';
        Imho.Guestbook.msgNewInformer.innerHTML = 'За время просмотра Вами данной страницы поступило <b>' + added + '</b> ' + text;
        //за время просмотра данной страницы поступило ... новых сообщений
        Imho.Guestbook.msgNewInformer.style.display = 'block';
    },
    clear: function()
    {
        if( this.msgContainer ) this.msgContainer.innerHTML = '';
        this.messages = null;
        this.messages = {};
    }
};

Imho.Guestbook.Message = function( /*XMLNode*/ root )
{
    this.shown = false;
    this.root = root;
    this.id = this.root.getAttribute( 'id' );
    this.offtopic = ( this.root.getElementsByTagName('offtopic')[0].firstChild.nodeValue == '1' );
    this.foul = ( this.root.getElementsByTagName('foul')[0].firstChild.nodeValue == '1' );
	this.wipped = false;
	  
    var user = this.root.getElementsByTagName('user')[0];
	var name = user.getElementsByTagName('name')[0];
	var team = user.getElementsByTagName('team')[0];	
    this.user =
    {
        id: user.getAttribute( 'id' ),
        name: ( ( name && name.firstChild ) ? name.firstChild.nodeValue : 'Anonymouses' ),
        team: ( ( team && team.firstChild ) ? team.firstChild.nodeValue : 1 )
    };
    var date = this.root.getElementsByTagName('date');
    for( var i = 0; i < date.length; i++ )
    {
        if( date[i].getAttribute( 'name' ) == 'created' ) { date = date[i]; break; }
    }
    if ( !date ) return false;
    this.date =
    {
        name: 'created',
        day: date.getAttribute( 'day' ),
        month: date.getAttribute( 'month' ),
        year: date.getAttribute( 'year' ),
        hour: date.getAttribute( 'hour' ),
        minute: date.getAttribute( 'minute' ),
        second: date.getAttribute( 'second' ),
        toString: function()
        {
            return this.day + '/' + this.month + '/' + this.year + ' ' + this.hour + ':' + this.minute + ':' +this.second;
        }
    };

    this.container = document.createElement( 'DIV' );
    this.container.className = 'msg';
    if( this.foul ) this.container.className += ' foul';

    this.getHTML = function()
    {
        var table = document.createElement( 'TABLE' );
        table.className = ( this.offtopic ) ? 'offtop' : 'imho';         
        var row = table.insertRow( 0 );

        var cell = row.insertCell( 0 );
        cell.style.width = '10px'; cell.noWrap = true; cell.innerHTML = '<B>' + this.id + '</B>';

        cell = row.insertCell( 1 );
        cell.style.width = '200px'; cell.noWrap = true;
        cell.innerHTML = '<A href="/users/profile/profile_' + this.user.id + '.html" target=_blank><FONT color=#000000><b>' + this.user.name + '</b></FONT></A>';

        cell = row.insertCell( 2 );
        cell.style.width = '10px'; cell.noWrap = true;
        if( this.foul ) cell.innerHTML = '<br/>';
        else
        {
            cell.innerHTML = '<A style="CURSOR: hand" onclick="return Imho.Guestbook.reply(\''+ this.id + ' '+ this.user.name+'\');" href="#">' +
                   '<IMG alt="Ответить на сообщение №'+this.id+' пользователя '+this.user.name+'" src="/images/reply_to.gif" border=0></A>';
        }

        cell = row.insertCell( 3 );
		cell.style.width = '250px'; cell.noWrap = true;
        cell.align = 'right'; cell.innerHTML = '<A onclick="return Imho.Guestbook.collapseMsg(\'' + this.id + '\');" href="#"><IMG alt="Спрятать сообщение" src="/images/close.gif" border=0></A>';

        cell = row.insertCell( 4 );
        //cell.style.text-align = 'right';
        cell.innerHTML = '<NOBR>&nbsp;&nbsp;&nbsp;&nbsp;<B>'+ this.date +'</B></NOBR>';

        this.container.appendChild( table );

        var contentValue = this.root.getElementsByTagName('text')[0];

        this.content = document.createElement( 'DIV' );		
		var contentBlock = document.createElement( 'DIV' );

        for( var i = 0; i < contentValue.childNodes.length; i++ )
        {
            if ( contentValue.childNodes[i].nodeType == 4 )
            {
                contentBlock.innerHTML += contentValue.childNodes[i].nodeValue;
            }
        }

        contentBlock.id = 'cont' + this.id;
		contentBlock.style.background = "url('/images/fon/" + this.user.team + "-2.gif') 100% 5px no-repeat";

		this.content.appendChild( contentBlock );
        this.container.appendChild( this.content );

        return this.container;
    };

    this.collapse = function()
    {		
        if ( !this.content ) return false;        
		if( !this.wipped )
		{
			dojo.lfx.html.fadeWipeOut(this.content, 300 ).play();
			this.wipped = true;
		}
		else
		{
			dojo.lfx.fadeWipeIn(this.content, 300 ).play();
			this.wipped = false;							
		}
    };
};

Imho.Guestbook.Pager =
{
    container:null,
    currentPage: -1,
    currentPageObj: null,
    prev: null,
    next: null,
    perpage: Core.Guestbook.perpage,
    totalpages: 0,
    buildDate: '',
    getParamValue: function()
    {
        if( Imho.Guestbook.Search.isActive() )
            return ( Imho.Guestbook.Search.getPageNumber() - 1 ) * this.perpage;
        else
            return ( this.currentPage > 0 ) ? ( this.currentPage - 1 ) * this.perpage : 0;
    },
    isShown: function() { return ( this.currentPageObj && this.currentPageObj.offsetHeight > 0 ); },    
	
	build: function( xml )
    {        

		if( !Imho.Guestbook.msgContainer ) return false;
        if( !this.container ) this.createContainer();
        if( !this.container ) return false;

        this.container.innerHTML = '';

        if( xml.getElementsByTagName('page').length === 0    )
        {
            this.container.parentNode.style.display = 'none';
            return false;
        }
		
        this.container.innerHTML = 'Страницы:&nbsp;';

        this.buildDate = Imho.Guestbook.getSelectedDate();

        var pages = xml.getElementsByTagName('page');
        var page = null;
        this.perpage = xml.getElementsByTagName('pages')[0].getAttribute('perpage');
        this.totalpages = xml.getElementsByTagName('pages')[0].getAttribute('totalPages');        

        var maybeePageNumber = ( Imho.Guestbook.Search.isActive() ) ?
            Imho.Guestbook.Search.getPageNumber() :
            location.hash.substring(2).replace( Imho.Guestbook.getSelectedDate(), '' ).replace( '/', '' );
        var currentPageNumber = 0, isCurrent = false;
		var firstPage = null;
        for( var i = 0; i < pages.length; i++ )
        {
            currentPageNumber = pages[i].getAttribute('num');
			isCurrent = ( pages[i].getAttribute('current') && maybeePageNumber.length === 0 || maybeePageNumber.length !== 0 && maybeePageNumber == currentPageNumber );
									
            page = document.createElement( isCurrent ? 'SPAN' : 'A' );
			if( i === 0 ) firstPage = page;
			if( isCurrent )
            {
				page.className = 'current';                
                this.currentPage = currentPageNumber;
                this.currentPageObj = page;
            }
			 
            page.href = ( Imho.Guestbook.Search.isActive() ) ?
                Imho.Guestbook.Search.makeSearchPath() + ( currentPageNumber ) + '/' :
                Core.Guestbook.root + '#/' + Imho.Guestbook.getSelectedDate() + ( currentPageNumber ) + '/';

            page.name = ( i + 1 );
            page.onclick = function()
            {
                return Imho.Guestbook.Pager.go( this );
            };
            page.title = 'c ' + pages[i].getAttribute( 'from' ) + ' по ' + pages[i].getAttribute( 'to' );            
            page.innerHTML = currentPageNumber;
            this.container.appendChild( page );            
        }
		
		var prev = xml.getElementsByTagName('prev')[0];				
				
		this.prev = document.createElement( this.currentPage > 1 ? 'A' : 'B' );
		this.prev.innerHTML = '&larr;';
		this.prev.target = 'prev';
		this.prev.href = '#';		         
        this.prev.name = ( this.currentPage - 1 ) * this.perpage;        
        this.prev.onclick = function()
        {
            return Imho.Guestbook.Pager.go( this, Imho.Guestbook.Pager.currentPage - 1 );
        };		        
		this.container.insertBefore( this.prev, firstPage );

        var next = xml.getElementsByTagName('next')[0];
		
		this.next = document.createElement( this.currentPage < this.totalpages ? 'A' : 'B' );
		//this.next.appendChild( document.createTextNode( '<![CDATA[&rarr;]]>' ) );
		this.next.innerHTML += '&rarr;';
		this.next.href = '#';
		this.next.target = 'next';		         
        this.next.name = ( this.currentPage - 1 ) * this.perpage;        
        this.next.onclick = function()
        {
            return Imho.Guestbook.Pager.go( this, Imho.Guestbook.Pager.currentPage + 1 );
        };        
        this.container.appendChild( this.next );
				
        this.container.parentNode.style.display = 'block';               
    },
	
    go: function( elem, pageNum )
    {
        elem.blur();

        if( elem.nodeName == 'A' && elem.target )
        {
            if( this.currentPage > pageNum  )
                elem = this.currentPageObj.previousSibling;
            else
                elem = this.currentPageObj.nextSibling;
        }		
        this.currentPage = elem.name;		

        elem.className = 'current';
        if( this.currentPageObj ) this.currentPageObj.className = '';
        this.currentPageObj = elem;

        Imho.Guestbook.Loading.show();

        location.href = elem.href;
        Imho.Guestbook.clear();
        Imho.Guestbook.load();

        return false;
    },
	mergeLinks: function( tagName, elem )
	{
		var newElem = document.createElement( tagName );
		newElem.innerHTML = elem.innerHTML;
		newElem.target = elem.target;
		newElem.href = elem.href;
		newElem.onclick = elem.onclick;
		elem.parentNode.insertBefore( newElem, elem );
		elem.removeNode( false );
		return newElem;					
	},	
    createContainer: function()
    {
        var div = document.createElement( 'DIV' );
        div.className = 'pagination';
		this.container = document.createElement('P');
		div.style.marginTop = '11px';
		div.appendChild( this.container );
		Imho.Guestbook.msgContainer.parentNode.insertBefore( div, Imho.Guestbook.msgContainer );		
    }
};

Imho.Guestbook.Calendar =
{
    selected: null,
    target: null,
    getSelectedDay: function()
    {
        return ( Imho.Guestbook.Calendar.selected ) ? Imho.Guestbook.Calendar.selected.getElementsByTagName('A')[0].href : null;
    },
    reload: function()
    {
        this.target.innerHTML = '';
        this.load( this.target.id, Core.Guestbook.worker + Imho.Guestbook.getSelectedDate() );
    },
    load: function( elemntId, url )
    {
        if( !this.target ) this.target = document.getElementById( elemntId );
        if( !this.target ) return false;
        if( !url )
        {
            url = Core.Guestbook.worker;
            if( Imho.Guestbook.getSelectedDate().length !== 0 ) url += Imho.Guestbook.getSelectedDate();
        }

        var request = new Http.Request( url, {calendar:'get'} );
        request.onComplete = Imho.Guestbook.Calendar.parse;
        request.send( true );
    },
    parse: function( responce )
    {
        var xml = responce.getXML();
        if ( !xml || !xml.getElementsByTagName( 'imho-responce' )[0] ) return false;
        Imho.Guestbook.Calendar.build( xml );
    },
    build: function( xml )
    {
        var weekNames = ['Пн','Вт','Ср','Чт','Пт','Сб','Вск'];
        var table = document.createElement( 'TABLE' );
        table.className = 'caltable';
        table.bgColor = '#ffffff';
        table.border = 0;
        table.cellPadding = 0;
        table.cellSpacing = 1;
        table.width = '100%';

        var tr = table.insertRow( table.rows.length );
        var cell = null;

        var currentDate = xml.getElementsByTagName( 'current' )[0];
        tr.className = 'header';
        cell = tr.insertCell( 0 );
        cell.colSpan = 7;
        cell.innerHTML = currentDate.getAttribute('month') + '-' + currentDate.getAttribute('year');

        tr = table.insertRow( table.rows.length );
        tr.className = 'weeks';

        for( var i = 0; i < weekNames.length; i++ )
        {
            cell = tr.insertCell( i );
            cell.innerHTML = weekNames[i];
        }

        var weeks = xml.getElementsByTagName( 'week' );
        var week = null, days = null, day = null, link = null, date = [];
        for( i = 0; i < weeks.length; i++ )
        {
            week = weeks[i];
            tr = table.insertRow( table.rows.length );
            days = week.getElementsByTagName('day');
            for( var j = 0; j < days.length; j++ )
            {
                day = days[j];
                cell = tr.insertCell( j );

                if( !day.firstChild ) cell.innerHTML = '&nbsp;';
                else
                {
                    if( day.getAttribute('year') && day.getAttribute('active') != 'false'  )
                    {
                        date = [day.getAttribute('year'),day.getAttribute('month'),day.getAttribute('num')];
                        if( ( Imho.Guestbook.getSelectedDate() == date.join('/') + '/' ) ||
                            ( location.hash.length === 0 && day.getAttribute('current') ) )
                        {
                            Imho.Guestbook.Calendar.selected = cell;
                            cell.className = 'current';
                        }
                        link = document.createElement('A');
                        link.href = Core.Guestbook.root + '#/' + date[0] + '/' + date[1] + '/' + date[2] + '/';
                        link.innerHTML = day.firstChild.nodeValue;
                        link.onclick = function()
                        {
                            this.blur();
                            if( this.parentNode.className != 'current' ) Imho.Guestbook.Calendar.go( this.href, this );
                            else return false;
                        };
                        cell.appendChild( link );
                    }
                    else
                    {
                        if( day.getAttribute('current') ) Imho.Guestbook.Calendar.selected = cell;
//                        if( day.getAttribute('active') == 'false' ) cell.className = 'gray';
                        cell.className = 'gray';
                        cell.innerHTML = day.firstChild.nodeValue;
                    }
                }
            }
        }

        tr = table.insertRow( table.rows.length );
        tr.className = 'archive';
        cell = tr.insertCell( 0 );
        cell.colSpan = 7;
        var archive = xml.getElementsByTagName('archive')[0].getElementsByTagName('date');

        var select = document.createElement('SELECT');
        select.options[ select.options.length ] = new Option( 'Архивы по месяцам:', '' );
        select.onchange = function()
        {
            if( this.value.length === 0 ) return false;
            Imho.Guestbook.Calendar.selected = null;
            Imho.Guestbook.Calendar.go( this.value + '31/' );
            Imho.Guestbook.Calendar.reload();
        };

        var dates = [];
        var datesSelected = Imho.Guestbook.getSelectedDate().split('/');
        for( i = 0; i < archive.length; i++  )
        {
            dates = [archive[i].getAttribute('year'),archive[i].getAttribute('month')];
            select.options[ select.options.length ] = new Option( dates[1] + '-' + dates[0], Core.Guestbook.root + '#/' + dates[0] + '/' + dates[1] + '/' );
            if ( datesSelected[0] == dates[0] && datesSelected[1] == dates[1] )
                select.options[ select.options.length - 1 ].selected = true;
        }
        cell.appendChild( select );

        this.target.appendChild( table );

        if( Imho.Guestbook.Search.isActive() ) return true;
        if( !Imho.Guestbook.Calendar.selected ||
            ( Imho.Guestbook.Calendar.selected && !Imho.Guestbook.Calendar.selected.getElementsByTagName('A')[0] ) )
        {
            var items = table.getElementsByTagName('TD');
            this.findDayWithPostsBackward( items );
//            if( Imho.Guestbook.Calendar.selected.innerHTML == Imho.Guestbook.Today.getDate() )
//                this.findDayWithPostsBackward( items );
//            else
//                this.findDayWithPostsForward( items );
        }
    },
    findDayWithPostsBackward: function( items )
    {
        for( var i = items.length - 1; i >= 0; i-- )
        {
            if( this.findDayWithPosts( items[i] ) ) break;
        }
    },
    findDayWithPostsForward: function( items )
    {
        var anchor = null;
        for( var i = 0; i < items.length; i++ )
        {
            if( this.findDayWithPosts( items[i] ) ) break;
        }
    },
    findDayWithPosts: function( item )
    {
        var anchor = item.getElementsByTagName('A')[0];
        if( anchor )
        {
            Imho.Guestbook.Calendar.go( anchor.href );
            Imho.Guestbook.Calendar.reload();
            return true;
        }
        return false;
    },
    highlight: function( elem )
    {
        if( !elem ) return false;
        if( !Imho.Guestbook.Calendar.selected )
        {
            elem.parentNode.className = 'current';
        }
        else
        {
            elem.parentNode.className = 'current';
            if( Imho.Guestbook.Calendar.selected.className == 'current' ) Imho.Guestbook.Calendar.selected.className = '';
        }
        Imho.Guestbook.Calendar.selected = elem.parentNode;
    },
    go: function( href, elem )
    {
        Imho.Guestbook.Loading.show();

        location.href = href;
        if( elem ) Imho.Guestbook.Calendar.highlight( elem );
        Imho.Guestbook.Pager.currentPage = 1;
        Imho.Guestbook.clear();
        Imho.Guestbook.load();
    }
};

Imho.Guestbook.Today = new Date();
Imho.Guestbook.Today.toString = function()
{
    var num = this.getMonth() + 1;
    return '/' + this.getFullYear() + '/' +
          ( ( num < 10 ) ? '0' + ( num ) : num ) + '/' +
          ( ( this.getDate() < 10 ) ? '0' + this.getDate() : this.getDate() ) + '/';
};

// paramName, srchPat[1], paramNum
Imho.Guestbook.Search =
{
    form: null,
    isActive: function() { return ( location.hash.indexOf('search') != -1 ); },
    doSearch: function()
    {
        if( !this.form ) return false;

        var params = this.getSearchParams();

        var empty = true;
        for( var i in params ) { if( params[i] && i != 'getmessages' ) { empty = false; break; } }
        if( empty ) return false;

        location.href = this.makeSearchPath( params );

        if( Imho.Guestbook.msgContainer ) Imho.Guestbook.clear();
        if( Imho.Guestbook.Calendar.target ) Imho.Guestbook.Calendar.reload();
        Imho.Guestbook.Pager.currentPage = 1;

        Imho.Guestbook.Loading.show();
        Imho.Guestbook.load();
    },
    init: function( id )
    {
        if( !this.form ) this.form = document.getElementById( id );
        if( !this.form ) return false;
        this.form.onsubmit = function()
        {
            Imho.Guestbook.Search.doSearch();
            return false;
        };
    },
    getSearchParams: function()
    {
        var params = {};
        if( this.form.paramName.value.length > 0 ) params['paramName'] = this.form.paramName.value;
        if( this.form.elements['srchPat[1]'].value.length > 0 ) params['srchPat[1]'] = this.form.elements['srchPat[1]'].value;
        if( this.form.paramNum.value.length > 0 ) params['paramNum'] = this.form.paramNum.value;
        params['getmessages'] = true;
        return params;
    },
    makeSearchPath: function()
    {
        var path = Core.Guestbook.root + '#/search/';
        for( var i = 0; i < this.form.elements.length; i++ )
        {
            if( this.form.elements[i].value.length === 0 ) continue;
            switch( this.form.elements[i].name )
            {
                case 'paramName':
                    path += 'author/' + Http.escape( this.form.elements[i].value ) + '/'; break;
                case 'srchPat[1]':
                    path += 'text/' + Http.escape( this.form.elements[i].value ) + '/'; break;
                case 'paramNum':
                    path += 'id/' + this.form.elements[i].value + '/'; break;
				default: break;
            }
        }
        return path;
    },
    fillFormByParamsFromUri: function()
    {
        var hash = location.hash.substring(2);
        var hashArr = hash.split('/');
        for( var i = 0; i < hashArr.length; i++ )
        {
            if( hashArr[i] == 'search' ) continue;
            switch( hashArr[i] )
            {
                case 'author':
                    this.form.paramName.value = Http.unescape( hashArr[++i] ); break;
                case 'text':
                    this.form.elements['srchPat[1]'].value = Http.unescape( hashArr[++i] ); break;
                case 'id':
                    this.form.paramNum.value = hashArr[++i]; break;
				default: break;
            }
        }
    },
    getPageNumber: function()
    {
        var searchPath = this.makeSearchPath();
        var num = location.href.substring( location.href.indexOf( searchPath ) + searchPath.length ).replace( '/', '' );
        return ( parseInt( num, 10 ) ) ? num : 1;
    }
};

Imho.Guestbook.Loading =
{
    container:null,
    show: function()
    {
        if( !this.container ) this.container = document.getElementById('gbLoading');
        if( this.container ) this.container.style.display = 'block';
    },
    hide: function() { if( this.container ) this.container.style.display = 'none'; }
};