/* headline_reader requires JKL ParseXML */

var HL = {};

/* セッティング */

// 巡回対象のフィード
HL.feeds = "news/news.xml";

// 表示エントリ数
HL.num = 15;

// dc:subject
HL.filter = 'Topics';

// 表示秒数(ミリセカンド)
HL.showtime = 3000;

// スクロールのスピード(数値が少ないほど早くなる)
HL.speed = 100;

// 書き換えを行なうID属性
HL.target = [ 'headdate', 'headline' ];

// new マークをつける期間
HL.newTime = 3600 * 24 * 7; // 7日

// 表示内容(他のタグを増やすと動かなくなるかも)
HL.template = '<a href="#{link}" target="#{target}" class="">#{title}</a>';
HL.template_nolink = '<span>#{title}</span>';
HL.template_new = '';

/* --- 設定完了 --- */

/* 拡張 */
Function.prototype.extend = function(newClass) {
   var proto = this.prototype;
   for(var property in newClass)
      proto[property] = newClass[property];
}

Function.extend({
      bind: function(base) {
         var self = this;
         return function() {
            self.apply(base, arguments);
         }
      }
   });

/* クラス関数 */
HL.Class = {
   create: function(baseClass) {
      var newClass = function() {
         this.initialize.apply(this, arguments);
      }
      newClass.prototype.initialize = function() {}

      newClass.inherit = function(base) {
         this.extend(base.prototype);
      }

      if(baseClass)
         newClass.extend(baseClass.prototype);

      return newClass;
   }
}

/* Feed リーダー用クラス */
HL.Feed = {};

HL.Feed.Loader = HL.Class.create();
HL.Feed.Loader.extend({
      initialize: function(options) {
         // キャッシュをさせたくない場合
         var feed = options.feeds + '?' + (new Date).getTime();

         new HL.Feed.Reader({
               feed: feed,
               template: HL.template,
               template_nolink: HL.template_nolink,
               template_new: HL.template_new,
               parent: this
            });
      },

      callback: function(lists) {
         this.call = {};
         this.call.lists = lists;
         this.call.i = -1;

         HL.addEvent(document.getElementById("headbtn_back"), 'click', this.loadBack.bind(this));
         HL.addEvent(document.getElementById("headbtn_next"), 'click', this.loadNext.bind(this));

         var self = this;
         self.loadNext();
         (function() {
               var call = self.call;
               if(call.last) {
                  if(call.last[1].finish == 'finish') {
                     call.last = false;
                     self.loadNext();
                  }
               }
               setTimeout(arguments.callee, 300);
            })();
      },

      loadBack: function() {
         var call = this.call;
         call.i--;
         if(call.i < 0) call.i = call.lists.length-1;
         this._load(call.i);
      },

      loadNext: function() {
         var call = this.call;
         call.i++;
         if(call.i >= call.lists.length) call.i = 0;
         this._load(call.i);
      },

      _load: function(i) {
         var call = this.call;
         if(call.last) {
            call.last[0].finish = 'finish';
            call.last[1].finish = 'finish';
         }
         var html = call.lists[i];
         var f0 = new HL.Effect.Fade({ target: HL.target[0], html: html[0] });
         var f1 = new HL.Effect.Scroll({ target: HL.target[1], html: html[1] });
         call.last = [ f0, f1 ];
         call.i = i;
         document.getElementById('headbtn_num').src = "/common/images/top/num_ticker"+(i+1)+".gif";
         document.getElementById('headbtn_num').alt = i+1;
      }
   });

