var loading = false;
var cLoading = false;

var addStatusListener = function ()
{
    if($defined($('update-status')))
    {
        statusForm = document.getElement('div#status form');
        statusForm.setStyle('display','none');
        
        btn = $('update-status');
        
        btn.addEvent('click',
            function (ev)
            {
                this.setStyle('display','none');
                $('status').getElement('h4').setStyle('display','none');

                if($defined($('status').getElement('p.status')))
                {
                    $('status').getElement('p.status').setStyle('display','none');
                    $('status').getElement('p.time-wrapper').setStyle('display','none');
                }

                statusForm.setStyle('display','block');
                addRoundedCorners(statusForm.getElement('input[type=submit]'),'beige');
            }
        );
        
        $('status').grab(btn);
        
        statusField = statusForm.getElement('textarea');
        statusField.addEvent('keypress',
            function (ev)
            {
                if(ev.key == 'enter' || statusField.value.length > 60)
                {
                    ev.preventDefault();
                }
            }
        );
        
        statusForm.addEvent('submit',
            function (ev)
            {
                ev.preventDefault();
                request = new Request.JSON({
                    'url':      responder,
                    'link':     'cancel',
                    onComplete: function (response)
                    {
                        if($defined(response.token))
                        {
                            token = response.token;
                            status = response.statusMsg;
                            if(status === false || status === 'false')
                            {
                                status = '...';
                            }
                            
                            $('status').getElement('h4').setStyle('display','block');
                            btn.setStyle('display','inline');
                            if($defined($('status').getElement('p.status')))
                            {
                                $('status').getElement('p.status').setStyle('display','block');
                                $('status').getElement('p.time-wrapper').setStyle('display','block');
                                $('status').getElement('p span.msg').set('html',status);
                                $('status').getElement('p span.time').set('html','just now');
                            }
                            else
                            {
                                p = new Element('p',
                                    {
                                        'class':    'status',
                                        'html':     $('current-username').get('html')+' is '
                                    }
                                );
                                p.grab(new Element('span',
                                    {
                                        'class':    'msg',
                                        'html':     status
                                    }
                                ));
                                p2 = new Element('p',
                                    {
                                        'class':    'time-wrapper',
                                        'html':     'Updated '
                                    }
                                );
                                p2.grab(new Element('span',
                                    {
                                        'class':    'time',
                                        'html':     'just now'
                                    }
                                ));
                                p.inject($('status').getElement('h4'),'after');
                                p2.inject(p,'after');
                            }
                            statusForm.setStyle('display','none');
                            $('status').highlight('#F91C01');
                        }
                    }
                }).post({
                    'action':   'updateStatus',
                    'status':   !statusField.value ? false : statusField.value,
                    'token':    token
                });
            }
        );
    }
};

var addCommentListener = function ()
{
    if($defined($('comments-form')))
    {
        commentsForm = $('comments-form');
        commentsForm.addEvent('submit',
            function (ev)
            {
                ev.preventDefault();
                request = new Request.JSON({
                    'url':      responder,
                    onComplete: function (response)
                    {
                        cLoading = false;
                        if($defined(response.error))
                        {
                            commentsForm.getElement('textarea').value = '';
                            errorMessage = new Element('p',
                                {
                                    'html':     'Sorry, we\'re unable to post your comment just now, please try again in a minute or two',
                                    'class':    'error'
                                }
                            );
                            if(!$defined(commentsForm.getElement('p.error')))
                            {
                                commentsForm.grab(errorMessage);
                                adjustHeights();
                            }
                            commentsForm.getElement('p.error').highlight('#F91C01','#e1d7c7');
                            return false;
                        }
                        commentsForm.getElement('textarea').value = '';
                        token = response.token;
                        addComment(response.comment);
                        adjustHeights();
                        trackEvent('profileaddcomment');
                    }
                }).post({
                    'action':   'addComment',
                    'token':    token,
                    'to_user':  commentsForm.getElement('input[name=to_user]').value,
                    'comment':  commentsForm.getElement('textarea').value
                });
            }
        );
    }
};

var addComment = function (r)
{
    div = new Element('div',
        {
            'class':        'comment'
        }
    );
    div.grab(new Element('p',
    {
       'html':          r.date + ' | posted by you',
       'class':         'details'
    }));
    div.grab(new Element('p',
    {
        'html':         r.comment
    }
    ));
    $('comments').grab(div,'top');
    if($defined($('no-comments')))
    {
        $('no-comments').destroy();
    }
    div.highlight('#F91C01','#FFF');
};

