jQuery.scope = function(target,func){return function(){func.apply(target,arguments);}};

var NsPhotoNews = {
  
  detailuriPrefix:'photonews_nsInc_',
  
  indexRegExp:/^(.*\/photonews_nsInc_)(.+)(\.html)/,
  
  getId:function(){
    try {
      var id = location.pathname.match(this.indexRegExp)[2];
    }
    catch(e)
    {
      var id = ""
    }
    return id;
  },
  
  getIndex:function(){

    if( this.index ) {
      return this.index
    } else {
      var items = $('items', this.xml);
      $('item',items).each(function(i,el){
        if($('id',el).text() == NsPhotoNews.getId()){
          NsPhotoNews.index = i;
        }
      })      
    }
    return this.index || 0;
  },
  
  getURLAt:function(index){
    var id = $('id',this.xml).eq(index).text();
    var uri;
    uri = this.detailuriPrefix.concat(id,'.html');
    return uri;
  },
  
  showLoading:function(){
    var el = $('<div class="processing"></div>').
    text('loading...').
    css('position','absolute').
    css('padding','6px 10px').css('margin','0px 20px').
    css('background','#C00').css('color','#FFF').css('opacity',0.5).
    css('top','0px').css('right','0px').
    css('display','none');
    $('body').append(el);
    $('.processing').fadeIn('fast');
  },
  
  hideLoading:function(){
    $('.processing').remove();
  },
  
  getIndexInstance:function(options){
    return this.$indexInstance = this.$indexInstance || new this.Index(options);
  }
  
}

// ページクラス
NsPhotoNews.Page = function(){
  this.id;
  this.index;
  this.title;
  this.description;
  this.link;
  this.pubDate;
  this.imageUrl;
  this.thumbUrl;
};

NsPhotoNews.Page.prototype = {
  
  getTimeStamp:function(){
    return new Date(this.pubDate.replace(/-/g,'/').replace(/\+.+$/,'')).getTime();
  },
  
  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()||0).
    replace(/#{min}/,d.getMinutes()||0);
  }
  
};

// ページコレクションクラス
NsPhotoNews.PageCollection = function(){
  this.initialize.apply(this,arguments);
};

NsPhotoNews.PageCollection.prototype = {
  
  initialize:function(options){
    this.options = $.extend({
      xmluri:'ajaxlib/photonews.xml',
      ngurlXML:'/ajaxlib/keyword/ngurl.xml'
    },options);
    this.pages = [];
    this.ignores = [];
    this.minIndex = 0;
    this.maxIndex = this.pages.length-1;
    this.index_ = 0;
  },
  
  getIndex:function(){ return this.index_; },
  
  setIndex:function(value){
    if(this.index_==value) return;
    this.index_ = value;
  },
  
  isNext:function(){
    return this.getIndex() < this.maxIndex;
  },
  
  isPrev:function(){
    return this.minIndex < this.getIndex();
  },
  
  getCurrent:function(){
    return this.pages[this.getIndex()];
  },
  
  sortWithDate:function(){
    var sorted = this.pages.sort(function(a,b){ return b.getTimeStamp() - a.getTimeStamp(); });
    return sorted;
  },

  loadInit:function(callback){
    this.loadIgnoreXML(this.options.ngurlXML, $.scope(this,function(data,status){
      this.loadPhotoXML(this.options.photoXML, $.scope(this,function(data,status){
        callback(data,status);
      }))
    }));
  },
  
  loadPhotoXML:function(url,callback){
    $.ajax({
      url:url,
      dataType:'xml',
      complete:$.scope(this,handleComplete)
    });
    function handleComplete(data,status){
      if(status=='success'){
        NsPhotoNews.xml = data.responseXML;
        $('item',data.responseXML).each($.scope(this,function(i,e){
          var page = new NsPhotoNews.Page();
          page.id = $('id',e).text();
          page.index = i;
          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') || page.imageUrl;
          if( !this.isIgnore(page.link) ){
            this.pages.push(page);
          }
        }));
      }
      this.maxIndex = this.pages.length - 1;
      callback(data,status);
      NsPhotoNews.collection = this;
    }
  },
  
  loadIgnoreXML:function(url,callback){
    $.ajax({
      url:url,
      dataType:'xml',
      complete:$.scope(this,handleComplete)
    });
    function handleComplete(data,status){
      if( status == 'success' ){
        var xml = data.responseXML;
        this.ignoreXML = xml;
      }
      callback(data,status);
    }
  },

  isIgnore:function(link){
    var matched = false;
    $('ngurl[regexp="true"]',this.ignoreXML).each(function(i,e){
      if( link.match(new RegExp($(e).text())) ) matched = true;
    });
    $('ngurl[regexp!="true"]',this.ignoreXML).each(function(i,e){
      if(link == $(e).text()){
        matched = true;
      }
    });
    return matched;
  }
  
};

