jQuery(function() {
    jQuery.each(jQuery('.btnKeep a'), function(index, obj) {
        if (obj.className != 'allFavorite') {
            doorObserve(this, 'add');
        }
    });
    jQuery.each(jQuery('.btnDelete a'), function(index, obj) {
        if (obj.className != 'allFavorite') {
            doorObserve(this, 'remove');
        }
    });
});

function doorObserve(favoriteBtn, actionType)
{
    Element.observe(favoriteBtn, 'click', function() {
        operateFavorite(actionType, [favoriteBtn.parentNode.value]);
        showFavoriteMsg(actionType);
        jQuery.each(jQuery('.' + favoriteBtn.parentNode.className + ' a'), function(index, similarBtn) {
            if (similarBtn.parentNode.value == favoriteBtn.parentNode.value) {
                similarBtn.parentNode.className = (actionType == 'add' ? 'btnDelete' : 'btnKeep');
                similarBtn.className = (actionType == 'add' ? 'deleteListBtn' : 'checkListBtn');
                Event.stopObserving(similarBtn, 'click');
                setTimeout(function() {doorObserve(similarBtn, actionType == 'add' ? 'remove' : 'add')}, 1000);
            }
        });

        favoriteBtn.parentNode.className = (actionType == 'add' ? 'btnDelete' : 'btnKeep');
        updateDoorRentBukkenFavorite(actionType, 1);
    });
}

function updateDoorRentBukkenFavorite(actionType, num)
{
    var currentCount = parseInt($('doorRentBukkenFavoriteCount').innerHTML);
    $('doorRentBukkenFavoriteCount').innerHTML = ((actionType == 'add') ? (currentCount + num) : (currentCount - num));
}

function showFavoriteMsg(actionType)
{
    var msg = "検討物件に追加しました";
    var msgHtml = "<img src='/img/front/search_result/list_add_icon2.png'>" + msg;
    if (actionType == 'remove') {
        var msg = "検討から削除しました";
        msgHtml = "<img src='/img/front/search_result/list_delete_btn2.png'>" + msg;
    }
    if (jQuery.notifyBar) {
        jQuery.notifyBar({
             html: msgHtml,
             delay: 1000,
             animationSpeed: "normal"
        });
    } else {
        alert(msg);
    }
}

function operateFavorite(actionType, bukkenIds)
{
    var params = '';
    for (var i = 0; i < bukkenIds.length; i ++) {
        if (i != 0) {
            params += '&';
        }
        params += 'id[]=' + bukkenIds[i];
    }
    new Ajax.Request(
        '/favorite/' + actionType,
        {
            method: 'get',
            parameters: params,
            asynchronous: false
        }
    );
}

function setDoorCookie(actionType, bukkenId)
{
    bukkenId = String(bukkenId).replace(/^0*/, '');
    var EXPIRE_LIMIT = 1000 * 60 * 60 * 24 * 7 * 2;
    var dat = new Date();
    var limitTime = (actionType == 'add') ? (dat.getTime() + EXPIRE_LIMIT) : (dat.getTime() - EXPIRE_LIMIT);
    dat.setTime(limitTime);
    expire = dat.toGMTString();
    document.cookie = 'doorRentBukkenFavorite[' + bukkenId + ']=' + Math.floor((new Date().getTime() / 1000)) + ';path=/;expires='+expire;
}