var addFriendListener = function ()
{
    if(!$defined($('request-friend')))
    {
        return false;
    }
    
    $('request-friend').addEvent('click',
        function (ev)
        {
            ev.preventDefault();
            request = new Request.JSON(
                {
                    'url':      responder,
                    'link':     'cancel',
                    onRequest:  function()
                    {
                        if(!loading)
                        {
                            loadingImage = new Element('img',
                                {
                                    'src':      '/images/loading.gif'
                                }
                            );
                            $('profile-options').grab(loadingImage);
                            loading = true;
                        }
                    },
                    onSuccess:  function (response)
                    {
                        $('profile-options').getElement('img').destroy();
                        loading = false;
                        if(response.token)
                        {
                            token = response.token;
                            span = new Element('span',
                            {
                                'html':'Request sent',
                                'class':'button'
                            }).replaces($('request-friend'));
                            addRoundedCorners(span);
                        }
                    }
                }
            ).post({
                'action':       'addFriend',
                'token':        token,
                'username':     $('request-friend').get('rel')
            });
        }
    );
};

var addLightboxListener = function ()
{
    $$('a[rel=lightbox]').each(
        function (link)
        {
            link.addEvent('click',
                function (ev)
                {
                    ev.preventDefault();
                    x   = $('container').getSize().x;
                    y   = $('container').getSize().y;
                    pX  = $('container').getPosition().x;
                    pY  = $('container').getPosition().y;

                    styles = {
                        'position':     'absolute',
                        'width':        x,
                        'height':       y,
                        'top':          pY,
                        'left':         pX,
                        'text-align':   'center'
                    };

                    lb = new Element('div',{'class':'lightbox'});
                    
                    lb.setStyles(styles);
                    lb2 = lb.clone();
                    
                    lb.setStyles({'opacity':0,'background':'#FFF'});
                    im = new Element('img',
                        {
                            'src':      link.href
                        }
                    );
                    lb2.grab(im);
                    
                    if($defined($('request-friend')) && !link.hasClass('gordon'))
                    {
                        p = new Element('p');
                        report = new Element('a',
                            {
                                'html':     'Report Image as offensive',
                                'href':     '#'
                            }
                        );

                        lb2.appendText('');
                        p.grab(report);
                        lb2.grab(p);

                        report.addEvent('click',
                            function (ev)
                            {
                                ev.preventDefault();
                                r = new Request.JSON({
                                    'url':      responder,
                                    onSuccess:  function (response)
                                    {
                                        token = response.token;
                                    }
                                }).post({
                                    'action':   'reportImage',
                                    'token':     token,
                                    'image':     link.getElement('img').get('alt')
                                });
                            }
                        );
                    }
                    
                    document.getElement('body').grab(lb);
                    tweener = new Fx.Tween(lb);
                    tweener.start('opacity',0,0.8).addEvent('complete',
                        function()
                        {
                            document.getElement('body').grab(lb2);
                        }
                    );

                    lb2.addEvent('click',
                        function()
                        {
                            im.destroy();
                            lb2.destroy();
                            tweener = new Fx.Tween(lb);
                            tweener.start('opacity',0.8,0).addEvent('complete',
                                function ()
                                {
                                    lb.destroy();
                                }
                            );
                        }
                    );

                    // lb.addEvent('click',
                    //     function (ev)
                    //     {
                    //         lb.fade('out').addEvent('complete',
                    //             function ()
                    //             {
                    //                 alert('destroying');
                    //                 this.destroy();
                    //             }
                    //         );
                    //     }
                    // );
                }
            );
        }
    );
};

var adjustHeights = function ()
{
    if(!Browser.Engine.trident && $defined($('friends')))
    {
        top = $('friends').getPosition().y;
        bottom = $('comments-form').getSize().y;
        bottom = bottom + $('comments-form').getPosition().y;
        newHeight = bottom-top;
        if($('places-to-eat').getSize().y < newHeight)
        {
            $('places-to-eat').setStyle('height',bottom-top);
        }
    }
};

var initReportCommentLinks = function ()
{
    $$('div#comments a.report').each(
        function (l)
        {
            l.addEvent('click',
                function (ev)
                {
                    ev.preventDefault();
                    r = new Request.JSON({
                        'url':  responder,
                        onSuccess: function ()
                        {
                            span = new Element('span',{
                                'html': 'reported'
                            });
                            span.replaces(l);
                        }
                    }).post({
                        'action':       'reportComment',
                        'token':        token,
                        'comment_id':   l.get('rel')
                    });
                }
            );
        }
    );
};

var initReportStatusLinks = function ()
{
    $$('div#status a.report').each(
        function (a)
        {
            reportStatus(a);
        }
    );
};

var reportStatus = function (a)
{
    a.addEvent('click',
        function (ev)
        {
            ev.preventDefault();
            r = new Request.JSON({
                'url':      responder,
                onSuccess:  function(response)
                {
                    token = response.token;
                    styles = a.getStyles();
                    span = new Element('span',{'html':'reported'}).replaces(a);
                    span.setStyles(styles);
                }
            }).post({
                'action':       'reportStatus',
                'token':        token,
                'status_id':    a.get('rel')
            });
        }
    );
};



window.addEvents({
    'domready': function ()
    {
        addStatusListener();
        addCommentListener();
        addFriendListener();
        addLightboxListener();
        addRedArrow();
        roundCorners();
        initReportCommentLinks();
        initReportStatusLinks();
    },
    'load': function ()
    {
        adjustHeights();
    }
});