NsPhotoNews.Index = function(){
  this.initialize.apply(this,arguments);
};

NsPhotoNews.Detail = function(){
  this.initialize.apply(this,arguments);
};

NsPhotoNews.Top = function(){
  this.initialize.apply(this,arguments);
};

NsPhotoNews.Index.prototype = {
  
  initialize:function(options){
    
    this.options = $.extend({
      xmluri:'ajaxlib/photonews.xml',
      ngurlXML:'/ajaxlib/keyword/ngurl.xml',
      rows: 4,
      cols: 5
    },options);

    this.page = 0;
    this.maxPage = 0;
    this.thumbLimit = this.options.rows * this.options.cols;
    this.collection = new NsPhotoNews.PageCollection({
      photoXML:this.options.xmluri,
      ngurlXML:this.options.ngurlXML
    });
    NsPhotoNews.showLoading();
    this.collection.loadInit($.scope( this, handleLoadComplete));
    function handleLoadComplete(data,status){
      this.maxPage = Math.ceil(this.collection.pages.length / this.thumbLimit )-1;
      //this.maxPage = Math.floor(this.collection.pages.length / this.thumbLimit );
      this.collection.setIndex(NsPhotoNews.getIndex());
      this.display();
      NsPhotoNews.hideLoading();
    }
  },
  
  getPage:function(){
    return this.page;
  },
  
  setPage:function(page){
    if(this.page == page) return;
    page = ( this.maxPage < page  ) ? this.maxPage : page;
    this.page = page;
  },
  
  isPrevPage:function(){
    return 0 < this.page;
  },
  
  isNextPage:function(){
    return this.page < this.maxPage;
  },
  
  getURLAt:function(index){
    var id = $('id',NsPhotoNews.xml).eq(index).text();
    var uri = NsPhotoNews.detailuriPrefix;
    return uri.concat(id,'.html');
  },
  
  getThumbs:function(){
    var index = this.collection.getIndex();
    var size = this.collection.pages.length;
    var limit = ( this.thumbLimit < size  ) ? this.thumbLimit : size;
    var begin = limit * this.page;
    var end = limit * ( this.page + 1 );
    var rangePages = this.collection.sortWithDate().slice(begin,end);
    return rangePages;p
  },
  
  display:function(page){
    if(0<=page) this.setPage(page);
    var index = this.collection.getIndex();
    var size = this.collection.pages.length;
    var rows = this.options.rows;
    var cols = this.options.cols;
    var limit = ( this.thumbLimit < size  ) ? this.thumbLimit : size;
    var begin = limit * this.page;
    var end = limit * ( this.page + 1 );
    var rangeThumbs = this.getThumbs();
    $('p.photoListNum').text( ''.concat(size,' 枚中 ', begin+1 ,' - ', end ,' 枚目') );
    var thumbWrapTemplate = $('#thumbWrapTemplate');
    var thumbInnerTemplate = $('#thumbInnerTemplate');
    $('.thumWrap[id!="thumbWrapTemplate"]').remove();
    for( var i=0; i<rows; i++ ){
      if( rangeThumbs.length <= 0 ) break;
      var wrap = thumbWrapTemplate.clone().css('display','').removeAttr('id');
      $('div.pageMove').before(wrap);
      for( var j=0; j<cols; j++ ){
        var inner = thumbInnerTemplate.clone().css('display','').removeAttr('id');
        if(rangeThumbs.length <= 0) {
        } else {
          var thumb = rangeThumbs.shift();
          var link = this.getURLAt(thumb.index);
          var res = inner.appendTo(wrap).
	  find('a').attr('href',link).attr('title','拡大写真を見る').
	  find('img').attr('src','/img/photonews_nophoto_small.gif').
	  attr('alt',thumb.title).attr('oncontextmenu','return false');
          inner.find('span.thumbtitle').text(thumb.title);
          inner.find('span.thumbdate').text('['+thumb.getDateFormated()+']');
	  var img = new Image();
	  $(img).bind('load', replaceImage(res) );
	  img.src = thumb.thumbUrl;
        }
      }
    }

    //thumbWrapTemplate.remove();
    // pagenate
    this.createPagenate();
    
    for( var i=0; i<rangeThumbs.length; i++ ){
      var y = Math.floor(i/rows);
      var x = i % cols;
    }

    function replaceImage(target){
      return function(){
	  target.attr('src', this.src).attr('width',this.width).attr('height',this.height);
      }
    }

  },
  
  createPagenate:function(){
    var target = $('.pageMove').empty();
    var ol = $('<ol></ol>');
    for(var i=0; i<=this.maxPage; i++){
      var link = $('<li>'+(i+1)+'</li>');
      if( this.page != i  ){
        link.wrapInner('<a href="javascript:void(0);"></a>');
        link.click($.scope(this,closure(i)));
      }
      var prev = $('<li>前のページ</li>');
      if(this.isPrevPage()){
        prev.wrapInner('<a href="javascript:void(0);"></a>');
        prev.click($.scope(this,closure(this.page-1)));
      }
      var next = $('<li>次のページ</li>');
      if(this.isNextPage()){
        next.wrapInner('<a href="javascript:void(0);"></a>');
        next.click($.scope(this,closure(this.page+1)));
      }
      ol.append(link);
    }
    target.append(prev);
    target.append(ol);
    target.append(next);

    function closure(index){
      return function(){
        this.display(index);
      }
    }

  }
};

