var i18n = {
    lang: [],
    init: function(lang){
        this.lang = lang;
    },
    get: function(key){
        if (!this.lang[key]) {
            throw 'Unkonwn lang key';
        }
        return this.lang[key];
    }
}

/**
 * @author Sam
 */
function makeDiggable($i18n){
    var responseHandler = function(response){
        if (response['error']) {
            if (response['error'] == 'not logged in') {
                $('#digbut' + response['look_id']).find('span.digit').replaceWith($('<a href="auth.login.do">' + $i18n['LOGIN'] + '</a>'));
            }
            else {
                alert(response['error']);
            }
            return false;
        }
        
        $('#digNumber_' + response['look_id']).text(response['number']);
        $('#digbut' + response['look_id']).css('cursor', 'auto').unbind('click').find('span.digit').replaceWith($('<span>' + $i18n['DUGG'] + '</span>'));
        
        return false;
    };
    
    $('.dig_button>span.digit').css('cursor', 'pointer').click(function(event){
        $.getJSON('look.dig.do', {
            'id': $(this.parentNode).attr('id').substr(6)
        }, responseHandler)
    });
}

// for sign up
function nameAvailableCheck($i18n){
    var responseHandler = function(response){
        if (response['available'] == 'true') 
            $('#avail').text($i18n['NAME_AVAILABLE']).removeClass('error').addClass('name_available');
        else 
            $('#avail').text(response['error']).removeClass('name_available').addClass('error');
    };
    
    var check = function(event){
        var e = $(this);
        var value = $.trim(e.val());
        if (value == e.attr('previousValue')) {
            return;
        }
        e.attr('previousValue', value);
        if (value.length < 2) {
            $('#avail').text($i18n['NAME_TOO_SHORT']).removeClass('name_available').addClass('error');
            return;
        }
        $.getJSON('acc.nameAvailable.do', {
            'name': value
        }, responseHandler)
    };
    
    $('#username').keyup(check).change(check);
}

//for comment
function submitComment($i18n){
    var responseHandler = function(response){
        $.unblockUI();
        if (response['error']) {
            alert(response['error']);
            return false;
        }
        
        var template = $(".comment:first");
        var comment = template.clone().insertBefore(template).hide();
        comment.find('.user_icon a img').attr('src', response['avatar']);
        comment.find('.user_icon a').attr('href', response['user_link']);
        comment.find('.comment_summary').html(response['comment_summary']);
        comment.find('.comment_content').text(response['comment_desc']);
        
        comment.slideDown("slow");
        
        comment.find('.comment_delete_button').click(function(){
            commentDelete(this, response['comment_id']);
        });
        
        $('#comment').val("");
        
        return false;
    };
    
    $('#submit_comment').click(function(event){
        $.getJSON('comment.add.do', {
            'id': $('#articleId').val(),
            'comment': $('#comment').val()
        }, responseHandler);
        
        $.blockUI({
            message: '<h1>正在提交留言……</h1>'
        });
    });
}

function commentReply(element, commentId){

    var responseHandler = function(response){
        $.unblockUI();
        if (response['error']) {
            alert(response['error']);
            return false;
        }
        
        var template = $(".comment_reply:first");
        var threadDiv = replyForm.parent().parent().find('.comment_thread');
        
        var comment = template.clone().appendTo(threadDiv);
        comment.find('.user_icon a img').attr('src', response['avatar']);
        comment.find('.user_icon a').attr('href', response['user_link']);
        comment.find('.comment_summary').html(response['comment_summary']);
        comment.find('.comment_content').text(response['comment_desc']);
        
        comment.slideDown("slow");
        
        comment.find('.comment_reply_delete_button').click(function(){
            commentDelete(this, response['comment_id']);
        });
        
        replyForm.find('#reply_comment').val("");
        
        return false;
    };
    
    var element = $(element).hide();
    var replyForm = $('#reply_form_template').clone().insertBefore(element).slideDown("fast");
    
    replyForm.find('.button').click(function(event){
        $.getJSON('comment.reply.do', {
            'id': commentId,
            'comment': replyForm.find('#reply_comment').val()
        }, responseHandler);
        
        $.blockUI({
            message: '<h1>正在提交回复……</h1>'
        });
        
        setTimeout(function(){
            $.unblockUI();
        }, 15000);
    });
    
}


function commentDelete(element, commentId){
    var responseHandler = function(response){
        if (response['error']) {
            alert(response['error']);
            return false;
        }
        var commentDiv = element.parent().parent().parent().parent();
        commentDiv.slideUp('slow', function(){
            commentDiv.remove();
        });
    }
    
    var element = $(element);
    $.getJSON('comment.delete.do', {
        'id': commentId
    }, responseHandler);
    
}

// for message
function replyMessage(threadId){
    var responseHandler = function(response){
        if (response['error']) {
            alert(response['error']);
            return false;
        }
        
        var template = $(".inbox:first");
        var message = template.clone().appendTo("#inboxs");
        message.find('.user_icon a img').attr('src', response['avatar']);
        message.find('.user_icon a').attr('href', response['my_link']);
        message.find('.inbox_info').html(response['outbox_info']);
        message.find('.inbox_content').text(response['body']);
        
        message.slideDown("slow");
        
        $('#message_body').val("");
        
        $.unblockUI();
        return false;
    };
    
    $.getJSON('message.reply.do', {
        'toId': $('#toId').val(),
        'threadId': $('#threadId').val(),
        'body': $('#message_body').val()
    }, responseHandler);
    
    $.blockUI({
        message: '<h1>正在提交回复……</h1>'
    });
    
    setTimeout(function(){
        $.unblockUI();
    }, 15000);
    
}

