/**
 * 同じクラスの要素を一定間隔で切り替える
 *
 * target_elementで示される要素のスタイルには "position: relative" が指定されていること。
 * element_selectorで示される要素のスタイルには "display: none;" が指定されていること。
 * .switch_panel 以下の element_selectorで示される要素のスタイルには "position: absolute; top:0; left:0;" が指定されていること。
 *
 * @param target_element 切り替え対象の親の要素を指すセレクタ
 * @param refresh_time 要素を切り替える間隔。単位msec。 デフォルトで 5000。
 * @param element_selector 対象とする要素のセレクタ。デフォルトで .image_switch
 */
var ImageSwitch = function(target_element, refresh_time, element_selector) {
  if (typeof element_selector == 'undefined') {
    this.element_selector = '.image_switch';
  } else {
    this.element_selector = element_selector;
  }
  this.refresh_time = 5000;
  if (typeof refresh_time != 'undefined') {
    this.refresh_time = refresh_time;
  }
  // 画像のフェードアウト/インの時間間隔
  this.dulation = 400;
  this.current_element = 0;
  this.active = true;
  this.elements = $(target_element+' '+this.element_selector);
  if (this.elements.length > 0) {
    this.init();
  }
};
ImageSwitch.prototype.init = function() {
  // 一番最初の要素の直前に表示領域を挿入する
  this.panel = $('<div class="switch_panel" style="display:block;"></div>');
  $(this.elements[0]).before(this.panel);
  for (var i=0; i < this.elements.length; i++) {
    this.panel.append(this.elements[i]);
  }
  // 最初の要素に refresh 属性が定義されていたらその値を refresh_time に利用する。
  var first = this.panel.find(this.element_selector+':nth-child(1)');
  var refresh = first.attr('refresh');
  if (refresh) {
    this.refresh_time = refresh;
  }
  // 最初の画像のサイズにエレメントの大きさを合わせてからアニメーション開始
  var self = this;
  first.find('img').one('load', function() {
    self.panel.width(first.width());
    self.panel.height(first.height());
    self.change();
  }).each(function() {
    if (this.complete) $(this).trigger('load');
  });
  // 表示領域にマウスが乗っている間はアニメーションを停止する
  this.panel.mouseenter(function() { 
    self.active = false; 
  }).mouseleave(function() { 
    self.active = true; 
  });
}
ImageSwitch.prototype.change = function(i) {
  if (typeof i == 'undefined') {
    i = this.current_element + 1;
  }
  if (i >= this.elements.length) {
    i = 0;
  }
  var last_id = i-1;
  if (last_id < 0) {
    last_id = this.elements.length -1;
  }
  this.current_element = i;
  var last = this.panel.find(this.element_selector+':nth-child('+(last_id+1)+')');
  var next = this.panel.find(this.element_selector+':nth-child('+(i+1)+')');
  last.fadeOut(this.duration);
  var self = this;
  next.fadeIn(this.duration, function() {
    setTimeout(function() {
      if (self.active) {
        self.change();
      } else {
        self.change(i);
      }
    }, self.refresh_time);
  });
  this.panel.width(next.width());
  this.panel.height(next.height());
}

var image_switch, image_switch2;
$(document).ready(function() {
  image_switch = new ImageSwitch('#content', 3000);
  image_switch2 = new ImageSwitch('#right_section', 3000);
});
