/**
 * at_cosme site - favorite
 *
 * @author      K.Saitoh
 * @require     jQuery 1.3.2+
 * @require     /js/favorite.js
 * @version     1.0.0
 */

jQuery.atcosme.favorite = {};

/**
 * メッセージ出力用
 */
jQuery.atcosme.favorite.message = {
    conf : { target :'#clipPopup', isIE6: null, isFirst:true, timeoutID:'' },
    link : {    0 : '<ul><li><a href="#">MY＠ｃｏｓｍｅへ</a></li></ul>',
                1 : '<ul><li><a href="#">ログインする</a></li><li><a href="#">新規会員登録</a></li></ul>',
                2 : '<ul><li><a href="#">追加情報登録</a></li></ul>',
                3 : '<ul><li><a href="#">MY＠ｃｏｓｍｅへ</a></li></ul>',
                4 : '<ul><li><a href="#">MY＠ｃｏｓｍｅへ</a></li></ul>',
                5 : ''
        },
    brand : {   0 : '<p>お気に入りブランドに登録しました！</p>',
                1 : '<p>お気に入りブランドに登録するにはログインする必要があります。</p>',
                2 : '<p class="error">登録するにはメンバー情報を追加する必要があります。</p>',
                3 : '<p class="error">このブランドは既に登録されています。</p>',
                4 : '<p class="error">登録できませんでした。</p><p class="ps">※お気に入りブランドは300件までしか登録できません。</p>',
                5 : '<p class="error">システムエラーが発生したため、登録できませんでした。</p>',
                9 : '<p class="question"><a href="#" target="_blank">お気に入りブランドとは</a></p>'
        },
    item : {    0 : '<p>商品をクリップしました！</p>',
                1 : '<p>商品をクリップするにはログインする必要があります。</p>',
                2 : '<p class="error">クリップするにはメンバー情報を追加する必要があります。</p>',
                3 : '<p class="error">この商品は既にクリップされています。</p>',
                4 : '<p class="error">クリップできませんでした。</p><p class="ps">※商品クリップは300件までしか登録できません。</p>',
                5 : '<p class="error">システムエラーが発生したため、クリップできませんでした。</p>',
                9 : '<p class="question"><a href="#" target="_blank">商品クリップとは</a></p>'
        },
    review : {  0 : '<p>クチコミをクリップしました！</p>',
                1 : '<p>クチコミをクリップするにはログインする必要があります。</p>',
                2 : '<p class="error">クリップするにはメンバー情報を追加する必要があります。</p>',
                3 : '<p class="error">このクチコミは既にクリップされています。</p>',
                4 : '<p class="error">クリップできませんでした。</p><p class="ps">※クチコミクリップは300件までしか登録できません。</p>',
                5 : '<p class="error">システムエラーが発生したため、クリップできませんでした。</p>',
                9 : '<p class="question"><a href="#" target="_blank">クチコミクリップとは</a></p>'
        },
    board : {   0 : '<p>chieco投稿をクリップしました！</p>',
                1 : '<p>chieco投稿をクリップするにはログインする必要があります。</p>',
                2 : '<p class="error">クリップするにはメンバー情報を追加する必要があります。</p>',
                3 : '<p class="error">このchieco投稿は既にクリップされています。</p>',
                4 : '<p class="error">クリップできませんでした。</p><p class="ps">※chiecoクリップは300件までしか登録できません。</p>',
                5 : '<p class="error">システムエラーが発生したため、クリップできませんでした。</p>',
                9 : '<p class="question"><a href="#" target="_blank">chieco投稿クリップとは</a></p>'
        },

        /**
        * type ( brand, item, review）
        * messageNum ( 1-ログイン必要、3-既に追加、4-200件以上、9-追加されました、）
        */
    show : function(type, messageNum, x, y, url){
        //初回時のみ
        if(this.conf.isFirst) {
            this.createOutline();
            this.conf.isFirst = false;
        }

        var pop = $(this.conf.target);
        if(pop.data('visible')){ this.hide(); };
        if(this.conf.isIE6==null){ this.conf.isIE6 = $.atcosme.browser.isIE6(); }
        //if(this.conf.isIE6){ $('select').css('visibility', 'hidden'); }

        var that = this;
        $('#clipPopup').find('.close a').click(function(){
            that.hide();
            return false;
        });

        linkMessage = $(this.link[messageNum]);
        anchors = $('a', linkMessage);
        $.each(anchors, function(i, anchor) {
            $(anchor).attr('href', url[i]);
        });
        var word = this[type][messageNum] + '<ul>' + linkMessage.html() + '</ul>'
        helpLink = $(this[type][9]);
        anchor = $('a', helpLink);
        anchor.attr('href', url.pop());
        word += '<p class="question">' + helpLink.html() + '</p>';
        $('#clipPopup').find('.clipPopupBoxWide').html(word);

        //pop.setCenterPos().data('visible', true).show();
        pop.setPos( x, y );
        pop.data('visible', true).show();

        //enterframe
        //that.conf.intervalID = window.setInterval( that.delayHide, 20);
    },
    hide : function(){
        if(!$.atcosme.overlay.is() && this.conf.isIE6){
            $('select').not('.dummy').css('visibility', 'visible');
        }
        $(this.conf.target).data('visible', false).hide()
            .find('.close a').unbind('click');

    },
    write : function(html){
        $(this.conf.target).find('p.txt').html(html);
    },
    is: function(){
        return ($(this.conf.target).data('visible'));
    },
    error: {
        maxnum: function(){
            return arguments[0] +'が'+ arguments[1] +'箇所以上選択されています。';
        },
        required: function(){
            return arguments[0] +'は必須です。';
        },
        noResultList: function(){
            return '申し訳ございません。<br />ご指定の検索条件に該当する物件はありません。';
        }
    },
    //外形の作成
    createOutline: function(){
        var that = this;

        $('body').append('<div id="clipPopup"><p class="close"><a href="#">閉じる</a></p><div class="clipPopupBoxBottom"><div class="clipPopupBoxWide"></div></div></div>');
        $('#clipPopup').css({position: 'absolute', 'z-index': '10000' }).data('visible', false).hide();
        $('#clipPopup').hover(
            function(e){
                window.clearTimeout( that.conf.timeoutID );
            },
            function(e){
                that.conf.timeoutID = window.setTimeout( that.delayHide, 300 );
            }
        );
    },
    delayHide: function() {
        $('#clipPopup').hide();
    }
};