//$(document).ajaxSuccess($.unblockUI);
//$(document).ajaxError(function(){
//	$.blockUI({
//		'message': '<h1>失败，请重新发送！</h1>'
//	});
//	setTimeout($.unblockUI, 2000);
//});

function messageDelete(element, threadId, messageId){
    var responseHandler = function(response){
        if (response['error'] != "ok") {
            alert(response['error']);
            return false;
        }
        var inboxDiv = element.parent().parent().parent();
        inboxDiv.slideUp('slow', function(){
            inboxDiv.remove();
        });
    }
    
    var element = $(element);
    $.getJSON('message.delete.do', {
        'threadId': threadId,
        'messageId': messageId
    }, responseHandler);
}

function conversationDelete(threadId){
    var responseHandler = function(response){
        if (response['error'] == "ok") {
            return location.href = "/message.inbox.do";
        }
        else {
            alert(response['error']);
            return false;
        }
    }
    
    $.getJSON('message.delete.do', {
        'threadId': threadId
    }, responseHandler);
}



// setup message checker deamon
$(function(){
    var docTitle = document.title;
    var noticeTimer = 0;
    var flashCount = 1;
    
    var flashTitle = function(updates){
        if (flashCount % 2 == 1) {
            document.title = updates['message'] + updates['notification'] + ' - ' + docTitle;
        }
        else {
            document.title = docTitle;
        }
        flashCount++;
    };
    
    var resultHandler = function(result, status){
        if (result['error'] == 'not logged in') {
            clearInterval(timer);
            return;
        }
        
        var container = $('#messageLinks');
        var newMessageLabel = container.find('.new_message').css('display', 'none');
        var newNotificationLabel = container.find('.new_notification').css('display', 'none');
        
        clearInterval(noticeTimer);
        if (!result['updates']) {
            document.title = docTitle;
        }
        else {
            if (result['updates']['message']) {
                if (newMessageLabel.size() == 0) {
                    newMessageLabel = $('<a class="new_message" href="#"></a>').appendTo(container);
                }
                newMessageLabel.attr('href', result['updates']['messageURL']).text(result['updates']['message']).css('display', 'inline');
            }
            
            if (result['updates']['notification']) {
                if (newNotificationLabel.size() == 0) {
                    newNotificationLabel = $('<a href="/message.notification.do"></a>').addClass('new_notification').appendTo(container);
                }
                newNotificationLabel.text(result['updates']['notification']).css('display', 'inline');
            }
            
            noticeTimer = setInterval(function(){
                flashTitle(result['updates']);
            }, 1500);
        }
    };
    
    var messageChecker = function(){
        $.getJSON('/message.checkNew.do', null, resultHandler);
    };
    var timer = setInterval(messageChecker, 30000);
    
    // setted in the html page files
    if (typeof(updatesFirstTime) != "undefined") {
        noticeTimer = setInterval(function(){
            flashTitle(updatesFirstTime);
        }, 1500);
    }
    
});

function setMyStatus(control){
    //var setStatusCount;
    var setStatus = $('#set_status');
    var responseHandler = function(response){
        if (response['error']) {
            alert(response['error']);
            return false;
        }
        if ($('#status_body').get(0)) {
            $('#status_body>#status').html("<span style='cursor:pointer;' onclick='setMyStatus()'>" + response['status'] + "</span>");
            $('#remove').find('a').attr('rel', response['status_id']);
            $('#remove').find('a').show();
            operate();
        }
        else {
            var status = $(".status:last").clone().insertBefore('.status:first');
            
            status.find('.status_content').text(response['status']);
            status.find('.time').text(response['status_time']);
            
            status.slideDown("slow");
        }
        setStatus.find('#content').val('');
        return false;
    };
    var operate = function(control){
        if (control == 'submit') {
            $.getJSON('status.submit.do', {
                'status': setStatus.find('#content').val()
            }, responseHandler);
        }
        else {
            if (setStatusCount % 2) {
                setStatus.slideDown("fast");
            }
            else {
                setStatus.slideUp("fast");
            }
            setStatusCount++;
        }
    };
    if (typeof(setStatusCount) == "undefined") {
        setStatusCount = 1;
    }
    operate(control);
}

function removeStatus($i18n){
    var responseHandler = function(response){
        if (response['error']) {
            alert(response['error']);
            return false;
        }
        element.find('a').hide();
        $('#status_body>#status').html("<span style=\"cursor:pointer;color:#ccc\" onclick=\"setMyStatus()\">" + $i18n['WHAT_ARE_YOU_DOING_TEXT'] + "</span>");
    }
    var element = $('#remove');
    element.click(function(event){
        $.getJSON('status.delete.remove.do', {
            'id': element.find('a').attr('rel')
        }, responseHandler);
    });
}

function deleteStatus(element, id){
    var responseHandler = function(response){
        if (response['error']) {
            alert(response['error']);
            return false;
        }
        var statusDiv = element.parent().parent().parent();
        statusDiv.slideUp('slow', function(){
            statusDiv.remove();
        });
    }
    var element = $(element);
    $.getJSON('status.delete.do', {
        'id': id
    }, responseHandler);
}
