$(document).ready(function(){
    flashMessage();
    addPopup($('.sidebar-jackets img'));
    $('input:enabled:first').focus();
    initAjaxGetRequest($('.add_to_favorites_links'));
    $('.name-item ul li.fb_like').after('<li class="hatena_star"></li>');
});

function initAjaxGetRequest(target){
    target.each(function(){
        $(this).click(function(){
            ajaxGetRequest($(this));
            return false;
        });
    });
}

function ajaxGetRequest(target){
    var href = target.attr('href');
    var id = target.attr('id');
    $('#' + id + '_msg').remove();
    target.hide();
    target.after('<span id="' + id + '_msg" class="ajax_msg">通信ちゅう...</span>');
    $.get(href, function(res){
        $('#' + id + '_msg').remove();
        $('#' + id).after(res);
        $('#' + id).remove();
    });
    return;
}

function flashMessage(){
    $('#flashMessage').fadeIn(500);
    setTimeout("$('#flashMessage').fadeOut(500)", 3000);
}

function addPopup(target, offset, id) {
    if (typeof(id) == 'undefined') {
        id = 'popupImage';
    }
    if (typeof(offset) == 'undefined') {
        offset = 5;
    }

    $('body').append('<span id="' + id + '"><img src="" /></span>');
    var cssObj = {
        position: 'absolute',
        border: '1px solid #999',
        background: '#FFF'
    }
    $('#' + id).css(cssObj).hide();
    $('#' + id + ' img').css('margin', '5px');

    target.each(function(){
        var imgURL = $(this).attr('src');

        $(this).mouseover(function(e){
            var imgURL = $(this).attr('src'); 
            $('#' + id + ' img').attr('src', imgURL);
            $('#' + id).show();
            setOffset(e);
        });

        $(this).mousemove(function(e){
            setOffset(e);
        });
        
        $(this).mouseout(function(){
            $('#' + id).hide();
        })
    });
    
    function setOffset(e) {
        var sizeX = $('#' + id).outerWidth(); 
        var sizeY = $('#' + id).outerHeight(); 
        offsetX = (e.clientX < $(window).width() / 2) ? offset: -(sizeX + offset);
        offsetY = (e.clientY < $(window).height() / 2) ? offset: -(sizeY + offset);
        var cssObj = {
            top: e.pageY + offsetY,
            left: e.pageX + offsetX
        }
        $('#' + id).css(cssObj);
    }

};