/**
 *  お気に入りに追加のイベント登録
 */
jQuery.atcosme.favorite.my = {
    conf: { xhr: {} },
    add: function(element, type, url) {
        var selector = $(element)
        var that = this;

        //popupを右寄せか左寄せかどうか決める
        var winWidth = 260;//popウィンドウの幅
        if( selector.offset().left < winWidth) {
            var tx = selector.offset().left;
        }else {
            var tx = selector.offset().left - ( winWidth - selector.width() ) + 15;
        }
        var ty = selector.offset().top + selector.height();

        var res = that.conf.xhr[type];
        res = $.atcosme.cancelRequest(that.conf.xhr[type]);
        res = $.ajax({
            url: url + "?back_url=" + encodeURIComponent(window.location.href),
            dataType: "jsonp",
            jsonp: 'callback',
            success: function(json){
                if (json.success == null) {
                    var e = Number(json.error);
                    if(e===1 || e===2 || e===3 || e===4) {
                        $.atcosme.favorite.message.show(type, e, tx, ty, json.url);
                        if (e===3) {
                            var img = $('img', selector);
                            var src = img.attr('src');
                            if (src.indexOf('clip') > -1) {
                                img.attr('src', $.atcosme.favorite.my.toClippedImg(src));
                                selector.replaceWith(img);
                            }
                        }
                    } else {
                        //システムエラー
                        $.atcosme.favorite.message.show(type, 5, tx, ty, json.url);
                    }
                } else {
                    $.atcosme.favorite.message.show(type, 0, tx, ty, json.url);
                    // 成功したら済画像に入れ替える
                    var img = $('img', selector);
                    var src = img.attr('src');
                    if (src.indexOf('clip') > -1) {
                        img.attr('src', $.atcosme.favorite.my.toClippedImg(src));
                        selector.replaceWith(img);
                    }
                }
            }
        });
        return false;
    },
    addEvent: function(selector) {
        var that = $.atcosme.favorite.message;
        selector.hover(
            function(){
            },
            function(){
                that.conf.timeoutID = window.setTimeout( that.delayHide, 300 );
            }
        );
    },
    toClippedImg: function(src) {
        return src.replace('.gif', '_off.gif').replace('.png', '_off.png');
    }
};

/* dom ready */
$(function() {
    $.each($('.addFavoriteBrand'), function(i, val) {
        $.atcosme.favorite.my.addEvent($(val), 'brand');
    });
    $.each($('.addFavoriteReview'), function(i, val) {
        $.atcosme.favorite.my.addEvent($(val), 'review');
    });
    $.each($('.addFavoriteProduct'), function(i, val) {
        $.atcosme.favorite.my.addEvent($(val), 'item');
    });
    $.each($('.addFavoriteBoard'), function(i, val) {
        $.atcosme.favorite.my.addEvent($(val), 'board');
    });
});

/**
 * ありがとうボタンへのイベント登録
 */
jQuery.atcosme.favorite.thanks = {
    id: {
        prefix: 'atcosme_thanks_give_',
        num:0
    },
    addEvent: function() {
        var selector = $('.thankGive a');
        var url = selector.attr('href');

        selector.click(function(){
            $(this).unbind('click');
            $.atcosme.favorite.thanks.id.num += 1;
            var id = $.atcosme.favorite.thanks.id.prefix + $.atcosme.favorite.thanks.id.num;
            $(this).replaceWith('<img id="'+id+'" width="70" height="21" border="0" alt="ありがとう" src="/images/common/common_btn_thanked.gif"/>');
            $.ajax({
                type: "GET",
                url: url,
                success : function(){
                    var total = Number($('#'+id).parent().parent().find('.thankTotal strong').html()) + 1;
                    $('#'+id).parent().parent().find('.thankTotal strong').html(total);
                },
                error: function(){
                }
            });
            return false;
        });
    }
};

function favorite(element, type, url) {
    return jQuery.atcosme.favorite.my.add(element, type, url);
}