HL.Feed.Reader = HL.Class.create();
HL.Feed.Reader.extend({
      initialize: function(options) {
         this.o = options;
         var http = new JKL.ParseXML(options.feed);
         var self = this;
         http.async(function(data) { self.done(data); });
         http.parse();
      },

      done: function(data) {
         var lists = new Array();
         var items = data['rdf:RDF'].item;
         var num = 0;

         // for(var i = 0; i < HL.num; i++) {
         for(var i = 0; i < items.length; i++) {
            var item = items[i];
            if(item['dc:subject'] != HL.filter) continue;
            if(++num && HL.num < num) break;
            var html = item.link ? this.o.template : this.o.template_nolink;
            var title = item.title;
            var date = item['dc:date'].replace(/T.*/, '').replace(/\-/g, '.');
            var time = (new Date(item['dc:date'].replace(/T/, ' ').replace(/\-/g, '/').replace(/\+09:00/, ''))).getTime() + (1000 * HL.newTime);
            if(time > (new Date()).getTime()) html = this.o.template_new + html;
            html = html.replace(/#{title}/g, title).replace(/#{link}/g, item.link)
                        .replace(/#{target}/g, item.target||'');
            lists.push([ date, html]);
         }

         this.o.parent.callback(lists);
      }
});

/* テキストエフェクト用クラス */
HL.Effect = {};

HL.Effect.Base = HL.Class.create();
HL.Effect.Base.extend({
      initialize: function(options) {
         this.elm  = document.getElementById(options.target);
         this.html = options.html;

         this.finish = false;
         this.count = 10;
         this.timeout = 100;
         this.before_start();
         this.elm.innerHTML = this.html;

         var self = this;
         var count = this.count;
         var timeout = this.timeout;
         (function() {
               if(self.finish) return;
               self.step(count);
               if(--count > 0) setTimeout(arguments.callee, timeout);
               else self.after_end();
            })();
      },

      set_opacity: function(elm, value) {
         if(value == 1) {
            if(/MSIE/.test(navigator.userAgent) && !window.opera)
               elm.style.filter = elm.style.filter.replace(/alpha\([^\)]*\)/gi,'');
         } else {
            if(value < 0.1) value = 0;
            if(/MSIE/.test(navigator.userAgent) && !window.opera)
               elm.style.filter = elm.style.filter.replace(/alpha\([^\)]*\)/gi,'') +
                  'alpha(opacity='+value*100+')';
         }
         elm.style.opacity = value;
      },

      setup: function() {},
      before_start: function() {},
      step: function() {},
      after_end: function() {}
});

/* フェードイン */
HL.Effect.Fade = HL.Class.create(HL.Effect.Base);
HL.Effect.Fade.extend({
      before_start: function() {
         this.elm.style.zoom = 1; // for IE
         this.set_opacity(this.elm, 0);
      },

      step: function(count) {
         this.set_opacity(this.elm, (10 - count) / 10);
      },

      after_end: function() {
         this.set_opacity(this.elm, 1);
      }
});

/* フェードイン+スクロールアウト */
HL.Effect.Scroll = HL.Class.create(HL.Effect.Fade);
HL.Effect.Scroll.extend({
      scroll: function() {
         if(!this.elm.firstChild)
            return;
         var child = this.elm.firstChild
         if(child.tagName.toLowerCase() == 'img') {
            this.elm.removeChild(child);
            child = this.elm.firstChild
         }
         var self = this;
         (function() {
               if(self.finish) return;
               child.innerHTML = child.innerHTML.replace(/^./, '');
               if(child.innerHTML.length) setTimeout(arguments.callee, HL.speed);
               else self.finish = 'finish';
            })();
      },

      after_end: function() {
         this.set_opacity(this.elm, 1);
         var self = this;
         setTimeout(function() { self.scroll(); }, HL.showtime);
      }
});

/* ユーティリティ関数 */
HL.addEvent = (window.addEventListener) ?
(function(elm, type, event) {
      elm.addEventListener(type, event, false);
   }) : (window.attachEvent) ?
(function(elm, type, event) {
      elm.attachEvent('on'+type, event);
   }) :
(function(elm, type, event) {
      elm['on'+type] = event;
   }) ;

/* 開始処理 */
HL.addEvent(window, 'load', function() {
      new HL.Feed.Loader({
            feeds: HL.feeds
         });
   });


