jQuery(function(){

    addCloseIntro();

    if(jQuery('#wrapper').length > 0){
        addRequestUserTimeline();
        addRequestReplies();
        addRequestFavorites();
        addRequestHome();
        addTwitterCounter();
        addUrlShortener();
        addRequestUpdateStatus();
        addEvents();
    }

})

function addEvents(context){
    addHovers(context);
    addFavorite(context);
    addRemoveFavorite(context);
    addReply(context);
    addDelete(context);
    //addPagination();
}

function addRequestUpdateStatus(){
    jQuery('#update-submit').click(function(){
        if(jQuery('#status').val().length > 140){
            alert('Votre tweet ne peut pas faire plus de 140 caractères');
            return false;
        }
        var data = jQuery('form#status_update_form').serialize();
        var context = jQuery('#timeline').attr('class').split(' ').slice(-1);
        jQuery('#status').attr('disabled','disabled');
        jQuery.ajax({
            type:'POST',
            url:'/',
            data:'request=updateStatus&'+data,
            dataType:'json',
            success:function(json){
                if(json.state == 'ok'){
                    if(context == 'home'){
                        jQuery('#timeline').prepend(json.status);
                        jQuery('#timeline li:first').slideDown();
                    }
                    jQuery('#currently').html(json.currently);
                    jQuery('#user-tweet-count').html(json.nbtweets+' tweets');
                    addEvents();
                    jQuery('#status').attr('disabled',false);
                    jQuery('#status').val('');
                    jQuery('#in_reply_to_status_id').val('');
                    jQuery('#in_reply_to').val('');
                }
                else{
                    alert(json.error);
                }
            },
            error:function(){
                jQuery('#status').attr('disabled',false);
                alert('Une erreur est survenue, veuillez réessayer');
            }
        })
        return false;

    })
}

function addRequestUserTimeline(){

    jQuery('.get-user-timeline').click(function(){
        var h = jQuery(this).parents('h2,h4').addClass('loading');
        jQuery.ajax({
            type:'GET',
            url:'/',
            data:'request=user',
            dataType:'json',
            success:function(json){
                jQuery('#content').html(json);
                h.removeClass('loading');
                addEvents();
            }
        })
        return false;
    })

}

function addRequestReplies(){

    jQuery('.request-replies').click(function(){
        var li = jQuery(this).parents('li').addClass('loading');
        jQuery.ajax({
            type:'GET',
            url:'/',
            data:'request=replies',
            dataType:'json',
            success:function(json){
                jQuery('#content').html(json);
                li.removeClass('loading');
                addEvents();
            }
        })
        return false;
    })

}
function addRequestFavorites(){

    jQuery('.request-favorites').click(function(){
        var li = jQuery(this).parents('li').addClass('loading');
        jQuery.ajax({
            type:'GET',
            url:'/',
            data:'request=favorites',
            dataType:'json',
            success:function(json){
                jQuery('#content').html(json);
                li.removeClass('loading');
                addEvents();
            }
        })
        return false;
    })
}
function addRequestHome(){

    jQuery('.request-home').click(function(){
        var li = jQuery(this).parents('li').addClass('loading');
        jQuery.ajax({
            type:'GET',
            url:'/',
            data:'request=home',
            dataType:'json',
            success:function(json){
                jQuery('#content').html(json);
                li.removeClass('loading');
                addEvents();
            }
        })
        return false;
    })
}

function addPagination(){
    jQuery('#more').click(function(){
        var context = jQuery('#timeline').attr('class').split(' ').slice(-1);
        var page = jQuery(this).attr('href').split('=');
        page = page[1];
        var pthis = jQuery(this);
        jQuery.ajax({
            type:'GET',
            url:'/',
            data:'request='+context+'&page='+page,
            dataType:'json',
            success:function(json){
                alert(json);
            }
        })
        return false;
    })
}

function addHovers(context){
    if(typeof(context) == undefined){
        context = '#content';
    }
    jQuery('li.status',context).unbind('hover');
    jQuery('li.status',context).hover(
        function(){
            jQuery(this).addClass('hover');
        },
        function(){
            jQuery(this).removeClass('hover');
        }
    )
}

