if (typeof _EMONYU == 'undefined') {
    var _EMONYU = {};
}

if (/^dev\./.test(location.host)) {
    _EMONYU.STATIC_HOST = '';
} else {
    var s3version = 30; // sed target
    if (location.host == 'emonyu.jp') {
        _EMONYU.STATIC_HOST = 'http://static.' + location.host + '/' + s3version;
    } else {
        _EMONYU.STATIC_HOST = 'http://static-' + location.host + '/' + s3version;
    }
}

_EMONYU.EMOTION_ID = {
    "h": 1,
    "u": 2,
    "j": 3,
    "s": 4,
    "p": 5,
    "a": 6,
    "su": 7
};
_EMONYU.EMOTION_CHAR = {
    "1": "h",
    "2": "u",
    "3": "j",
    "4": "s",
    "5": "p",
    "6": "a",
    "7": "su"
};

_EMONYU.DEFAULT_EMOTION_CHAR = 'h';
_EMONYU.inputedMemo = false;
_EMONYU.MEMO_MAX_LENGTH = 20;

_EMONYU.hasLatestEmotion = function() {
    return $('#emo_latest_img').attr('src');
}

_EMONYU.notSwitchEmotion = function(img) {
    return img.src.match(/icon_[a-z][a-z]?_hover\.gif$/);
}

_EMONYU.getEmotionCharFromFeelingButton = function(img) {
    img.src.match(/icon_([a-z][a-z]?)(_hover)?\.gif$/);
    return RegExp.$1;
}

_EMONYU.getPointFromSlider = function() {
    return $('#point_slider').slider('value', 0);
}

_EMONYU.createEmotionIconSrc = function(point, emotionChar, size) {
    var src = _EMONYU.STATIC_HOST + '/img/emotion/' + size + '/' + emotionChar;
    if (point >= 80) {
        src += '3.gif';
    }
    else if (point >= 50) {
        src += '2.gif';
    } else {
        src += '1.gif';
    }
    return src;
}

_EMONYU.setPreviewEmotion = function(src) {
    $('#preview .face img').attr('src', src);
}

_EMONYU.removeHoverFromAllFeelingButtons = function() {
    $('#entry_feeling ul li img').each(function() {
        $(this).attr('src', function() {
            return this.src.replace(/_hover/, '');
        });
    });
}

_EMONYU.getEmotionIdByChar = function(c) {
    return _EMONYU.EMOTION_ID[c];
}

_EMONYU.getEmotionIdBySrc = function(src) {
    for (var char in _EMONYU.EMOTION_ID) {
        if (src.match(new RegExp(char + '[0-9]\.gif'))) {
            return _EMONYU.EMOTION_ID[char];
        }
    }
}

/* 投稿フォームの感情選択時の動作 */
_EMONYU.switchEmotion = function(img) {
    if (this.notSwitchEmotion(img)) {
        return true;
    }

    var emotionChar = this.getEmotionCharFromFeelingButton(img);
    var point = this.getPointFromSlider();
    var src = this.createEmotionIconSrc(point, emotionChar, 72);

    this.setPreviewEmotion(src);

    this.removeHoverFromAllFeelingButtons();

    $(img).attr('src', function() {
        return this.src.replace(/\.gif/, '_hover.gif');
    });

    $('input[name="emotion_id"]').val(this.getEmotionIdByChar(emotionChar));
}

_EMONYU.getLatestEmotionChar = function() {
    if (this.hasLatestEmotion()) {
        $('#emo_latest_img').attr('src').match(/([a-z][a-z]?)\d\.gif$/);
        return RegExp.$1;
    }
    return this.DEFAULT_EMOTION_CHAR;
}

_EMONYU.getLatestPoint = function() {
    if (!$('#emo_latest_img').attr('src')) {
        return 50;
    }
    $('#emo_latest_img').attr('src').match(/[a-z][a-z]?(\d)\.gif/);
    var level = RegExp.$1;
    if (level == 3) {
        return 100;
    }
    else if (level == 2) {
        return 50;
    }
    else if (level == 1) {
        return 0;
    }
    return null;
}

