﻿/**
연합뉴스 속보 티커
*/
var SokboTicker = {

    /* 속보 JSON 목록을 저장 */
    List: undefined,
    /* 속보 JSON URL */
    ListURL: "http://www.yonhapnews.co.kr/data/sokbo_ticker.js",
    //ListURL: "http://www.yonhapnews.co.kr/bwjeon/ticker/sokbo_ticker_test.js",
    /* setTimeout 을 담는 변수 */
    Timeout: undefined,
    /* 현재 기사의 인덱스 */
    Index: 0,
    /* 속보 JSON 업데이트 주기 (초) */
    UpdateSeconds: 60,
    /* Slide 속도 (ms) */
    SlideTime: 1000,
    /* 기사 교체 간격 = JSON 업데이트 주기를 기사 건수로 나눈 시간 -> 한번 다 돌고 JSON 갱신함 */
    TickSeconds: function () {
        var n = SokboTicker.UpdateSeconds * 1000 / SokboTicker.List.length;
        return n;
    },
    /* 일시 중지 플레그 */
    Pause: false,

    /* 중지 */
    Stop: function () {
        SokboTicker.Pause = true;
        clearTimeout(SokboTicker.Timeout);
        $('.top_brklst').children().stop();
        SokboTicker.SetArticle();
    },
    /* 시작 */
    Start: function () {
        SokboTicker.Pause = false;
        SokboTicker.SetArticle();

    },
    /* 다음 기사 */
    Next: function () {
        var n = SokboTicker.Index + 1;
        if (n >= SokboTicker.List.length)
            n = 0;
        SokboTicker.Index = n;
        clearTimeout(SokboTicker.Timeout);
        $('.top_brklst').children().stop();
        SokboTicker.SetArticle();

    },
    /* 이전 기사 */
    Prev: function () {
        var n = SokboTicker.Index - 1;
        if (n < 0)
            n = SokboTicker.List.length - 1;
        SokboTicker.Index = n;
        clearTimeout(SokboTicker.Timeout);
        $('.top_brklst').children().stop();
        SokboTicker.SetArticle();
    },
    /* 이벤트 바인딩 */
    Bind: function () {

        $('.top_brkctrl button.stp').addClass('blind');
        // 버튼
        $('.top_brkctrl button.stp').click(function () {
            $('.top_brkctrl button.stp').addClass('blind');
            $('.top_brkctrl button.ply').removeClass('blind');
            SokboTicker.Start();
        });
        $('.top_brkctrl button.ply').click(function () {
            $('.top_brkctrl button.ply').addClass('blind');
            $('.top_brkctrl button.stp').removeClass('blind');
            SokboTicker.Stop();
        });


        // 이전기사
        $('.top_brkctrl .pre').unbind();
        $('.top_brkctrl .pre').bind('click', SokboTicker.Prev);

        // 다음기사.
        $('.top_brkctrl .nxt').unbind();
        $('.top_brkctrl .nxt').bind('click', SokboTicker.Next);

    },
    /* JSON 로딩 */
    LoadJSON: function () {
        $.ajax({
            type: "GET",
            url: SokboTicker.ListURL + '?' + new Date().getTime(),
            dataType: "json",
            //dataType: "text", //text 형식 사용시
            data: "",
            success: SokboTicker.LoadSuccess
          /*
            error: function () {
                alert("Ticker LoadJSON Error");
            }
           */
        });
    },
    /* JSON 로딩후 콜백 함수 */
    //LoadSuccess: function (text) {
    LoadSuccess: function (json) {
        //var json = eval('(' + text + ')'); //dataType:"json" 사용시 삭제
        SokboTicker.List = json['DATA'];
        var caption;
        for (var i = 0; i < SokboTicker.List.length; i++) {
            caption = SokboTicker.List[i]["TEXT_BODY"];
            caption = caption.replace(/^\s*|\s*$/g, '').replace(/\r?\n/g, ' ');
            caption = caption.replace(/(\([^\)]+= *연합[\S]+ *\))(([^=\n\r]+)= *)?/, '');
            SokboTicker.List[i]["TEXT_BODY"] = caption;
        }
        SokboTicker.SetArticle();
    },
    /* 기사를 표시하고 지정 시간후 슬라이딩 */
    SetArticle: function () {
        var n1 = SokboTicker.Index;
        var n2 = n1 + 1;
        var list = SokboTicker.List;

        if (n2 >= list.length)
            n2 = 0;
        var h = '';
        h += SokboTicker.MakeHTML(list, n1);
        h += SokboTicker.MakeHTML(list, n2);
        h += '';
        $('.top_brklstcvr').css('top', '0px');
        $('.top_brklstcvr').html(h);

        // 이미 실행되고 있는 놈은 중지.
        clearTimeout(SokboTicker.Timeout);
        SokboTicker.Timeout = setTimeout(SokboTicker.Slide, SokboTicker.TickSeconds());

    },
    /* 기사 슬라이딩 */
    Slide: function () {
        if (!SokboTicker.Pause) {
            var h = $('.top_brklstcvr').height() / 2;
            $('.topar_brk').css('overflow', 'hidden'); //.css('display', 'block');
            $('.topar_brk').children().css('position', 'relative');
            $('.top_brklstcvr').animate({ top: -h + 'px' }, SokboTicker.SlideTime,
                function () {
                    var n = $('.top_brklstcvr').children().eq(1).clone(true);
                    $('.top_brklstcvr').children().eq(0).html(n.html());
                    $('.top_brklstcvr').css('top', '0px');
                    SokboTicker.Index++;

                    if (SokboTicker.Index >= SokboTicker.List.length) {
                        SokboTicker.Index = 0;
                        if (!SokboTicker.Pause)
                            SokboTicker.LoadJSON();
                    }
                    else
                        SokboTicker.SetArticle();
                }
                );
        }
        else {
            setTimeout(function () {
                SokboTicker.SetArticle();
            }, SokboTicker.SlideTime);
        }
    },

    MakeHTML: function (list, offset) {
        var title = list[offset]['TITLE'];
        var caption = list[offset]['TEXT_BODY'];
        var link = list[offset]['CONTENTS_LINK'];
        var urgency = list[offset]['URGENCY'];
        var hpurgency = list[offset]['HPURGENCY'];
        var h = '<dl class="top_brklst">';
        if (urgency == '0' || urgency == '1') {
            h += '<dt><a href="' + link + '" class = "sp_br">' + title + '</a></dt>';
        } else if (hpurgency == '0') {
            h += '<dt><a href="' + link + '" class = "sp">' + title + '</a></dt>';
        } else {
            h += '<dt><a href="' + link + '" >' + title + '</a></dt>';
        }
        h += '<dd>' + caption + '</dd>';
        h += '</dl>\n';
        return h;
    }
};

$(document.body).ready(function () {
    SokboTicker.Bind();
    SokboTicker.LoadJSON();
});