// 写真ニュースの詳細ページクラス
NsPhotoNews.Detail.prototype = {
  
  initialize:function(options){
    this.thumbLimit = 5;
    this.options = $.extend({
      xmluri:'ajaxlib/photonews.xml',
      ngurlXML:'/ajaxlib/keyword/ngurl.xml'
    },options);
    this.collection = new NsPhotoNews.PageCollection({
      photoXML:this.options.xmluri,
      ngurlXML:this.options.ngurlXML
    });
    NsPhotoNews.showLoading();
    this.collection.loadInit($.scope( this, handleLoadComplete));
    function handleLoadComplete(data,status){
      this.collection.setIndex(NsPhotoNews.getIndex());

      if( NsPhotoNews.getId() == this.collection.getCurrent().id ){
        this.display();
        NsPhotoNews.hideLoading();
      } else {
        var url = location.href.replace(/photonews_nsInc_/,'');
	this.getNsPicture(url);
      }

    }
  },

  getNsPicture:function(url){
    // 暫定的に/ajaxlib/root/へ転送 080513 haga
    url = url.replace(/^https?:\/\/.+?\//,'/ajaxlib/root/');
    
    $.ajax({
      url:url,
      dataType:'html',
      complete:$.scope(this,handleGetNsPicture)
    });
    function handleGetNsPicture(data,status){
      data = data.responseText;
      if(status=='success'){
        var imageUrl,title;
        try {
          imageUrl = data.match(/nsPicture.+?content="(.*?.jpg)"/)[1].replace(/ns.jpg/,'ns-big.jpg');
          title = data.match(/<title>(.*?)<\/title>/i)[1].replace(/ : nikkansports.com/,'');
        } catch (e){}
        if(!!imageUrl&&!!title){
          this.display({
            imageUrl:imageUrl,
            title:title,
            link:url
          });
        } else {
          this.display();
        }
      } else {
        this.display();
      }
      NsPhotoNews.hideLoading();
    }
  },
  
  getThumbs:function(){
    var index = this.collection.getIndex();
    var size = this.collection.pages.length;
    var limit = ( this.thumbLimit < size  ) ? this.thumbLimit : size;
    var begin = index - Math.floor(limit/2);
    begin = begin < 0 ? 0 :begin;
    begin = ( size < begin + limit ) ? size - limit : begin;
    var end = begin + limit;
    var rangePages = this.collection.pages.slice( begin, end );
    return rangePages;
  },
  
  display:function( _page  ){
    var page = this.collection.getCurrent();
    var index = this.collection.getIndex();
    var rangeThumbs = this.getThumbs();

    if(_page){
      index = -1;
      page.imageUrl = _page.imageUrl;
      page.title = _page.title;
      page.link = _page.link;
    }

    if( !!page  ){

	var bigimage = $('.npImage').
	    find('img').
	    attr('src','/img/photonews_nophoto_small.gif').
	    attr('alt',page.title).
	    attr('oncontextmenu','return false');
      var img = new Image();
      $(img).bind('load',replaceImage(bigimage));
      img.src = page.imageUrl;

      // 見出し
      document.title = page.title;
      $('#bigPhoto h1').text(page.title);
      
      // next
      if( this.collection.isNext() ){
        $('.photoMove li.next a').attr('href', NsPhotoNews.getURLAt(index+1) );
        $('.npImage a').attr('href', NsPhotoNews.getURLAt(index+1) ).
	    attr('title','次の写真を見る');
      }
      
      // prev
      if( this.collection.isPrev() ){
        $('.photoMove li.prev a').attr('href', NsPhotoNews.getURLAt(index-1) );
      }

      // link
      $('#bigPhoto p.readEntry a').
	  attr('href', page.link);

      //$('#bigPhoto .newsPhotoDescription').text( page.description);
      $('.npCount').text(this.collection.pages.length);

      var tmpl = $('#thumbTemplate');

      for( var i=0; i<rangeThumbs.length; i++ ){
        var link = NsPhotoNews.getURLAt(rangeThumbs[i].index);
        var current = index == rangeThumbs[i].index;
        var el = tmpl.clone().css('display','').removeAttr('id');
        var res = el.appendTo('.thumWrap').
	find('a').attr('href',link).attr('title','拡大写真を見る').
        find('img').attr('src','/img/photonews_nophoto_small.gif').attr('alt',rangeThumbs[i].title);
        if(current) el.find('p').addClass('current');
        var img = new Image();
        $(img).bind('load', replaceImage(res) );
        img.src = rangeThumbs[i].thumbUrl;
      }
      
    } else {
      
    }
    function replaceImage(target){
      return function(){
        target.attr('src', this.src).attr('width',this.width).attr('height',this.height);
      }
    }
  }

};

NsPhotoNews.Top.prototype = {

  initialize:function(options){
    this.options = $.extend({
      xmluri:'ajaxlib/photonews.xml',
      ngurlXML:'/ajaxlib/keyword/ngurl.xml'
    },options);
    this.collection = new NsPhotoNews.PageCollection({
      photoXML:this.options.xmluri,
      ngurlXML:this.options.ngurlXML
    });
    NsPhotoNews.showLoading();
    this.collection.loadInit($.scope( this, handleLoadComplete));
    function handleLoadComplete(data,status){
      this.display();
      NsPhotoNews.hideLoading();
    }
  },
  
  display:function(){
    var sorted = this.collection.sortWithDate();
    $('#newPhoto p').each(function(i,e){
      if(sorted.length<=i) $(e).remove();
      try {
        var page = sorted[i];
        $('a',e).attr('href',page.link).attr('title','拡大写真を見る');
        var thumb = $('img',e).
          attr('alt',page.title).
	    attr('oncontextmenu','return false').
          attr('src', '/img/photonews_nophoto_small.gif').
          removeAttr('width').removeAttr('height');
	      var img = new Image();
	      $(img).bind('load', replaceImage(thumb) );
	      img.src = page.thumbUrl;
      } catch(e){
      }
    });
    function replaceImage(target){
	return function(){
	    target.attr('src', this.src).attr('width',this.width).attr('height',this.height);
	}
    }
  }
};