_EMONYU.replaceIconByPoint = function(point) {
    if (point >= 80) {
        $('#preview .face img').attr('src', function(){ return this.src.replace(/[0-9]\.gif/, '3.gif'); });
    }
    else if (point >= 50) {
        $('#preview .face img').attr('src', function(){ return this.src.replace(/[0-9]\.gif/, '2.gif'); });
    } else {
        $('#preview .face > img').attr('src', function(){ return this.src.replace(/[0-9]\.gif/, '1.gif'); });
    }
}

_EMONYU.convertPointToKana = function(point) {
    if (point == null) {
        return 'まあまあ';
    }
    if (point >= 80) {
        return 'かなり';
    }
    else if (point >= 50) {
        return 'まあまあ';
    }
    return 'ちょっと';
}

_EMONYU.getEmotionCharFromEmotionId = function(emotionId) {
    if (emotionId == 1) {
        return 'h';
    }
    if (emotionId == 2) {
        return 'u';
    }
    if (emotionId == 3) {
        return 'j';
    }
    if (emotionId == 4) {
        return 's';
    }
    if (emotionId == 5) {
        return 'p';
    }
    if (emotionId == 6) {
        return 'a';
    }
    if (emotionId == 7) {
        return 'su';
    }
}

/* スライダーの初期セットアップ */
_EMONYU.initSlider = function(startValue) {
    if (startValue == null) {
        startValue = 50;
    }
    $('#point_slider').slider({
        startValue: startValue,
        steps: 2,
        slide: function() {
            var point = _EMONYU.getPointFromSlider();
            //$('#point').text(point);
            $('#point').text(_EMONYU.convertPointToKana(point));
            $('input[name="point"]').val(point);
            _EMONYU.replaceIconByPoint(point);
        }
    });
}

/* home画面での投稿フォームの初期設定 */
_EMONYU.initPostForm = function() {
    this.initSlider(this.getLatestPoint());

    var lastEmotionChar = this.getLatestEmotionChar();
    var point = this.getLatestPoint();
    this.replaceIconByPoint(point);

    $('#point').text(_EMONYU.convertPointToKana(point));
    $('input[name="point"]').val(point);

    if (_EMONYU.hasLatestEmotion()) {
        this.setPreviewEmotion($('#emo_latest_img').attr('src'));
    }

    $('#entry_feeling ul li img[src*="icon_' + lastEmotionChar + '."]').attr('src', function() {
        return this.src.replace(/\.gif/, '_hover.gif');
    }).addClass('on');

    $('input[name="emotion_id"]').val(this.getEmotionIdByChar(lastEmotionChar));

    $('#entry_feeling ul li img').each(function() {
        $(this).bind('click', function() {
            _EMONYU.switchEmotion(this);
        });
        $(this).css('cursor', 'pointer');
    });

    $('input[name="memo"]').val('いまの気持ちをひとこと (' + _EMONYU.MEMO_MAX_LENGTH + '文字)').css('color', '#aaa');
}

/* 投稿編集画面での投稿フォームの設定 */
_EMONYU.setupPostForm = function() {
    this.initSlider($('input[name="point"]').val());

    var point = $('input[name="point"]').val();
    this.replaceIconByPoint(point);

    $('#point').text(_EMONYU.convertPointToKana(point));
    $('input[name="point"]').val(point);

    var emotionChar = this.getEmotionCharFromEmotionId($('input[name="emotion_id"]').val());
    this.setPreviewEmotion(this.createEmotionIconSrc(point, emotionChar, 72));

    $('#entry_feeling ul li img[src*="icon_' + emotionChar + '."]').attr('src', function() {
        return this.src.replace(/\.gif/, '_hover.gif');
    }).addClass('on');

    $('#entry_feeling ul li img').each(function() {
        $(this).bind('click', function() {
            _EMONYU.switchEmotion(this);
        });
        $(this).css('cursor', 'pointer');
    });
}

_EMONYU.statusCreate = function(form) {
    if (!_EMONYU.inputedMemo) {
        form.memo.value = '';
    }
    form.submit();
    return false;
}

