/**
 * Usage: NsRelation.init();
 * Options:
 *   target
 *   keywordXmlDir
 *   ngurlXml
 *   limit
 */
jQuery.scope = function(target,func){
  return function(){
    func.apply(target,arguments);
  };
};
var NsRelation = {
  init:function(options){
    (options.target||$('ul.newsList')).each(function(i,e){
      var gen = new NsRelation.Generator(e,options);
      gen.execute();
    });
  }
};

NsRelation.Page = function(){
  this.id;
  this.title;
  this.description;
  this.link;
  this.pubDate;
  this.imageUrl;
  this.thumbUrl;
};

NsRelation.Page.prototype = {
  getTimeStamp:function(){
    return new Date(this.pubDate.replace(/-/g,'/').replace(/[^\s]\+/,' +')).getTime()||0;
  },
  isFlash:function(){
    return this.link.split('/').slice(-1)[0].slice(0,1) == 'f';
  },
  isPaper:function(){
    return this.link.split('/').slice(-1)[0].slice(0,1) == 'p';
  },
  isImage:function(){
    return !!this.imageUrl;
  },
  getDateFormated:function(){
    var d = new Date();
    d.setTime(this.getTimeStamp());
    var text = '#{day}日#{hour}:#{min}';
    return text.replace(/#{day}/,d.getDate()).
    replace(/#{hour}/,d.getHours()).
    replace(/#{min}/,d.getMinutes());
  }
};

NsRelation.Generator = function(target,options){
  this.target = target;
  this.options = options;
  this.options;
  this.keywords = [];
  this.ignores;
  this.relations = [];
  this.initialize();
  
};
NsRelation.Generator.prototype = {
  
  initialize:function(){
    this.options = jQuery.extend({
      keywordXmlDir: '/ajaxlib/keyword/',
      ngurlXml: '/ajaxlib/keyword/ngurl.xml',
      limit: 3
    },this.options);
    this.keywords = this.getKeywords();
  },
  
  execute:function(){
    if( this.keywords.length <= 0 ) return;
    this.loadIgnores();
  },
  
  getKeywords:function(){
    var t = $("meta[name='nsKeywords']").attr('content');
    return (t?t:'').split(',') || [];
  },
  
  loadIgnores:function(){
    $.ajax({
      type: 'GET',
      dataType:'xml',
      url: this.options.ngurlXml,
      complete: $.scope(this,handleComplete)
    });
    function handleComplete(data,status){
      if( status == 'success' ){
        var xml = data.responseXML;
        this.ignores = xml;
        this.loadKeywordXmls(this.keywords);
      }
    }
  },
  
  loadKeywordXmls:function(keywords){
    this.relations = [];
    this.keywordLoadedLength = 0;
    for(var i=0; i<keywords.length; i++){
      //var keywordXml = this.options.keywordXmlDir.concat( encodeURI(keywords[i]).replace(/%/g,'x'),'.xml');
      var keywordXml = this.options.keywordXmlDir.concat( encodeURI(keywords[i]),'.xml');
      $.ajax({
        index: i,
        type: 'GET',
        timeout: 1000,
        dataType:'xml',
        url: keywordXml,
        complete: $.scope(this,handleComplete)
      });
    }
    function handleComplete(data,status){
      this.keywordLoadedLength++;
      if(status == 'success'){
        var xml = data.responseXML;
        $('item',xml).each( $.scope(this,function(i,e){
          var page = new NsRelation.Page();
          page.title = $('title',e).text();
          page.description = $('description',e).text();
          page.link = $('link',e).text();
          page.pubDate = $('pubDate',e).text();
          page.imageUrl = $('image',e).attr('url');
          page.thumbUrl = $('image',e).attr('thumbUrl');
          this.relations.push(page);
        }));
      }
      if( this.keywords.length == this.keywordLoadedLength ){
        //console.log('keywords loaded.');
        this.output();
      }
    }
  },
  
  output:function(){
    $(this.target).empty();
    var filterd = this.filterPages();
    $.each(filterd,$.scope(this,function(i,e){
      var html = '<li class="#{type}"><a href="#{e.link}">#{e.title}</a>#{icon}<span>&nbsp;[#{formatedDate}]</span></li>';
      var icon = '<img width="16" height="12" alt="写真つき記事" src="/img/icon-camera.gif"/>';
      var type = e.isFlash() ? 'iconFlash' : e.isPaper() ? 'iconPaper' : 'iconOther';
      var element = html.replace(/#{type}/,type).
      replace(/#{e.link}/,e.link).
      replace(/#{e.title}/,e.title).
      replace(/#{icon}/,e.isImage()?icon:'').
      replace(/#{formatedDate}/g,e.getDateFormated());
      $(this.target).append(element);
    }))
  },

  filterPages:function(){
    var pages = this.relations.sort(function(a,b){return b.getTimeStamp() - a.getTimeStamp()});
    var pageFilterd = [];
	var linkmap = {};
    while( pageFilterd.length < this.options.limit ){
      var page = pages.shift();
      if(!page) break;
	  if(page.link==location.href||linkmap[page.link]) continue;
      var matched = false;
      $('ngurl[regexp="true"]',this.ignores).each(function(i,e){
        if( page.link.match(new RegExp($(e).text())) ) matched = true;
      });
      $('ngurl[regexp!="true"]',this.ignores).each(function(i,e){
        if(page.link == $(e).text()){
          matched = true;
        }
      });
      if(!matched) {
        pageFilterd.push(page);
		linkmap[page.link]=1;
	  }
    }
    return pageFilterd;
    return this.relations.sort(function(a,b){ return b.getTimeStamp() - a.getTimeStamp(); }).slice(0,this.options.limit);
  }
};
