/**
 * 달려라 골드마블
 * @type {{eventId: null, init: goldMarble.init, setApplyFunc: goldMarble.setApplyFunc, apply: goldMarble.apply, isProcess: boolean, getNowNumOftime: goldMarble.getNowNumOftime, numTime: null}}
 */
var goldMarble = {
    eventId: null
    , numTime: null
    , isProcess: false
    , init: function(keymap){
        goldMarble.eventId = keymap.eventId;

        // 설정 정보 가져오기
        goldMarble.getNowNumOftime();
    }
    , setApplyFunc: function(){
        $(".btnGoldMarble").click(function(){
            if (goldMarble.isProcess == false) {
                var numTime = $(this).data("numTime");
                goldMarble.numTime = numTime;
                goldMarble.isProcess = true;
                goldMarble.apply();
            }
            return false;
        });
    }
    , getNowNumOftime: function(){
        var data = {
            "eventId": goldMarble.eventId
        };
        $.post("/api/event/goldMarble/stampCnt", data, function(result){
            var stampCnt = result.stampCnt;
            var winList = result.winList;
            var remainCntList = result.remainCntList;

            if (stampCnt > 0) {
                $("div.stamp_num > strong").html(stampCnt);
            } else {
                $("div.stamp_num > strong").html("0");
            }

            var html = '<li class="start"><em>start</em></li>';
            for (var i=1; i<=30; i++) {
                var no = i;
                if (no < 10) {
                    no = "0"+ i;
                }

                // 경품 잔여 수량 체크
                var soldOutYn = "N";
                var prizeBtnYn = "N";
                $(remainCntList).each(function(index, item){
                    if (i == item.PRIZE_TIME) {
                        prizeBtnYn = "Y";
                        if (item.REMAIN_CNT < 1) {
                            soldOutYn = "Y";
                            return;
                        }
                    }
                });

                // 스탬프 적용 체크
                if (i <= stampCnt) {
                    // 당첨 여부 체크
                    var prizeName = "";
                    var winnerYn = "N";
                    $(winList).each(function(index2, item2){
                        if (i == item2.PRIZE_TIME) {
                            prizeName = item2.PRIZE_NAME;
                            winnerYn = "Y"
                            return;
                        }
                    });

                    if (winnerYn == "Y") {
                        html += '<li class="active complete"><em>'+ no +'</em></li>';
                    } else {
                        if (soldOutYn == "Y") {
                            html += '<li class="entry soldout"><em>'+ no +'</em></li>';
                        } else {
                            if (prizeBtnYn == "Y") {
                                html += '<li class="active entry"><em>'+ no +'</em><a href="javascript:void(0)" class="btnGoldMarble" data-num-time="'+ i +'">응모하기</a></li>';
                            } else {
                                html += '<li class="active"><em>'+ no +'</em></li>';
                            }
                        }
                    }
                } else {
                    if (prizeBtnYn == "Y") {
                        html += '<li class="entry"><em>'+ no +'</em><a href="javascript:void(0)" class="btnGoldMarble" data-num-time="'+ i +'">응모하기</a></li>';
                    } else {
                        // 스탬프 안찍힘(횟수미달)
                        html += '<li><em>' + no + '</em></li>';
                    }
                }

            }
            html += '<li class="end"><em>end</em></li>';
            $(".marble-list").append(html);
            goldMarble.setApplyFunc();
        });
    }
    , apply: function(){
        var numTime = goldMarble.numTime;
        var eventId = goldMarble.eventId;
        var data = {
            "numTime": numTime
        };

        $.ajax({
            url: '/api/event/goldMarble/'+ eventId,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function (data, status, xhr) {
                switch(data.result){
                    case "login":
                        goLogin();
                        break;
                    case "no-adult":
                        alert("19세 이상만 참여 가능합니다.");
                        break;
                    case "already-regist":
                        alert("이미 이벤트에 응모하셨습니다.\n다음 칸으로 전진해 주세요!");
                        break;
                    case "no-apply-cnt":
                        alert("참여 횟수가 충분하지 않습니다.\n3,000원 이상 구매 후 원바코드로 포인트 적립하고\n이벤트에 참여해 주세요!");
                        break;
                    case "no-prev-regist":
                        alert("이전 회차 부터 참여해 주세요.");
                        break;
                    case "sold-out":
                        alert("선착순 경품 지급이\n완료되었습니다ㅜㅜ\n다음칸으로 전진해 주세요!");
                        break;
                    case "ok":
                    case "ok-real":
                        alert("["+ data.prizeName +"] 당첨되셨습니다!\n축하 드립니다!");
                        // 응모 완료 처리
                        $(".btnGoldMarble").each(function(){
                            var no = $(this).data("numTime");
                            if (no == goldMarble.numTime) {
                                $(this).parent().addClass("complete");
                                return;
                            }
                        });
                        break;
                    default:
                        alert("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요...");
                        break;
                }
                goldMarble.isProcess = false;
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.");
                goldMarble.isProcess = false;
                console.log(xhr);
            },
            fail: function(e, data){
                alert("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요..");
                console.log(e.isDefaultPrevented());
                goldMarble.isProcess = false;
            }
        });
    }
};