_EMONYU.checkAgreement = function() {
    if (document.user_create.agree_on_tos.checked) {
        $('#user_create_submit').attr('disabled', false);
    } else {
        $('#user_create_submit').attr('disabled', true);
    }
}

_EMONYU.deleteIcon = function() {
    if (confirm('現在設定されているプロフィール画像を削除します。よろしいですか？')) {
        document.icon_create.action = '/icon/delete';
        document.icon_create.submit();
    }
    return false;
}

_EMONYU.leave = function() {
    if (confirm('退会処理を実行します。よろしいですか？')) {
        document.leave.submit();
    }
    return false;
}

_EMONYU.toggleChartDisplay = function(id) {
    var postfixes = [
        'last_month',
        'this_month',
        'all'
    ];
    id.match(/^show_summary_(.+)$/);
    var targetPostfix = RegExp.$1;
    for (var i = 0; i < postfixes.length; i++) {
        var postfix = postfixes[i];
        if (postfix == targetPostfix) {
            $('#chart_' + postfix).show();
            $('#table_' + postfix).show();
            $('#show_summary_' + postfix).addClass('chart_selected').removeClass('clickable');
        } else {
            $('#chart_' + postfix).hide();
            $('#table_' + postfix).hide();
            $('#show_summary_' + postfix).addClass('clickable').removeClass('chart_selected');
        }
    }
}

// initialize
$(document).ready(function() {
    if (location.href.match(/\/home$/)) {
        _EMONYU.initPostForm();
    }
    else if (location.href.match(/\/edit\/[0-9]+$/)) {
        _EMONYU.inputedMemo = true;
        _EMONYU.setupPostForm();
    }

    $('input[name="memo"]').focus(function() {
        if (!_EMONYU.inputedMemo) {
            $('input[name="memo"]').val('').css('color', '#000');
            _EMONYU.inputedMemo = true;
        }
    });

    // status_delete
    $('span.status_delete').click(function() {
        if (confirm('この気持ちを削除します。よろしいですか？')) {
            $(this).attr('id').match(/^status_delete_(\d+)$/);
            var id = RegExp.$1;
            var endPoint = '/status/delete/' + id + '?format=json';
            var data = {
                'one_time_token': $('input[name="one_time_token"]:first').val()
            }
            $.ajax({
                "type": "POST",
                "url": endPoint,
                "data": data,
                "success": function(json) {
                    json = eval("(" + json + ")");
                    var nextEmo = undefined;
                    if ($('div.emoybox:hidden:first')) {
                        nextEmo = $('div.emoybox:hidden:first');
                    }
                    $('#emobox_' + json.status_id).fadeOut(1000, function() {
                        $(this).remove();
                        //location.reload();
                    });
                }
            });
        }
    });

    // sympathy_create
    $('span.sympathy_create').mouseover(function() {
        $(this).toggleClass('over');
    });
    $('span.sympathy_create').click(function() {
        $(this).attr('id').match(/^sympathy_create_(\d+)$/);
        var statusId = RegExp.$1;
        var endPoint = '/sympathy/create/?format=json';
        var data = {
            'status_id': statusId,
            'one_time_token': $('input[name="one_time_token"]:first').val()
        }
        $.ajax({
            "type": "POST",
            "url": endPoint,
            "data": data,
            "success": function(json) {
                json = eval("(" + json + ")");
                if (json.id) {
                    var buttonId = '#sympathy_create_' + statusId;
                    var sympathyIcon = _EMONYU.STATIC_HOST + '/img/icon_symp.gif';
                    if (!/icon_symp\.gif$/.test($(buttonId + ' ~ img').attr('src'))) {
                        $(buttonId).after($('<img src="' + sympathyIcon + '" />'));
                    }
                    $(buttonId).hide();
                    $('#sympathy_count_' + statusId).text(json.sympathy_count);
                }
            }
        });
    });

    // change_chart
    $('#show_summary_last_month').click(function() {
        _EMONYU.toggleChartDisplay($(this).attr('id'));
    });
    $('#show_summary_this_month').click(function() {
        _EMONYU.toggleChartDisplay($(this).attr('id'));
    });
    $('#show_summary_all').click(function() {
        _EMONYU.toggleChartDisplay($(this).attr('id'));
    });
});