function addFavorite(context){
    if(typeof(context) == undefined){
        context = '#content';
    }
    jQuery('.fav-action.non-fav',context).unbind('click');
    jQuery('.fav-action.non-fav',context).click(function(){
        var pthis = jQuery(this);
        var statusId = pthis.attr('href').split('/');
        statusId = statusId[statusId.length - 1];
        jQuery.ajax({
            type:'GET',
            url:'/',
            data:'request=addFavorite&statusId='+statusId,
            dataType:'json',
            success:function(json){
                if(json.state == 'ok'){
                    pthis.removeClass('non-fav');
                    pthis.addClass('fav');
                    pthis.attr('title','retirer des favoris');
                    addRemoveFavorite('#status_'+statusId);
                }
                else{
                    alert(json.error);
                }
            }
        })
        return false;
    })
}

function addDelete(context){
    if(typeof(context) == undefined){
        context = '#content';
    }
    jQuery('.delete',context).unbind('click');
    jQuery('.delete',context).click(function(){
        var listatus = jQuery(this).parents('li.status');
        var statusId = jQuery(this).attr('href').split('/');
        statusId = statusId[statusId.length - 1];
        jQuery.ajax({
            type:'GET',
            url:'/',
            data:'request=removeStatus&statusId='+statusId,
            dataType:'json',
            success:function(json){
                if(json.state == 'ok'){
                    listatus.slideUp('normal', function(){listatus.remove()});
                    jQuery('#currently').html(json.currently);
                    jQuery('#user-tweet-count').html(json.nbtweets+' tweets');
                }
                else{
                    alert(json.error);
                }
            }
        })
        return false;
    })
}
function addReply(context){
    if(typeof(context) == undefined){
        context = '#content';
    }
    jQuery('.reply',context).unbind('click');
    jQuery('.reply',context).click(function(){
        var string = jQuery(this).attr('href').split('=');
        var status = string[1].split('&');
        status = status[0].replace('%20',' ');
        var in_reply_to_status_id = string[2].split('&');
        in_reply_to_status_id = in_reply_to_status_id[0];
        var in_reply_to = string[3];
        jQuery('#status').val(jQuery('#status').val()+status);
        //console.info(in_reply_to_status_id+' - '+in_reply_to);
        jQuery('#in_reply_to_status_id').val(in_reply_to_status_id);
        jQuery('#in_reply_to').val(in_reply_to);
        jQuery('#status').focus();
        return false;
    })
}
function addRemoveFavorite(context){
    if(typeof(context) == undefined){
        context = '#content';
    }
    jQuery('.fav-action.fav',context).unbind('click');
    jQuery('.fav-action.fav',context).click(function(){
        var pthis = jQuery(this);
        var statusId = pthis.attr('href').split('/');
        statusId = statusId[statusId.length - 1];
        jQuery.ajax({
            type:'GET',
            url:'/',
            data:'request=removeFavorite&statusId='+statusId,
            dataType:'json',
            success:function(json){
                if(json.state == 'ok'){
                    pthis.removeClass('fav');
                    pthis.addClass('non-fav');
                    pthis.attr('title','ajouter aux favoris');
                    addFavorite('#status_'+statusId);
                }
                else{
                    alert(json.error);
                }
            }
        })
        return false;
    })
}

function addTwitterCounter(){
    jQuery('#status').twitterCounter({
        limit: 140,
        counter: '#chars_left_notice',

        okSize: 140,
        okStyle: '.ok',

        watchSize: 20,
        watchStyle: '.watch',

        warningSize: 10,
        warningStyle: '.warning',

        errorSize: 0,
        errorStyle: '.error'
    });
}

function addUrlShortener(){
    jQuery('#shorten-url').click(function(){
        var url = jQuery('#url_to_shorten').val();
        if(url.length == 0){
            alert('Veuillez rentrer une adresse internet');
            return false;
        }
        jQuery.ajax({
            type:'POST',
            url:'/',
            data:'request=shortenUrl&url='+url,
            dataType:'json',
            success:function(json){
                if(json === false || json === "Error: The URL entered was not valid."){
                    alert('Veuillez rentrer une adresse internet correcte')
                    return false;
                }
                jQuery('#status').val(jQuery('#status').val()+json);
                jQuery('#status').focus();
            }
        })

    })
}

function addCloseIntro(){
    jQuery('.closeIntro').click(function(){
        jQuery('#intro').slideUp();
    })
}