var Article = new Class(
{
    initialize:function(root)
    {
        
        var t = this;
        
        var post = root;
        this.content = root.getElement( 'div[class$=postContent]' );
        this.bodyWrap = root.getElement( 'div[class$=postWrap]' );
        this.body = this.bodyWrap.getElement('div[class$=postText]' );
        this.loadAnim = root.getElement( 'div[class$=ajaxLoadWrap]' );
        this.comments = root.getElement( 'div[class$=comments]' );
        this.commentsLink = this.comments.getElement( 'a' );
        this.load = root.getElement( 'div[class$=loadArticle]' );
        var loadLabel = this.load.getElement( 'a' );
        this.close = root.getElement( 'div[class$=closeArticle]');
        var closeLabel = this.close.getElement( 'a' );
        
        this.commentWrap = root.getElements( 'div[class$=postWrap]' )[1];
        this.innerCommentWrap = this.commentWrap.getElement( 'div[class$=postWrap]' );
        this.commentBody = this.innerCommentWrap.getElement( 'div' );
        
        this.data = { "id":post.getProperty( 'id' ).substring( 4 ), "body":{ "-c":this.body.innerHTML } };
        
        var commentNew = this.commentNew = new Element( 'div', {'class':'commentNew'} );
        var commentLoad = new Element( 'div', {'class':'commentLoad'} ).setText( 'Posting Your Comment...' ).injectInside( commentNew );
        new Element( 'img', {'class':'commentsIcon', src:'/blog/images/comments.png', width:'16', height:'15'} ).injectInside( commentNew );
        new Element( 'span', {'class':'postComment'} ).setText( 'Post a comment' ).injectInside( commentNew );
        this.formLabelName = new Element( 'label', {'for':'name' + this.data.id} ).setText( 'Name:' ).injectInside( commentNew );
        this.formUsername = new Element( 'input', {'id':'name' + this.data.id, 'name':'name', 'type':'text'} ).injectInside( commentNew );
        new Element( 'label', {'for':'website' + this.data.id} ).setText( 'Website:' ).injectInside( commentNew );
        this.formWebsite = new Element( 'input', {'id':'website' + this.data.id, 'name':'website', 'type':'text'} ).injectInside( commentNew );
        this.formLabelMessage = new Element( 'label', {'for':'message' + this.data.id} ).setText( 'Comments:' ).injectInside( commentNew );
        this.formMessage = new Element( 'textarea', {'id':'message' + this.data.id, 'name':'message'} ).injectInside( commentNew );
        var submit = new Element( 'a', {'href':'#', 'class':'submitBtn'} ).setText( 'Post Your Comment' ).injectInside( commentNew );
        commentNew.injectInside( this.commentWrap );
        submit.addEvent( 'click', function(e){t.onClickPostComment(e);});
        
        this.lastCommentId = 0;
        this.commentsLoaded = this.commentBody.getElements( 'div[class$=commentPost]' ).length + this.commentBody.getElements( 'div[class$=commentPostAlt]' ).length != 0;
        
            
        
        loadLabel.addEvent( 'click', function(e){t.onClickLoad(e);});
        closeLabel.addEvent( 'click', function(e){t.onClickClose(e);});
        this.commentsLink.addEvent( 'click', function(e){t.onClickComments(e);});
        this.close.setStyle('display','none');
        post.injectAfter( $('quote') );
        
        this.bodyWrap.setStyle( 'height', this.body.getStyle( 'height' ));
        this.showLoader = new Fx.Styles(this.loadAnim, 
		{
			duration: 200,
			transition: Fx.Transitions.quartInOut
		});
		
		this.showArticle = new Fx.Styles(this.bodyWrap, 
		{
			duration: 400,
			transition: Fx.Transitions.quartInOut
		});
		
		this.showComments = new Fx.Styles(this.commentWrap, 
		{
			duration: 400,
			transition: Fx.Transitions.quartInOut
		});
		
		this.showInnerComments = new Fx.Styles(this.innerCommentWrap, 
		{
			duration: 400,
			transition: Fx.Transitions.quartInOut
		});
		
		this.showCommentLoader = new Fx.Styles(commentLoad, 
		{
			duration: 400,
			transition: Fx.Transitions.quartInOut
		});
		
		this.commentNewShow = new Fx.Styles(this.commentNew,
		{
		    duration: 400,
		    transition: Fx.Transitions.quartInOut
		});
    },
    
    revealComments:function()
    {
        var t = this;
        
        var c = this.commentBody.getElements( 'div[class$=commentPost]' ).length + this.commentBody.getElements( 'div[class$=commentPostAlt]' ).length;
        this.commentNew.removeClass( 'commentNew' );
        this.commentNew.removeClass( 'commentNewAlt' );
        this.commentNew.addClass( ( c%2 == 0 ? 'commentNew' : 'commentNewAlt') );
        
        this.showComments.start({
            'height': parseInt(this.commentBody.getStyle( 'height' ))+parseInt(this.commentNew.getStyle( 'height' ))+60/*padding*/
         }).chain(function(){
            t.showInnerComments.start({
                'height': t.commentBody.getStyle( 'height' )
            });
         });
    },
    
    loadMore:function()
    {
        var t = this;
        var request = new Json.Remote( '/blog/core/BlogMore.php?blogId=' + this.data.id + '&out=json', 
	    {
		    onComplete: function(obj)
		    {
		        t.onMoreLoaded( obj );
		    }
	    }).send();
    },
    
    loadComments:function()
    {
        var t = this;
        var request = new Json.Remote( '/blog/core/CommentList.php?blogId=' + this.data.id + '&out=json', 
	    {
		    onComplete: function(obj)
		    {
		        t.onCommentsLoaded( obj );
		    }
	    }).send();
    },
    
    onClickComments:function(e)
    {
        new Event(e).stop()
        var t = this;
        
        if( this.commentsLoaded )
        {
            this.commentsLoaded = false;
            this.showComments.start({
                'height':'0px'
            }).chain(function()
            {
                // delete the comments...
                t.commentBody.remove();
                t.commentBody = new Element('div' ).injectInside( t.innerCommentWrap );
                setFooter();
            });
        }
        else
        {
            this.commentsLoaded = true;
            this.showLoader.start({
		        'opacity': [0,0],
			    'height': ['0px','40px']
		    }).chain(function()
		    {
		        this.start({
		            'opacity': [0,1]
		        }).chain(function()
		        {
		            t.loadComments();
		        })
		    });
        }
    },
    
    onClickLoad:function(e)
    {
        new Event(e).stop()
        
        var t = this;
	    
	    this.showLoader.start({
		    'opacity': [0,0],
			'height': ['0px','40px']
		}).chain(function()
		{
		    this.start({
		        'opacity': [0,1]
		    }).chain(function()
		    {
		        t.loadMore();
		    })
		});
//		this.loadAnim.setStyle('display','block');
        this.load.setStyle('display','none');
        this.close.setStyle('display','block');
    },
    
    onClickClose:function(e)
    {
        //new Event(e).stop();
        
        this.body.setHTML(this.data.body['-c']);
        this.close.setStyle('display','none');
        this.load.setStyle('display','block');
        this.showArticle.start({
            'height': this.body.getStyle( 'height' )
        });
    },
    
    expandToFit:function()
    {
        this.showArticle.start({
            'height': this.body.getStyle( 'height' )
        });
    },
    
    onMoreLoaded:function( data )
    {
        var t = this;
        
        this.body.setHTML(this.data.body['-c'] + data.more['-c']);
        
        this.showArticle.start({
            'height': this.body.getStyle( 'height' )
        }).chain(function(e){
            t.showLoader.start({
		        'opacity': [1,0],
			    'height': ['40px','0px']
		    });
        });
    },
    
    sendComment:function()
    {
        var t = this;
        var request = new Json.Remote( '/blog/core/CommentCreate.php', 
	    {
		    onComplete: function(obj)
		    {
		        t.onCommentCreated( obj );
		    }
	    }).send( { 'out':'json', 'commentId':this.lastCommentId, 'blogId':this.data.id, 'body':this.formMessage.value, 'name':this.formUsername.value, 'email':'', 'url':this.formWebsite.value });
    },
    
    onClickPostComment:function( e )
    {
        new Event(e).stop();
        var t = this;
        this.showCommentLoader.start({
            'height':'24px'
        }).chain(function(e){
            t.sendComment();
        });
       
        this.showComments.start({
            'height':parseInt(this.commentBody.getStyle( 'height' ))+72//-231
        });
        
        this.commentNewShow.start({
            'height': '12px'
         });
         
    },
    
    onCommentCreated:function( data )
    {
        this.formLabelName.removeClass( 'error' );
        this.formLabelMessage.removeClass( 'error' );
        if( data.response['@'].success == '0' )
        {
            for( var i = 0; i < data.response.error.length; i++ )
            {
                if( data.response.error[i]['$']['-c'] == 'name' )
                {
                    
                    this.formLabelName.addClass( 'error' );
                }
                else if( data.response.error[i]['$']['-c'] == 'body' )
                {
                    
                    this.formLabelMessage.addClass( 'error' );
                }
            }
        }
        else
        {
            this.appendComments( data );
            this.formMessage.value = '';
            this.formUsername.value = '';
            this.formWebsite.value = '';
        }
        var t = this;
        
         this.showComments.start({
                'height': parseInt(t.commentBody.getStyle( 'height' ))+304/*padding*/
         })
         this.showCommentLoader.start({
            'height':'0px'
         });
         this.commentNewShow.start({
            'height': '244px'
         }).chain( function(e){
             t.showInnerComments.start({
                'height': t.commentBody.getStyle( 'height' )
             });
         });
    },
    
    appendComments:function( data )
    {
        var c = this.commentBody.getElements( 'div[class$=commentPost]' ).length + this.commentBody.getElements( 'div[class$=commentPostAlt]' ).length;
        var cm2 = c%2;
        var i;
        var t = this;
        for( i = 0; i < data.item.length; i++ )
        {
            commentPost = new Element( 'div', {'class':i%2 != cm2 ? 'commentPost' : 'commentPostAlt'} );
            var poster = new Element( 'span', {'class':'poster'} );
            var posterA = undefined;
            if( data.item[i].user == undefined && data.item[i].url != '' )
                posterA = new Element( 'a', {'href':data.item[i].url} );
            else if( data.item[i].user != undefined )
                posterA = new Element( 'a', {'href':'/blog/authors/' + data.item[i].user.url} );
            var commentDate = new Element( 'span', {'class':'commentDate'} );
            
            commentPost.setHTML( data.item[i].body['-c'] );
            
            poster.injectTop( commentPost );
            if( posterA != undefined )
            {
                posterA.setText( data.item[i].user == undefined ? data.item[i].name : data.item[i].user.name );
                posterA.injectInside( poster );
            }
            else
                poster.setText( data.item[i].user == undefined ? data.item[i].name : data.item[i].user.name );
                
            poster.appendText( ' writes:' );
            
            commentDate.injectInside( commentPost );
            commentDate.setHTML('Posted at ' + new Date( parseInt(data.item[i].date)*1000 ).formatDate( "g:i a, F j, Y" )); //11:35 am, October 20, 2006
            commentPost.injectInside( this.commentBody );
            
            this.lastCommentId = data.item[i].id;
        }
        this.commentNew.removeClass( 'commentNew' );
        this.commentNew.removeClass( 'commentNewAlt' );
        this.commentNew.addClass( ( (c+i) == 0 || (cm2+i)%2 != 0 ? 'commentNew' : 'commentNewAlt') );
        
        this.commentsLink.remove();
        this.commentsLink = new Element('a', {'href':'#'}).setHTML( (c+i) + ((c+i)==1 ? ' Comment ' : ' Comments ') ).injectInside( this.comments );
        var image = new Element( 'img', {'src':'/blog/images/comment.png','width':'14','height':'11'} ).injectInside( this.commentsLink );
        this.commentsLink.addEvent( 'click', function(e){t.onClickComments(e);});
    },
    
    onCommentsLoaded:function( data )
    {
        var t = this;
        
        
        this.appendComments( data );
		this.innerCommentWrap.setStyle( 'height', this.commentBody.getStyle( 'height' ) );
        this.showComments.start({
            'height': parseInt(this.commentBody.getStyle( 'height' ))+parseInt(this.commentNew.getStyle( 'height' ))+60/*padding*/
        }).chain(function(e){
            t.showLoader.start({
		        'opacity': [1,0],
			    'height': ['40px','0px']
		    });
		    setFooter();
        });
    }
});


var ArticleLoader = 
{
    init:function()
	{  
	    this.articles = new Array();
		var articles = $E('html').getElements( 'div[class$=post]' );
		this.articles = new Array();
		for( var i = 0; i < articles.length; i++ )
		{
		    this.articles.push( new Article( articles[i] ) );
		}
		new SmoothScroll();
		linkColorChange.setupColorChange();
		if( articles.length == 1 )
		    this.articles[0].revealComments();
	},
	
	onBlogList:function( data )
	{
	    for( var i = data.item.length-1; i >= 0; i-- )
        {
            this.articles.push( new Article( data.item[i] ) );
        }
        new SmoothScroll();
        setFooter();
        linkColorChange.setupColorChange();
	},
	
	expandToFit:function()
	{
	    for( var i = 0; i < this.articles.length; i++ )
	        this.articles[i].expandToFit();
	}
}
window.onDomReady(ArticleLoader.init.bind(ArticleLoader));