if(!Searcher.Shop) Searcher.Shop = {};

/*
 * Searcher.Shop.Searcher
 */
Searcher.Shop.Searcher = Class.create({
  initialize: function() {
    this.node = $('searcher').down('.shop.tab_content');

    this.lead = new Searcher.Shop.LeadContainer(this);
    this.menu = new Searcher.Shop.MenuContainer(this);
    this.resultList = new Searcher.Shop.ResultListContainer(this);

    this.setupStateSwitch();
    this.setupStateSwitchGroup();
    this.setupSelectArea();

    this.node.down('.search_menu_area p select.area').observe('change', function(event){
      var item = Searcher.Map.find(event.target.value);
      if(!item) return;
      var img = this.node.down('.search_menu_area p.shop_area_map img');
      img.src = item.image;
      event.target.next('a').observe('click', function() {
        img.src = '/common/imgs/jmap_default.gif';
      });
    }.bindAsEventListener(this));

    var shop_id = Mokkotsu.Page.args.s || '';
    var view_id = Mokkotsu.Page.args.v || '';
    if(shop_id.match(/\d+/) && view_id.match(/[123]/)) {
      Searcher.Page.tabManager.changeTab($('top_shop_button'));
      Searcher.Page.tabManager.activate('shop');
      Searcher.Page.infomationPanel.node.hide();
      var obj = this.resultList.get('shop');
      obj.details.node.show();
      Searcher.LoaderPanel.show(this.node.up());
      if(view_id == '1') obj.details.tabManager.activate('kodawari', shop_id);
      if(view_id == '2') obj.details.tabManager.activate('detail', shop_id);
      if(view_id == '3') obj.details.tabManager.activate('event', shop_id);
      obj.details.request(shop_id);
    }

  },
  setupSelectArea: function() {
    this.node.select('select.area').each(function(element){
      Searcher.MapList.each(function(area){
        var list = [];
        area.items.each(function(item){
          list.push(Builder.node('option', { value:item.map_id }, item.name));
        });
        element.insert(Builder.node('optgroup', { label: area.name }, list));
      });
      element.down('option').selected = true;

      element.observe('change', function(event){
        if(event.target.value == '') {
          element.next('a').switchOff();
        }else{
          element.next('a').switchOn();
        }
      });
      element.next('a').observe('click', function() {
        if(!element.next('a').hasClassName('on')) return;
        element.selectedIndex = 0;
      });
    });
  },
  setupStateSwitch: function() {
    this.node.select('a.state_switch').each(function(anchor){
      anchor.switchState = function() {
        var options = {
          transition: Effect.Transitions.sinoidal,
          x: 42,
          duration: 0.2,
          afterFinish: function() {
            anchor.toggleClassName('on');
            anchor.fire('button:stateChanged');
          },
          queue: { scope: 'state_switch', limit: 1 }
        };
        if(!anchor.hasClassName('on')) options.x *= -1;
        new Effect.Move(anchor.down('img'), options);
      };
      anchor.observe('click', anchor.switchState);
      anchor.isSwitchOn = function() {
        return (anchor.hasClassName('on'));
      };
      anchor.switchOn = function() {
        if(anchor.isSwitchOn()) return;
        anchor.switchState();
      };
      anchor.switchOff = function() {
        if(!anchor.isSwitchOn()) return;
        anchor.switchState();
      };
    });
  },
  setupStateSwitchGroup: function() {
    this.node.select('div.state_switch_group').each(function(group){

      var items = group.select('a.state_switch_item');
      items.each(function(anchor){
        anchor.hoge = function() {alert(9);};
        anchor.observe('click', function() {

          var options = {
            sync: true,
            transition: Effect.Transitions.sinoidal,
            x: 42,
            afterFinish: function(args) { $(args.element.up()).toggleClassName('on'); }
          };

          var effects = [];
          if(!anchor.hasClassName('on')) {
            items.each(function(item) {
              if(!item.hasClassName('on')) return;
              if(item == anchor) return;
              effects.push(new Effect.Move(item.down('img'), options));
            });
          }
          if(!anchor.hasClassName('on')) options.x *= -1;
          effects.push(new Effect.Move(anchor.down('img'), options));
          new Effect.Parallel(effects, {
            duration: 0.2,
            afterFinish: function() { anchor.fire('button:stateChanged'); },
            queue: { scope: 'state_switch', limit: 1 }
          });
        });

        anchor.isSwitchOn = function() {
          return (anchor.hasClassName('on'));
        };

      });
    });
  }
});

/*
 * Searcher.Shop.LeadContainer
 */
Searcher.Shop.LeadContainer = Class.create({
  initialize: function(container) {
    this.container = container;
    this.list = this.container.node.select('div.lead_container .item');
  },
  change: function(name) {
    this.list.each(function(item){
      if(item.hasClassName(name)) {
        item.show();
      }else{
        item.hide();
      }
    });
  }
});

/*
 * Searcher.Shop.MenuContainer
 */
Searcher.Shop.MenuContainer = Class.create({
  initialize: function(container) {
    this.container = container;

    this.menuItems = [];
    this.container.node.select('.search_shop_menu li').each(function(item){
      this.menuItems.push(new Searcher.Shop.MenuItem(item));
      item.observe('item:click', this.itemClicked.bindAsEventListener(this));
    }.bind(this));
    this.container.node.select('.search_shop_menu li').each(function(item){
      item.addClassName('down');
    });
    this.container.node.down('.search_shop_menu li').removeClassName('down').addClassName('up active');
  },
  itemClicked: function(event) {
    Searcher.Page.shopSearcher.resultList.list[0].details.hide();
    var menuItem = event.memo.node;
    if(menuItem.hasClassName('active')) return;

    var effects = [];
    if(menuItem.hasClassName('up')) {
      menuItem.up().select('.up').each(function(item){
        if(menuItem == item) return;
        if(menuItem.offsetTop > item.offsetTop) return;
        item.removeClassName('up').addClassName('down');
        effects.push(new Effect.Move(item, { y: 263, sync: true }));
      });
    }else if(menuItem.hasClassName('down')){
      menuItem.up().select('.down').each(function(item){
        if(menuItem.offsetTop < item.offsetTop) return;
        item.removeClassName('down').addClassName('up');
        effects.push(new Effect.Move(item, { y: -263, sync: true }));
      });
    }else{
      return;
    }
    new Effect.Parallel(effects, {
      duration: 0.3,
      transition: Effect.Transitions.sinoidal,
      queue: { scope: 'shop_menu', limit: 1 }
    });
    menuItem.up().select('li').each(function(item){
      item.removeClassName('active');
    });
    menuItem.addClassName('active');
    event.memo.mouseout();
    Searcher.Page.shopSearcher.lead.change(event.memo.name);
    Searcher.Page.shopSearcher.resultList.change(event.memo.name);
    if(event.memo.name == 'shop') {
      Searcher.Page.tabManager.changeTab($('top_shop_button'));
      Mokkotsu.Page.tracker('/search/shop_data');
    }
    if(event.memo.name == 'blog') {
      Searcher.Page.tabManager.changeTab($('top_shop_diary_button'));
      Mokkotsu.Page.tracker('/search/shop_diary');
    }
    if(event.memo.name == 'event') {
      Searcher.Page.tabManager.changeTab($('top_shop_event_button'));
      Mokkotsu.Page.tracker('/search/shop_event');
    }
  },
  activate: function(name) {
    this.menuItems.each(function(item){
      if(name != item.name) return;
      item.node.fire('item:click', item);
    });
  }
});

/*
 * Searcher.Shop.MenuItem
 */
Searcher.Shop.MenuItem = Class.create({
  initialize: function(node) {
    this.node = node;
    this.name = this.node.className;
    var anchor = $(this.node.down('a.menu_button'));
    anchor.observe('click', this.node.fire.curry('item:click', this));
    anchor.observe('mouseover', this.mouseover.bindAsEventListener(this));
    anchor.observe('mouseout', this.mouseout.bindAsEventListener(this));
  },
  mouseover: function() {
    if(this.node.hasClassName('active')) return;
    var img = this.node.down('img');
    img.src = img.src.replace(/_off\./,'_on.');
  },
  mouseout: function() {
    var img = this.node.down('img');
    img.src = img.src.replace(/_on\./,'_off.');
  }
});


/*
 * Searcher.Shop.ResultListContainer
 */
Searcher.Shop.ResultListContainer = Class.create({
  list: [],
  initialize: function(container) {
    this.node = container.node.down('div.result_content');
    this.list.push(new Searcher.Shop.ShopResultListItem(this.node.down('div.result_content_item.shop')));
    this.list.push(new Searcher.Shop.BlogResultListItem(this.node.down('div.result_content_item.blog')));
    this.list.push(new Searcher.Shop.EventResult(this.node.down('div.result_content_item.event')));
  },
  change: function(name) {
    this.list.each(function(item){
      if(!item.node.hasClassName(name)) return;
      this.node.insert(item.node);
      if(Object.isFunction(item.showList)) item.showList();
    }.bind(this));
  },
  get: function(name) {
    var obj;
    this.list.each(function(item){
      if(!item.node.hasClassName(name)) return;
      obj = item;
      return;
    }.bind(this));
    return obj
  }
});

/*
 * 施工店検索 施工店情報
 * Searcher.Shop.ShopResultListItem
 */
Searcher.Shop.ShopResultListItem = Class.create({
  initialize: function(node) {
    this.node = node;
    this.build();
    this.firstRequest = true;
    this.request();

    this.selectArea = $('searcher').down('.shop.tab_content div.search_shop_menu ul li.shop .search_menu_area select.area');
    this.selectArea.observe('change', this.stateChanged.bindAsEventListener(this));

    this.selectArea.next('a').observe('button:stateChanged', function() {
      if(this.selectArea.next('a').hasClassName('on')) return;
      this.selectArea.selectedIndex = 0;
      this.stateChanged();
    }.bind(this));

    this.details = new Searcher.Shop.DetailsContentManager(this.listArea);
  },
  showList: function() {
    this.details.hide();
  },
  stateChanged: function() {
    if(!this.json) return;
    Searcher.LoaderPanel.show(this.listArea);
    this.pager.node.hide();
    var item = Searcher.Map.find(this.selectArea.value);
    var param = { text: '全一覧' };
    if(item && item.name) {
      param.text = '「' + item.name + '」で絞り込み結果一覧';
      param.filter = function(obj){ return (obj.area_pref.indexOf(item.name) > -1); }
      Mokkotsu.Page.tracker('/search/serch_tool/refine/area/' + item.name + '/shop');
    }
    this.listup.curry(param).bind(this).delay(0.5);
  },
  build: function(){
    this.messengerPanel = $(Builder.node('div', { className: 'messenger', style: 'display:none;' }, Builder.node('span', '該当するものは、ございませんでした。')));
    this.node.insert({ top: this.messengerPanel });

    this.listArea = $(Builder.node('div', { className:'result_list_area results' }));
    this.node.insert(this.listArea);

    this.upper = Builder.node('ul', { className:'images' });
    this.listArea.insert(Builder.node('div', { className:'upper' }, this.upper));

    this.lower = Builder.node('ul', { className:'images' });
    this.listArea.insert(Builder.node('div', { className:'lower' }, this.lower));
  },
  listup: function(args){
    var options = Object.extend({
      text: '全一覧',
      filter: Prototype.K,
      page: 1
    }, args || { });

    this.clear(this.upper);
    this.clear(this.lower);

    var element = this.upper;
    var itemPerPages = 10;
    var from = itemPerPages * (options.page - 1);
    var to = from + itemPerPages;

    var filteredList = this.json.clone().findAll(options.filter);
    var slicedList = filteredList.slice(from, to);

    slicedList.each(function(item, index){
      if(index >= 5) element = this.lower;
      // var src = 'http://www.mokkotsu.com/net/thumbnail/' + item.photo1;
      // var src = 'http://www.ncn-se.co.jp/wm/03/photo.php?pid=' + item.photo1;
      var src = 'http://www.mokkotsu.com/net/upload/' + item.photo1;
      var node = Builder.node('span', { className:'image' } );

      var img = new Image();
      img.src = '/common/imgs/noimage.gif';
      var imgPreloader = new Image();
      imgPreloader.onload = (function(){
        img.src = src;
        if(Prototype.Browser.IE) {
          if((img.width / img.height) > (116 / 78)) {
            img.width = '116';
            img.removeAttribute('height');
          }else{
            img.height = '78';
            img.removeAttribute('width');
          }
        }
      });
      imgPreloader.src = src;

      $(node).insert(Builder.node('a', { href:'javascript:void(0);', title:item.name }, img));
      var listItem =
        Builder.node('li', [
          node,
          Builder.node('a', { className:'info' }, [
            Builder.node('span', { className:'name' }, item.shop_name),
            Builder.node('span', { className:'place' }, '(' + item.pref + ')')
          ])
        ]);
      $(listItem).observe('click', function(){
        // 施工店の詳細を表示
        Searcher.LoaderPanel.show(this.node);
        this.details.tabManager.activate('detail', item.shop_id);
        this.details.request(item.shop_id);
      }.bind(this));
      element.insert(listItem);
      if((index + 1) % 5 != 0) element.insert($(Builder.node('li', { className:'ph' })).update('&nbsp;'));
    }.bind(this));

    if(this.pager) Element.remove(this.pager.node);
    this.pager = new Searcher.Pager(this.node, {
      text: options.text,
      totalCount: filteredList.length,
      currentPage: options.page
    });
    this.setupPaging(options);
    if(slicedList.length == 0) {
      this.messengerPanel.show();
    }else{
      this.messengerPanel.hide();
    }
    if(!this.firstRequest) Searcher.LoaderPanel.hide();
    this.firstRequest = false;
  },
  setupPaging: function(options) {
    this.pager.previous.observe('click', function(){
      var clonedOptions = Object.clone(options);
      clonedOptions.page -= 1;
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      Searcher.LoaderPanel.show(this.listArea);
      this.pager.node.hide();
      this.listup.curry(clonedOptions).bind(this).delay(0.5);
    }.bindAsEventListener(this));

    this.pager.next.observe('click', function(){
      var clonedOptions = Object.clone(options);
      clonedOptions.page += 1;
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      Searcher.LoaderPanel.show(this.listArea);
      this.pager.node.hide();
      this.listup.curry(clonedOptions).bind(this).delay(0.5);
    }.bindAsEventListener(this));

    var list = this.pager.node.select('ul.pages li a.number');
    list.each(function(item){
      var clonedOptions = Object.clone(options);
      clonedOptions.page = parseInt(item.innerHTML, 10);
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      item.observe('click', function(){
        Searcher.LoaderPanel.show(this.listArea);
        this.pager.node.hide();
        clonedOptions.page = parseInt(item.innerHTML, 10);
        this.listup.curry(clonedOptions).bind(this).delay(0.5);
      }.bind(this));
    }.bind(this));
  },
  clear: function(element){
    $(element).select('li').each(Element.remove);
  },
  /**
   * Ajax request
   */
  request: function() {
    var params = {};
    params.datetime = (new Date()).getTime();
    new Ajax.Request('/cgi-bin/select_shop_list.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    this.json = xhr.responseText.evalJSON();
    this.updateAreaCount();
    this.listup.bind(this).delay(0.5);
  },
  updateAreaCount: function() {
    this.selectArea.select('option').each(function(option){
      if(!option.value.toString()) return;
      var count = 0;
      this.json.each(function(item){
        if(item.area_pref.indexOf(option.innerHTML) > -1) count++;
      });
      if(count > 0) {
        option.update(option.innerHTML + '&nbsp;(' + count +'件)');
      }else{
        option.addClassName('nodata');
      }
    }.bind(this));
  }
});

/*
 * 施工店検索 経営者ブログ
 * Searcher.Shop.BlogResultListItem
 */
Searcher.Shop.BlogResultListItem = Class.create({
  initialize: function(node) {
    this.node = node;
    this.build();
    this.firstRequest = true;
    this.request();

    this.selectArea = $('searcher').down('.shop.tab_content div.search_shop_menu ul li.blog .search_menu_area select.area');
    this.selectArea.observe('change', this.stateChanged.bindAsEventListener(this));

    this.selectArea.next('a').observe('button:stateChanged', function() {
      if(this.selectArea.next('a').hasClassName('on')) return;
      this.selectArea.selectedIndex = 0;
      this.stateChanged();
    }.bindAsEventListener(this));

    this.sortByNew = $('searcher').down('.shop.tab_content div.search_shop_menu ul li.blog a.state_switch.sort_by_new');
    this.sortByNew.observe('button:stateChanged', this.stateChanged.bindAsEventListener(this));

  },
  stateChanged: function() {
    if(!this.json) return;
    Searcher.LoaderPanel.show(this.listArea);
    this.pager.node.hide();
    var item = Searcher.Map.find(this.selectArea.value);
    var param = { text: '全一覧' };
    if(item && item.name) {
      param.text = '「' + item.name + '」で絞り込み結果一覧';
      param.filter = function(obj){ return (obj.area_pref.indexOf(item.name) > -1); };
      Mokkotsu.Page.tracker('/search/serch_tool/refine/area/' + item.name + '/diary');
    }
    if(this.sortByNew.isSwitchOn()) {
      param.text += ' / 新着順';
      param.sort = function(obj){ return parseInt(obj.date_diff, 10); };
      Mokkotsu.Page.tracker('/search/serch_tool/sort/newly/dairy');
    }
    this.listup.curry(param).bind(this).delay(0.5);
  },
  build: function(){
    this.messengerPanel = $(Builder.node('div', { className: 'messenger', style: 'display:none;' }, Builder.node('span', '該当するものは、ございませんでした。')));
    this.node.insert({ top: this.messengerPanel });

    this.listArea = $(Builder.node('div', { className:'result_list_area results' }));
    this.node.insert(this.listArea);

    this.upper = Builder.node('ul', { className:'images' });
    this.listArea.insert(Builder.node('div', { className:'upper' }, this.upper));

    this.lower = Builder.node('ul', { className:'images' });
    this.listArea.insert(Builder.node('div', { className:'lower' }, this.lower));
  },
  listup: function(args){
    var options = Object.extend({
      text: '全一覧',
      filter: Prototype.K,
      sort: Prototype.K,
      page: 1
    }, args || { });

    this.clear(this.upper);
    this.clear(this.lower);

    var element = this.upper;
    var itemPerPages = 10;
    var from = itemPerPages * (options.page - 1);
    var to = from + itemPerPages;

    var filteredList = this.json.clone().findAll(options.filter).sortBy(options.sort);
    var slicedList = filteredList.slice(from, to);

    slicedList.each(function(item, index){
      if(index >= 5) element = this.lower;
      // var src = 'http://www.mokkotsu.com/net/thumbnail/' + item.daihyo_photo;
      // var src = 'http://www.ncn-se.co.jp/wm/03/photo.php?pid=' + item.daihyo_photo;
      var src = 'http://www.mokkotsu.com/net/upload/' + item.daihyo_photo;
      if(!item.daihyo_photo) src = '/common/imgs/noimage.gif';
      var node = Builder.node('span', { className:'image' } );

      var imgPreloader = new Image();
      imgPreloader.onload = (function(){
        var img = new Image();
        img.src = src;
        if(Prototype.Browser.IE) {
          if((img.width / img.height) > (116 / 78)) {
            img.width = '116';
            img.removeAttribute('height');
          }else{
            img.height = '78';
            img.removeAttribute('width');
          }
        }
        $(node).insert(Builder.node('a', { href:'javascript:void(0);', title:item.daihyo_name }, img));
      });
      imgPreloader.src = src;
      var listItem =
        Builder.node('li', [
          node,
          Builder.node('a', { className:'info' }, [
            Builder.node('span', { className:'date' }, '更新日 ' + item.date),
            Builder.node('span', { className:'name' }, item.shop_name),
            Builder.node('span', { className:'place' }, '(' + item.pref + ')')
          ])
        ]);
      $(listItem).observe('click', function(){
        window.open('/diary/?shop_id=' + item.shop_id);
      });
      element.insert(listItem);
      if((index + 1) % 5 != 0) element.insert($(Builder.node('li', { className:'ph' })).update('&nbsp;'));
    }.bind(this));

    if(this.pager) Element.remove(this.pager.node);
    this.pager = new Searcher.Pager(this.node, {
      text: options.text,
      totalCount: filteredList.length,
      currentPage: options.page
    });
    this.setupPaging(options);
    if(slicedList.length == 0) {
      this.messengerPanel.show();
    }else{
      this.messengerPanel.hide();
    }
    if(!this.firstRequest) Searcher.LoaderPanel.hide();
    this.firstRequest = false;
  },
  setupPaging: function(options) {
    this.pager.previous.observe('click', function(){
      var clonedOptions = Object.clone(options);
      clonedOptions.page -= 1;
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      Searcher.LoaderPanel.show(this.listArea);
      this.pager.node.hide();
      this.listup.curry(clonedOptions).bind(this).delay(0.5);
    }.bindAsEventListener(this));

    this.pager.next.observe('click', function(){
      var clonedOptions = Object.clone(options);
      clonedOptions.page += 1;
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      Searcher.LoaderPanel.show(this.listArea);
      this.pager.node.hide();
      this.listup.curry(clonedOptions).bind(this).delay(0.5);
    }.bindAsEventListener(this));

    var list = this.pager.node.select('ul.pages li a.number');
    list.each(function(item){
      var clonedOptions = Object.clone(options);
      clonedOptions.page = parseInt(item.innerHTML, 10);
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      item.observe('click', function(){
        Searcher.LoaderPanel.show(this.listArea);
        this.pager.node.hide();
        clonedOptions.page = parseInt(item.innerHTML, 10);
        this.listup.curry(clonedOptions).bind(this).delay(0.5);
      }.bind(this));
    }.bind(this));
  },
  clear: function(element){
    $(element).select('li').each(Element.remove);
  },
  /**
   * Ajax request
   */
  request: function() {
    var params = {};
    params.datetime = (new Date()).getTime();
    new Ajax.Request('/cgi-bin/select_blog_list.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    this.json = xhr.responseText.evalJSON();
    this.updateAreaCount();
    this.listup.bind(this).delay(0.5);
  },
  updateAreaCount: function() {
    this.selectArea.select('option').each(function(option){
      if(!option.value.toString()) return;
      var count = 0;
      this.json.each(function(item){
        if(item.area_pref.indexOf(option.innerHTML) > -1) count++;
      });
      if(count > 0) {
        option.update(option.innerHTML + '&nbsp;(' + count +'件)');
      }else{
        option.addClassName('nodata');
      }
    }.bind(this));
  }

});

/*
 * 施工店情報 イベント
 * Searcher.Shop.EventResult
 */
Searcher.Shop.EventResult = Class.create({
  initialize: function(node) {
    this.node = node;
    this.build();
    this.showList();
  },
  build: function() {
    var listNode = Builder.node('div', { className:'list' });
    this.node.insert(listNode);
    this.list = new Searcher.Shop.EventResultListItem(listNode);
    this.list.parent = this;

    var detailNode = Builder.node('div', { className:'detail' });
    this.node.insert(detailNode);
    this.detail = new Searcher.Shop.EventResultDetailItem(detailNode);
    this.detail.parent = this;
  },
  showList: function() {
    // this.node.insert(this.list.node);
    $(this.detail.node).hide();
  },
  showDetail: function() {
    // this.node.insert(this.detail.node);
    $(this.detail.node).show();
  }
});

/*
 * Searcher.Shop.EventResultListItem
 */
Searcher.Shop.EventResultListItem = Class.create({
  initialize: function(node) {
    this.node = $(node);
    this.build();
    this.firstRequest = true;
    this.request();

    this.selectArea = $('searcher').down('.shop.tab_content div.search_shop_menu ul li.event .search_menu_area select.area');
    this.selectArea.observe('change', this.stateChanged.bindAsEventListener(this));

    this.selectArea.next('a').observe('button:stateChanged', function() {
      if(this.selectArea.next('a').hasClassName('on')) return;
      this.selectArea.selectedIndex = 0;
      this.stateChanged();
    }.bindAsEventListener(this));

    this.filterByOpen = $('searcher').down('.shop.tab_content div.search_shop_menu ul li.event a.state_switch_item.open');
    this.filterByOpen.observe('button:stateChanged', this.stateChanged.bindAsEventListener(this));
    this.filterByFuture = $('searcher').down('.shop.tab_content div.search_shop_menu ul li.event a.state_switch_item.future');
    this.filterByFuture.observe('button:stateChanged', this.stateChanged.bindAsEventListener(this));
    this.filterByAlways = $('searcher').down('.shop.tab_content div.search_shop_menu ul li.event a.state_switch_item.always');
    this.filterByAlways.observe('button:stateChanged', this.stateChanged.bindAsEventListener(this));

  },
  stateChanged: function() {
    if(!this.json) return;
    Searcher.LoaderPanel.show(this.listArea);
    this.pager.node.hide();
    var item = Searcher.Map.find(this.selectArea.value);
    var param = { text: '全一覧' };
    if(item && item.name) {
      param.text = '「' + item.name + '」';
      param.filter = function(obj){
        if(this.filterByOpen.isSwitchOn()) {
          return (obj.pref.indexOf(item.name) > -1) && obj.union_order == '1';
        }else if(this.filterByFuture.isSwitchOn()) {
          return (obj.pref.indexOf(item.name) > -1) && obj.union_order == '2';
        }else if(this.filterByAlways.isSwitchOn()) {
          return (obj.pref.indexOf(item.name) > -1) && obj.union_order == '3';
        }else{
          return (obj.pref.indexOf(item.name) > -1);
        }
      }.bind(this);
      Mokkotsu.Page.tracker('/search/serch_tool/refine/area/' + item.name + '/event');

      if(this.filterByOpen.isSwitchOn()) {
        param.text += ' / 「開催中」で絞り込み結果一覧';
        Mokkotsu.Page.tracker('/search/serch_tool/refine/period/now/event');
      }else if(this.filterByFuture.isSwitchOn()) {
        param.text += ' / 「これから開催！」で絞り込み結果一覧';
        Mokkotsu.Page.tracker('/search/serch_tool/refine/period/next/event');
      }else if(this.filterByAlways.isSwitchOn()) {
        param.text += ' / 「常時開催」で絞り込み結果一覧';
        Mokkotsu.Page.tracker('/search/serch_tool/refine/period/alldays/event');
      }else{
        param.text += 'で絞り込み結果一覧';
      }
    }else{
      param.filter = function(obj){
        if(this.filterByOpen.isSwitchOn()) {
          return obj.union_order == '1';
        }else if(this.filterByFuture.isSwitchOn()) {
          return obj.union_order == '2';
        }else if(this.filterByAlways.isSwitchOn()) {
          return obj.union_order == '3';
        }else{
          return true;
        }
      }.bind(this);
      if(this.filterByOpen.isSwitchOn()) {
        param.text = '「開催中」で絞り込み結果一覧';
        Mokkotsu.Page.tracker('/search/serch_tool/refine/period/now/event');
      }else if(this.filterByFuture.isSwitchOn()) {
        param.text = '「これから開催！」で絞り込み結果一覧';
        Mokkotsu.Page.tracker('/search/serch_tool/refine/period/next/event');
      }else if(this.filterByAlways.isSwitchOn()) {
        param.text = '「常時開催」で絞り込み結果一覧';
        Mokkotsu.Page.tracker('/search/serch_tool/refine/period/alldays/event');
      }
    }
    this.listup.curry(param).bind(this).delay(0.5);
  },
  build: function(){
    this.messengerPanel = $(Builder.node('div', { className: 'messenger', style: 'display:none;' }, Builder.node('span', '該当するものは、ございませんでした。')));
    this.node.insert({ top: this.messengerPanel });

    this.listArea = $(Builder.node('div', { className:'result_list_area event_list_area' }));
    this.node.insert(this.listArea);

    this.eventList = Builder.node('ul');
    this.listArea.insert(Builder.node('div', { className:'scroll_container' }, this.eventList));

    var scrollContainer = this.listArea.down('.scroll_container');
    var top = $(Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/to_top_off.gif', alt:'先頭へ戻る' })));
    top.observe('click', function() { new Effect.Tween(null, scrollContainer.scrollTop, 0, { duration:0.2 }, function(p){ scrollContainer.scrollTop = p }); });
    Mokkotsu.Page.setupButton(top);
    scrollContainer.insert(Builder.node('p', { className:'to_top' }, top));
  },
  processTopButton: function(element) {
    var scrollContainer = element.down('.scroll_container');
    if(!scrollContainer) return;
    if(scrollContainer.scrollHeight == 0) return;
    if(scrollContainer.getHeight() >= scrollContainer.scrollHeight) {
      scrollContainer.down('p.to_top').hide();
    }else{
      scrollContainer.down('p.to_top').show();
    }
  },
  listup: function(args){
    var options = Object.extend({
      text: '全一覧',
      filter: Prototype.K,
      sort: Prototype.K,
      page: 1
    }, args || { });

    this.clear(this.eventList);

    var itemPerPages = 10;
    var from = itemPerPages * (options.page - 1);
    var to = from + itemPerPages;

    var filteredList = this.json.clone().findAll(options.filter).sortBy(options.sort);
    var slicedList = filteredList.slice(from, to);

    slicedList.each(function(item){
      // var src = 'http://www.mokkotsu.com/net/thumbnail/' + item.photo1;
      // var src = 'http://www.ncn-se.co.jp/wm/03/photo.php?pid=' + item.photo1;
      var src = 'http://www.mokkotsu.com/net/upload/' + item.photo1;
      if(!item.photo1) src = '/common/imgs/noimage.gif';
      var node = Builder.node('div', { className:'image' } );

      var imgPreloader = new Image();
      imgPreloader.onload = (function(){
        var img = new Image();
        img.src = src;
        img.title = item.photo1_caption;
        if(Prototype.Browser.IE) {
          if((img.width / img.height) > (70 / 100)) {
            img.width = '70';
            img.removeAttribute('height');
          }else{
            img.height = '100';
            img.removeAttribute('width');
          }
        }
        $(node).insert(img);
        if(item.url) {
          var pplink =  Builder.node('a', { className:'button pplink_img', href:item.url, target:'_blank' }, Builder.node('img', { src:'common/imgs/pp_event_button_mini_off.png', alt:'' }));
          Mokkotsu.Page.setupButton(pplink);
          pplink.observe('click', function(event) {
            Mokkotsu.Page.tracker('/pplink/id/' + item.shop_id + '/event/');
            event.stopPropagation();
          });
          $(node).insert(pplink);
        }
      });
      imgPreloader.src = src;

      var dl = $(Builder.node('dl', { className:'details' }));
      var listItem = $(Builder.node('li', { className: 'underline' } , Builder.node('div', { className:'inner_area clearfix' }, [node, dl])));

      listItem.observe('click', function(){
        Searcher.LoaderPanel.show(this.listArea);
        this.parent.detail.request(item.data_code);
        Mokkotsu.Page.tracker('/search/' + item.shop_id + '/event/' + item.data_code);
      }.bind(this));

      listItem.observe('mouseover', function(){
        var img = listItem.down('dl dd a.button img');
        img.src = img.src.replace('icon_url_', 'icon_url_gray_');
      }.bind(this));
      listItem.observe('mouseout', function(){
        var img = listItem.down('dl dd a.button img');
        img.src = img.src.replace('icon_url_gray_', 'icon_url_');
      }.bind(this));

      this.eventList.insert(listItem);
      if(slicedList.last() == item) listItem.removeClassName('underline');

      dl.insert(Builder.node('dt', { className: 'title' }, item.event_title));
      dl.insert(Builder.node('dt', '期間'));
      dl.insert(Builder.node('dd', item.event_schedule));
      dl.insert(Builder.node('dt', '場所'));
      dl.insert(Builder.node('dd', item.pref + (item.city || '')));
      dl.insert(Builder.node('dt', '概要'));
      dl.insert(Builder.node('dd', item.comment));
      dl.insert(Builder.node('dt', '施工'));
      dl.insert(Builder.node('dd', item.shop_name));
      dl.insert(Builder.node('dt', 'URL'));
      var anchor =
      $(Builder.node('a', { className:'button', href:item.url, target:'_blank' }, [
        item.url,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_url_off.gif', alt:'' })
      ]));
      anchor.observe('click', function(event){
        Mokkotsu.Page.tracker('/pplink/id/' + item.shop_id + '/event/');
        window.open(item.url);
        event.stop();
      });
      dl.insert(Builder.node('dd', anchor));
      Mokkotsu.Page.setupButton(anchor);
    }.bind(this));
    this.listArea.down('.scroll_container').scrollTop = 0;

    if(this.pager) Element.remove(this.pager.node);
    this.pager = new Searcher.Pager(this.node, {
      text: options.text,
      totalCount: filteredList.length,
      currentPage: options.page
    });
    this.setupPaging(options);
    if(slicedList.length == 0) {
      this.messengerPanel.show();
    }else{
      this.messengerPanel.hide();
    }
    this.processTopButton(this.listArea);
    this.parent.showList();

    if(!this.firstRequest) Searcher.LoaderPanel.hide();
    this.firstRequest = false;
  },
  setupPaging: function(options) {
    this.pager.previous.observe('click', function(){
      var clonedOptions = Object.clone(options);
      clonedOptions.page -= 1;
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      Searcher.LoaderPanel.show(this.listArea);
      this.pager.node.hide();
      this.listup.curry(clonedOptions).bind(this).delay(0.5);
    }.bindAsEventListener(this));

    this.pager.next.observe('click', function(){
      var clonedOptions = Object.clone(options);
      clonedOptions.page += 1;
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      Searcher.LoaderPanel.show(this.listArea);
      this.pager.node.hide();
      this.listup.curry(clonedOptions).bind(this).delay(0.5);
    }.bindAsEventListener(this));

    var list = this.pager.node.select('ul.pages li a.number');
    list.each(function(item){
      var clonedOptions = Object.clone(options);
      clonedOptions.page = parseInt(item.innerHTML, 10);
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      item.observe('click', function(){
        Searcher.LoaderPanel.show(this.listArea);
        this.pager.node.hide();
        clonedOptions.page = parseInt(item.innerHTML, 10);
        this.listup.curry(clonedOptions).bind(this).delay(0.5);
      }.bind(this));
    }.bind(this));
  },
  clear: function(element){
    $(element).select('li').each(Element.remove);
  },
  /**
   * Ajax request
   */
  request: function() {
    var params = {};
    params.datetime = (new Date()).getTime();
    new Ajax.Request('/cgi-bin/select_event_list.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    this.json = xhr.responseText.evalJSON();
    this.updateAreaCount();
    this.listup.bind(this).delay(0.5);
  },
  updateAreaCount: function() {
    this.selectArea.select('option').each(function(option){
      if(!option.value.toString()) return;
      var count = 0;
      this.json.each(function(item){
        if(item.pref.indexOf(option.innerHTML) > -1) count++;
      });
      if(count > 0) {
        option.update(option.innerHTML + '&nbsp;(' + count +'件)');
      }else{
        option.addClassName('nodata');
      }
    }.bind(this));
  }
});

/*
 * Searcher.Shop.EventResultDetailItem
 */
Searcher.Shop.EventResultDetailItem = Class.create({
  initialize: function(node) {
    this.node = node;
    this.build();
    this.setupTitle();
  },
  build: function(){

  },
  setupTitle: function() {
    var node = $('searcher').down('div.lead_container .item.event_title');
    this.title = node.down('span.title');
    var list_button = node.down('span.return a.button');
    list_button.observe('click', function(){
      this.title.update('');
      Searcher.Page.shopSearcher.lead.change('event');
      this.parent.showList();
    }.bindAsEventListener(this));
  },
  /**
   * Ajax request
   */
  request: function(data_code) {
    var params = { id: data_code, datetime: (new Date()).getTime() };
    new Ajax.Request('/cgi-bin/event.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    var json = xhr.responseText.evalJSON();
    this.show.curry(json).bind(this).delay(0.5);
  },
  processTopButton: function(element) {
    var scrollContainer = element.down('.scroll_container');
    if(!scrollContainer) return;
    if(scrollContainer.scrollHeight == 0) return;
    if(scrollContainer.getHeight() >= scrollContainer.scrollHeight) {
      scrollContainer.down('p.to_top').hide();
    }else{
      scrollContainer.down('p.to_top').show();
    }
  },
  show: function(json){
    if(this.details) Element.remove(this.details);
    this.details = $(Builder.node('div'));
    this.node.insert(this.details);

    this.title.update(json.shop_name);

    if(json.chouki_flg) {
      this.details.insert(Builder.node('p', { className:'subtitle' }, json.chouki_flg));
    }

    this.details.insert(Builder.node('p', { className:'title' }, json.event_title));
    this.details.insert(Builder.node('p', { className:'kubun' }, json.kubun));

    var container = $(Builder.node('div', { className:'scroll_container' }));
    if(json.chouki_flg) container.addClassName('short');
    this.details.insert(container);

    if(json.url) {
      var pplink =  Builder.node('a', { className:'button pplink_img', href:json.url, target:'_blank' }, Builder.node('img', { src:'common/imgs/pp_event_button_off.jpg', alt:'' }));
      Mokkotsu.Page.setupButton(pplink);
      pplink.observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/event/'));
      container.insert(pplink);
    }

    var list = [];
    list.push({ photo:json.photo1, caption:json.photo1_caption });
    list.push({ photo:json.photo2, caption:json.photo2_caption });
    list.push({ photo:json.photo3, caption:json.photo3_caption });
    list.push({ photo:json.photo4, caption:json.photo4_caption });
    // list.push({ photo:json.photo5, caption:json.photo5_caption });
    // list.push({ photo:json.photo6, caption:json.photo6_caption });

    var ul = $(Builder.node('ul', { className:'images' }));
    container.insert(ul);
    list.each(function(item, index){
      // var src = 'http://www.ncn-se.co.jp/wm/03/photo.php?pid=' + item.photo;
      var src = 'http://www.mokkotsu.com/net/upload/' + item.photo;
      var li = $(Builder.node('li'));
      ul.insert(li);
      if(index < 5) ul.insert(Builder.node('li', { className:'ph' }, ' '));
      var imgPreloader = new Image();
      imgPreloader.onload = (function(){
        var img = new Image();
        img.src = src;
        if(Prototype.Browser.IE) {
          if((img.width / img.height) > (95 / 65)) {
            img.width = '95';
            img.removeAttribute('height');
          }else{
            img.height = '65';
            img.removeAttribute('width');
          }
        }
        var anchor = Builder.node('a', { href:src, rel:'lightbox[search_shop_detail_event_photo]', title:item.caption }, img);
        $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/search/' + json.shop_id + '/event/' + json.data_code));
        $(li).insert(anchor);
      });
      imgPreloader.src = src;
    }.bind(this));

    var dl = $(Builder.node('dl', { className:'items clearfix' }));
    container.insert(dl);

    var addItem = function(name, value) {
      if(!value) return;
      dl.insert(Builder.node('dt', name));
      if(Object.isElement(value)) {
        dl.insert(Builder.node('dd', value));
      }else{
        dl.insert($(Builder.node('dd')).update(value.toString().replace(/\n/g, '<br />')));
      }
    };

    addItem('期間', json.event_schedule);
    addItem('場所', json.pref + (json.city || ''));
    addItem('概要', json.comment);
    addItem('TEL', json.tel);
    if(json.url) {
      var anchor =
      Builder.node('a', { className:'button', href:json.url, target:'_blank' }, [
        json.url,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_url_off.gif', alt:'' })
      ])
      addItem('URL', anchor);
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/event/'));
    }
    if(json.mail) {
      var anchor =
      Builder.node('a', { className:'button', href:'mailto:' + json.mail }, [
        json.mail,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_mail_off.gif', alt:'' })
      ])
      addItem('MAIL', anchor);
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/search/' + json.shop_id + 'mail'));
    }
    addItem('交通', json.traffic);

    var top = $(Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/to_top_off.gif', alt:'先頭へ戻る' })));
    top.observe('click', function() { new Effect.Tween(null, container.scrollTop, 0, { duration:0.2 }, function(p){ container.scrollTop = p }); });
    Mokkotsu.Page.setupButton(top);
    container.insert(Builder.node('p', { className:'to_top' }, top));

    this.parent.showDetail();
    this.processTopButton(this.details);

    Searcher.Page.shopSearcher.lead.change('event_title');
    Searcher.LoaderPanel.hide();
  }
});

/*
 * 施工店情報 施工店情報 詳細（こだわり、詳細情報、イベントおよび施工物件一覧）
 * Searcher.Shop.DetailsContentManager
 */
Searcher.Shop.DetailsContentManager = Class.create({
  initialize: function(parent) {
    this.parent = parent;
    this.node = $('searcher').down('.shop.tab_content .shop.detail.content_panel');

    this.build();
    this.setupTitle();

    this.tabManager = new Searcher.Shop.DetailsTabManager(this, this.detailsTabArea);
    this.exampleList = new Searcher.Shop.DetailsExampleList(this, this.right);
    this.example = new Searcher.Shop.DetailsExample(this, this.exampleArea);

  },
  setupTitle: function() {
    var node = $('searcher').down('div.lead_container .item.shop_title');
    this.title = node.down('span.title');
    node.down('span.return a.button').observe('click', function() {
      this.hide();
    }.bindAsEventListener(this));
  },
  build: function() {
    this.left = $(Builder.node('div', { className: 'details_left' }));
    this.node.insert(this.left);
    this.detailsTabArea = Builder.node('div', { className: 'detail_tab' });
    this.left.insert(this.detailsTabArea);

    this.exampleArea = Builder.node('div', { className: 'detail_example', style:'display:none;' });
    this.left.insert(this.exampleArea);

    this.right = $(Builder.node('div', { className: 'details_right' }));
    this.node.insert(this.right);
    this.exampleListArea = Builder.node('div', { className: 'example_list results' });
    this.right.insert(this.exampleListArea);

  },
  show: function(json) {
    this.title.update(json.shop_name);
    this.tabManager.cleanup();

    this.tabManager.contentList.kodawari.insert(this.buildTabKodawari(json));
    this.tabManager.contentList.detail.insert(this.buildTabDetail(json));

    this.tabManager.contentList.event.insert(Builder.node('div', { className:'event_container' }, [
       Builder.node('div', { className:'event_list_area' }, this.buildTabEvent(json)),
       Builder.node('div', { className:'event_detail_area', style:'display:none' })
    ]));

    this.exampleList.show(json);

    this.shop_id = json.shop_id;

    Searcher.Page.shopSearcher.lead.change('shop_title');
    this.node.show();
    Searcher.LoaderPanel.hide();
  },
  hide: function() {
    if(!this.node.visible()) return;
    this.title.update('');
    Searcher.Page.shopSearcher.lead.change('shop');
    this.node.hide();
  },
  /**
   * Ajax request
   */
  request: function(shop_id) {
    var params = { id: shop_id, datetime: (new Date()).getTime() };
    new Ajax.Request('/cgi-bin/select_shop_detail.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    var json = xhr.responseText.evalJSON();
    this.show.curry(json).bind(this).delay(0.5);
  },
  buildTabKodawari: function(json) {
    var daihyo_photo = '/common/imgs/noimage.gif';
    if(json.daihyo_photo) daihyo_photo = 'http://www.mokkotsu.com/net/upload/' + json.daihyo_photo;

    var links = [];
    if(json.has_blog) {
      var anchor = Builder.node('a', { href: 'javascript:void(0);', className: 'blog button' }, Builder.node('img', { src: '/common/imgs/diary_off.gif' }));
      $(anchor).observe('click', function() {
        Mokkotsu.Page.tracker('/search/' + json.shop_id + '/dairy/data_code');
        window.open('/diary/?shop_id=' + json.shop_id);
      });
      links.push(anchor);
      Mokkotsu.Page.setupButton(anchor);
    }
    if(json.url) {
      var pplink =  Builder.node('a', { className:'button pplink_img', href:json.url, target:'_blank' }, Builder.node('img', { src:'common/imgs/pp_info_button_off.jpg', alt:'' }));
      Mokkotsu.Page.setupButton(pplink);
      pplink.observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/detail/'));
      links.push(pplink);
    }
    var kodawari = [];
    if(json.kodawari){
      kodawari.push(Builder.node('p', { className: 'section_title' }, Builder.node('img', { src:'/common/imgs/shop_details_title_kodawari.gif', alt:'こだわり' })));
      kodawari.push($(Builder.node('p')).update(json.kodawari.replace(/\n/g, '<br />')));
    }
    var node =
      $(Builder.node('div', { className: 'scroll_container' }, [
        Builder.node('div', { className: 'clearfix' }, [
          Builder.node('div', { className: 'president_area' }, [
            Builder.node('span', { className: 'image' }, Builder.node('img', { src:daihyo_photo })),
            links
          ]),
          $(Builder.node('p', { className: 'introduce' })).update((json.shop_introduce || '').replace(/\n/g, '<br />')),
          kodawari
        ])
      ]));

    var top = $(Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/to_top_off.gif', alt:'先頭へ戻る' })));
    top.observe('click', function() { new Effect.Tween(null, node.scrollTop, 0, { duration:0.2 }, function(p){ node.scrollTop = p }); });
    Mokkotsu.Page.setupButton(top);
    node.insert(Builder.node('p', { className:'to_top', style:'display:none;' }, top));

    return node;
  },
  buildTabDetail: function(json) {
    var node = Builder.node('div', { className: 'scroll_container' });
    var dl = $(Builder.node('dl', { className:'items clearfix' }));
    if(json.url) {
      var pplink =  Builder.node('a', { className:'button pplink_img', href:json.url, target:'_blank' }, Builder.node('img', { src:'common/imgs/pp_info_button_off.jpg', alt:'' }));
      Mokkotsu.Page.setupButton(pplink);
      $(pplink).observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/detail/'));
      $(node).insert(pplink);
    }
    $(node).insert(dl);

    var addItem = function(name, value) {
      if(!value) return;
      dl.insert(Builder.node('dt', name));
      dl.insert($(Builder.node('dd')).update(value.replace(/\n/g, '<br />')));
    };

    addItem('会社名', json.shop_name);
    if(json.url) dl.select("dd:last-child")[0].addClassName('wrap');
    addItem('郵便番号', json.zipcode);
    if(json.map) {
      dl.insert(Builder.node('dt', '住所'));
      var anchor =
      Builder.node('a', { className:'button', rel:'lightbox', href:'http://www.mokkotsu.com/net/upload/' + json.map, title: json.map_caption },
        Builder.node('img', { className:'icon', src:'/common/imgs/shop_access_map_off.jpg', alt:'' })
      )
      dl.insert(Builder.node('dd', [ json.pref + (json.city || '') + (json.address || ''), anchor]));
      Mokkotsu.Page.setupButton(anchor);
    }else{
      if(json.pref) addItem('住所', json.pref + (json.city || '') + (json.address || ''));
    }
    if(json.url) dl.select("dd:last-child")[0].addClassName('wrap');
    addItem('TEL', json.tel);
    addItem('FAX', json.fax);

    if(json.url) {
      dl.insert(Builder.node('dt', 'Webサイト'));
      var anchor =
      Builder.node('a', { className:'button', href:json.url, target:'_blank' }, [
        json.url,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_url_off.gif', alt:'' })
      ])
      dl.insert(Builder.node('dd', anchor));
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/detail/'));
    }
    if(json.url2) {
      dl.insert(Builder.node('dt', 'ブログ'));
      var anchor =
      Builder.node('a', { className:'button', href:json.url2, target:'_blank' }, [
        json.url2,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_url_off.gif', alt:'' })
      ])
      dl.insert(Builder.node('dd', anchor));
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/detail/'));
    }
    if(json.mail) {
      dl.insert(Builder.node('dt', 'メールアドレス'));
      var anchor =
      Builder.node('a', { className:'button', href:'mailto:' + json.mail }, [
        json.mail,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_mail_off.gif', alt:'' })
      ])
      dl.insert(Builder.node('dd', anchor));
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/search/' + json.shop_id + '/mail'));
    }
    addItem('お客様窓口', json.madoguchi);
    addItem('設立', json.establish);
    addItem('資本金', json.capital);
    addItem('従業員', json.jyugyo_num);
    addItem('本体価格目安', json.price);
    addItem('施工エリア', json.area);
    addItem('施工実績（年度）', json.construct);
    addItem('代表設計士', json.architect_name);
    addItem('代表設計士の資格・経歴', json.architect_license);
    addItem('代表SE構法施工管理技士', json.engineer_name);
    addItem('代表SE構法施工管理技士番号', json.engineer_no);
    addItem('アフター・保障', json.after);
    addItem('設立許可番号', json.kyoka_no);

    var top = $(Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/to_top_off.gif', alt:'先頭へ戻る' })));
    top.observe('click', function() { new Effect.Tween(null, node.scrollTop, 0, { duration:0.2 }, function(p){ node.scrollTop = p }); });
    Mokkotsu.Page.setupButton(top);
    node.insert(Builder.node('p', { className:'to_top', style:'display:none;' }, top));

    return node;
  },
  buildTabEvent: function(json) {
    if(!json.event_list) return;
    var node = $(Builder.node('div', { className: 'scroll_container' }));
    if(json.event_list.length == 0) {
      node.insert(Builder.node('div', { className: 'messenger' }, Builder.node('span', '予定されているイベントはありません。')));
      return node;
    }
    var eventList = $(Builder.node('ul'));
    node.insert(eventList);
    json.event_list.each(function(item){
      // var src = 'http://www.mokkotsu.com/net/thumbnail/' + item.photo1;
      // var src = 'http://www.ncn-se.co.jp/wm/03/photo.php?pid=' + item.photo1;
      var src = 'http://www.mokkotsu.com/net/upload/' + item.photo1;
      if(!item.photo1) src = '/common/imgs/noimage.gif';
      var node = Builder.node('div', { className:'image' } );

      var imgPreloader = new Image();
      imgPreloader.onload = (function(){
        var img = new Image();
        img.src = src;
        img.title = item.photo1_caption;
        if(Prototype.Browser.IE) {
          if((img.width / img.height) > (70 / 100)) {
            img.width = '70';
            img.removeAttribute('height');
          }else{
            img.height = '100';
            img.removeAttribute('width');
          }
        }
        $(node).insert(img);

        if(json.url) {
          var pplink =  Builder.node('a', { className:'button pplink_img', href:json.url, target:'_blank' }, Builder.node('img', { src:'common/imgs/pp_event_button_mini_off.png', alt:'' }));
          Mokkotsu.Page.setupButton(pplink);
          pplink.observe('click', function(event) {
            Mokkotsu.Page.tracker('/pplink/id/' + json.shop_id + '/event/');
            event.stopPropagation();
          });
          $(node).insert(pplink);
        }
      });
      imgPreloader.src = src;

      var dl = $(Builder.node('dl', { className:'details' }));
      var listItem = $(Builder.node('li', { className: 'underline' } , Builder.node('div', { className:'inner_area clearfix' }, [node, dl])));

      listItem.observe('click', function(){
        Searcher.LoaderPanel.show(this.detailsTabArea);
        var event = new Searcher.Shop.DetailsEvent(node.up('.event_container'));
        event.request(item.data_code);
        Mokkotsu.Page.tracker('/search/' + json.shop_id + '/event/' + item.data_code);
      }.bind(this));

      listItem.observe('mouseover', function(){
        var img = listItem.down('dl dd a.button img');
        img.src = img.src.replace('icon_url_', 'icon_url_gray_');
      }.bind(this));
      listItem.observe('mouseout', function(){
        var img = listItem.down('dl dd a.button img');
        img.src = img.src.replace('icon_url_gray_', 'icon_url_');
      }.bind(this));

      eventList.insert(listItem);
      if(json.event_list.last() == item) listItem.removeClassName('underline');

      dl.insert(Builder.node('dt', { className: 'title' }, item.event_title));
      dl.insert(Builder.node('dt', '期間'));
      dl.insert(Builder.node('dd', item.event_schedule));
      dl.insert(Builder.node('dt', '場所'));
      dl.insert(Builder.node('dd', item.pref + (item.city || '')));
      dl.insert(Builder.node('dt', '概要'));
      dl.insert(Builder.node('dd', item.comment));
      dl.insert(Builder.node('dt', '施工'));
      dl.insert(Builder.node('dd', item.shop_name));
      dl.insert(Builder.node('dt', 'URL'));
      var anchor =
      $(Builder.node('a', { className:'button', href:item.url, target:'_blank' }, [
        item.url,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_url_off.gif', alt:'' })
      ]));
      anchor.observe('click', function(event){
        window.open(item.url);
        event.stop();
      });
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/event/'));
      dl.insert(Builder.node('dd', anchor));
      Mokkotsu.Page.setupButton(anchor);
    }.bind(this));

    var top = $(Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/to_top_off.gif', alt:'先頭へ戻る' })));
    top.observe('click', function() { new Effect.Tween(null, node.scrollTop, 0, { duration:0.2 }, function(p){ node.scrollTop = p }); });
    Mokkotsu.Page.setupButton(top);
    node.insert(Builder.node('p', { className:'to_top', style:'display:none;' }, top));

    return node;
  }
});

/*
 * Searcher.Shop.DetailsTabManager
 */
Searcher.Shop.DetailsTabManager = Class.create({
  initialize: function(manager, container) {
    this.manager = manager;
    this.container = $(container);
    this.tabList = {};
    this.contentList = {};
    this.build();
    this.node = this.container.down('ul.tab');
  },
  cleanup: function() {
    for(var name in this.contentList) {
      var container = $(this.contentList[name]).down();
      if(!container) continue;
      container.remove();
    }
  },
  build: function() {
    // タブの作成
    this.tabList.kodawari = Builder.node('li', { className: 'kodawari' }, Builder.node('a', { href: 'javascript:void(0);', className: 'button'}, Builder.node('img', { src:'/common/imgs/shop_details_kodawari_active_off.gif', alt:'こだわり' })));
    this.tabList.detail = Builder.node('li', { className: 'detail' }, Builder.node('a', { href: 'javascript:void(0);', className: 'button'}, Builder.node('img', { src:'/common/imgs/shop_details_info_inactive_off.gif', alt:'詳細情報' })));
    this.tabList.event = Builder.node('li', { className: 'event' }, Builder.node('a', { href: 'javascript:void(0);', className: 'button'}, Builder.node('img', { src:'/common/imgs/shop_details_event_inactive_off.gif', alt:'イベント' })));

    this.tabList.kodawari.down('a.button').observe('click', function(){
      this.activate('kodawari', this.manager.shop_id);
    }.bindAsEventListener(this));

    this.tabList.detail.down('a.button').observe('click', function(){
      this.activate('detail', this.manager.shop_id);
    }.bindAsEventListener(this));

    this.tabList.event.down('a.button').observe('click', function(){
      this.activate('event', this.manager.shop_id);
    }.bindAsEventListener(this));

    Mokkotsu.Page.setupButton(this.tabList.kodawari.down('a.button'));
    Mokkotsu.Page.setupButton(this.tabList.detail.down('a.button'));
    Mokkotsu.Page.setupButton(this.tabList.event.down('a.button'));

    var ul = Builder.node('ul', { className: 'tab clearfix' }, [this.tabList.kodawari, this.tabList.detail, this.tabList.event]);
    this.container.insert(ul);

    // タブ別のコンテンツ作成
    this.contentList.kodawari = Builder.node('div', { className: 'tab_content kodawari' });
    this.contentList.detail = Builder.node('div', { className: 'tab_content detail' });
    this.contentList.event = Builder.node('div', { className: 'tab_content event' });

    this.tabContainer = $(Builder.node('div', { className:'tab_content_container' }, [this.contentList.kodawari, this.contentList.detail, this.contentList.event]));
    this.container.insert(this.tabContainer);
  },
  activate: function(activateThis, shop_id) {
    for(var name in this.tabList) {
      var tab = this.tabList[name];
      var anchor = tab.down('a.button');
      var img = tab.down('img');
      if(this.tabList[activateThis] == tab) {
        img.src = img.src.replace('_inactive_', '_active_');
        anchor.addClassName('active');
        this.tabContainer.insert(this.contentList[name]);
        this.processTopButton(this.contentList[name]);
      }else{
        anchor.removeClassName('active');
        img.src = img.src.replace('_active_', '_inactive_');
      }
    }
    if(activateThis == 'kodawari' ) Mokkotsu.Page.tracker('/search/' + shop_id + '/detail/kodawari');
    if(activateThis == 'detail' ) Mokkotsu.Page.tracker('/search/' + shop_id + '/detail/data');
    if(activateThis == 'event' ) Mokkotsu.Page.tracker('/search/' + shop_id + '/detail/event');
  },
  processTopButton: function(element) {
    var scrollContainer = element.down('.scroll_container');
    if(!scrollContainer) return;
    if(scrollContainer.getHeight() >= scrollContainer.scrollHeight) return;
    if(scrollContainer.down('p.to_top').visible()) return;
    scrollContainer.down('p.to_top').show();
    scrollContainer.scrollTop = 0;
  }
});

/*
 * 施工店情報 施工店情報 施工物件一覧
 * Searcher.Shop.DetailsExampleList
 */
Searcher.Shop.DetailsExampleList = Class.create({
  initialize: function(container, node) {
    this.container = container;
    this.node = node;
    this.listArea = node.down('.example_list');
    this.build();
  },
  build: function(){
    this.upper = Builder.node('ul', { className:'images' });
    this.listArea.insert(Builder.node('div', { className:'upper' }, this.upper));

    this.lower = Builder.node('ul', { className:'images' });
    this.listArea.insert(Builder.node('div', { className:'lower' }, this.lower));
  },
  show: function(json) {
    this.container.example.node.hide();
    this.json = json;
    this.listup();
  },
  listup: function(args){
    if(!this.json.example_list) return;
    var options = Object.extend({
      text: '',
      page: 1
    }, args || { });

    this.clear(this.upper);
    this.clear(this.lower);

    var element = this.upper;
    var itemPerPages = 4;
    var from = itemPerPages * (options.page - 1);
    var to = from + itemPerPages;

    var clonedList = this.json.example_list.clone();
    var slicedList = clonedList.slice(from, to);

    slicedList.each(function(item, index){
      if(index >= 2) element = this.lower;
      // var src = 'http://www.mokkotsu.com/net/thumbnail/' + item.photo1;
      // var src = 'http://www.ncn-se.co.jp/wm/03/photo.php?pid=' + item.photo1;
      var src = 'http://www.mokkotsu.com/net/upload/' + item.photo1;
      var node = Builder.node('span', { className:'image' } );

      var img = new Image();
      img.src = '/common/imgs/noimage.gif';
      var imgPreloader = new Image();
      imgPreloader.onload = (function(){
        img.src = src;
        if(Prototype.Browser.IE) {
          if((img.width / img.height) > (116 / 78)) {
            img.width = '116';
            img.removeAttribute('height');
          }else{
            img.height = '78';
            img.removeAttribute('width');
          }
        }
      });
      imgPreloader.src = src;

      var anchor = Builder.node('a', { href:'javascript:void(0);', title:item.name }, img);
      if(item.is_new && item.daihyo_flg == "0") anchor.insert(Builder.node('img', { className:'icon_new', src:'/common/imgs/store_new_tag.png' }));
      node.insert(anchor);
      var listItem =
        Builder.node('li', [
          node,
          Builder.node('a', { className:'info' }, [
            Builder.node('span', { className:'place' }, item.place),
            Builder.node('span', { className:'name' }, item.name)
          ])
        ]);
      $(listItem).observe('click', this.showDetail.curry(item.data_code).bindAsEventListener(this));
      element.insert(listItem);
      if((index + 1) % 2 != 0) element.insert($(Builder.node('li', { className:'ph' })).update('&nbsp;'));
    }.bind(this));

    if(this.pager) Element.remove(this.pager.node);
    this.pager = new Searcher.Pager(this.node, {
      text: options.text,
      totalCount: clonedList.length,
      countPerPage: itemPerPages,
      enumPagesCount: 5,
      currentPage: options.page
    });
    this.setupPaging(options);
    Searcher.LoaderPanel.hide();
  },
  setupPaging: function(options) {
    this.pager.previous.observe('click', function(){
      var clonedOptions = Object.clone(options);
      clonedOptions.page -= 1;
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      Searcher.LoaderPanel.show(this.listArea);
      this.pager.node.hide();
      this.listup.curry(clonedOptions).bind(this).delay(0.5);
    }.bindAsEventListener(this));

    this.pager.next.observe('click', function(){
      var clonedOptions = Object.clone(options);
      clonedOptions.page += 1;
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      Searcher.LoaderPanel.show(this.listArea);
      this.pager.node.hide();
      this.listup.curry(clonedOptions).bind(this).delay(0.5);
    }.bindAsEventListener(this));

    var list = this.pager.node.select('ul.pages li a.number');
    list.each(function(item){
      var clonedOptions = Object.clone(options);
      clonedOptions.page = parseInt(item.innerHTML, 10);
      if(!this.pager.isValidPage(clonedOptions.page)) return;
      item.observe('click', function(){
        Searcher.LoaderPanel.show(this.listArea);
        this.pager.node.hide();
        clonedOptions.page = parseInt(item.innerHTML, 10);
        this.listup.curry(clonedOptions).bind(this).delay(0.5);
      }.bind(this));
    }.bind(this));
  },
  clear: function(element){
    $(element).select('li').each(Element.remove);
  },
  showDetail: function(data_code) {
    Searcher.LoaderPanel.show(this.container.tabManager.container);
    Mokkotsu.Page.tracker('/search/' + this.container.shop_id + '/example/' + data_code);
    this.container.example.request(data_code);
  }
});

/*
 * 施工店情報 施工店情報 詳細の施工物件
 * Searcher.Shop.DetailsExample
 */
Searcher.Shop.DetailsExample = Class.create({
  initialize: function(container, node) {
    this.container = container;
    this.node = $(node);
    this.build();
  },
  build: function(){
    this.detailContainer = $(Builder.node('div', { className:'example_detail' }));
    this.node.insert(this.detailContainer);

    var kodawari = Builder.node('li', Builder.node('a', { href:'javascript:void(0);' }, 'こだわり'));
    $(kodawari).observe('click', this.hidefor.curry('kodawari').bindAsEventListener(this));
    var detail = Builder.node('li', Builder.node('a', { href:'javascript:void(0);' }, '詳細情報'));
    $(detail).observe('click', this.hidefor.curry('detail').bindAsEventListener(this));
    var event = Builder.node('li', Builder.node('a', { href:'javascript:void(0);' }, 'イベント'));
    $(event).observe('click', this.hidefor.curry('event').bindAsEventListener(this));

    var list = [];
    list.push(kodawari);
    list.push(detail);
    list.push(event);
    this.node.insert(Builder.node('ul', { className:'tab_links clearfix' }, list));
  },
  hidefor: function(tabName) {
    this.container.tabManager.activate(tabName, this.shop_id);
    this.node.hide();
  },
  /**
   * Ajax request
   */
  request: function(data_code) {
    if(this.requesting) return;
    this.requesting = true;
    Searcher.LoaderPanel.show(this.node);
    var params = { id: data_code, datetime: (new Date()).getTime() };
    new Ajax.Request('/cgi-bin/example.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    var json = xhr.responseText.evalJSON();
    this.show.curry(json).bind(this).delay(0.5);
  },
  show: function(json){
    this.shop_id = json.shop_id;
    if(this.details) Element.remove(this.details);
    this.details = $(Builder.node('div'));
    this.detailContainer.insert(this.details);

    var vtButton = $(Builder.node('a', { className:'vt', style:'display:none', href:'javascript:void(0);' }, Builder.node('img', { src:'/common/imgs/vt3d_off.gif' })));
    if(json.virtual_town_id) {
      Mokkotsu.Page.setupButton(vtButton);
      vtButton.show();
      vtButton.observe('click', function(){
        var uri = '/vseh/view/index.html';
        var query = '?id=' + json.virtual_town_id;
        var vtwin = window.open(uri + query, 'virtualtown', 'width=920,height=700,scrollbars=yes,resizable=yes');
        vtwin.window.focus();
      });
    }
    this.details.insert(Builder.node('p', { className:'example_name' }, [json.name, vtButton]));

    var container = $(Builder.node('div', { className:'detail_container' }));
    this.details.insert(container);

    if(json.url) {
      var pplink =  Builder.node('a', { className:'button pplink_img', href:json.url, target:'_blank' }, Builder.node('img', { src:'common/imgs/pp_info_button_off.jpg', alt:'' }));
      Mokkotsu.Page.setupButton(pplink);
      pplink.observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/detail/'));
      container.insert(pplink);
    }

    var list = [];
    list.push({ photo:json.photo1, caption:json.photo1_caption });
    list.push({ photo:json.photo2, caption:json.photo2_caption });
    list.push({ photo:json.photo3, caption:json.photo3_caption });
    list.push({ photo:json.photo4, caption:json.photo4_caption });
    list.push({ photo:json.photo5, caption:json.photo5_caption });
    list.push({ photo:json.photo6, caption:json.photo6_caption });

    var ul = $(Builder.node('ul', { id:'detail_images', className:'images' }));
    container.insert(ul);
    list.each(function(item, index){
      // var src = 'http://www.ncn-se.co.jp/wm/03/photo.php?pid=' + item.photo;
      var src = 'http://www.mokkotsu.com/net/upload/' + item.photo;
      var li = $(Builder.node('li'));
      ul.insert(li);
      if(index < 5) ul.insert(Builder.node('li', { className:'ph' }, ' '));
      var imgPreloader = new Image();
      imgPreloader.onload = (function(){
        var img = new Image();
        img.src = src;
        if(Prototype.Browser.IE) {
          if((img.width / img.height) > (83 / 57)) {
            img.width = '83';
            img.removeAttribute('height');
          }else{
            img.height = '57';
            img.removeAttribute('width');
          }
        }
        var anchor = Builder.node('a', { href:src, rel:'lightbox[search_shop_details_photo]', title:item.caption }, img);
        $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/search/' + json.shop_id + '/example/' + json.data_code));
        $(li).insert(anchor);
      });
      imgPreloader.src = src;
    }.bind(this));

    var dl = $(Builder.node('dl', { className:'items clearfix' }));
    container.insert(dl);

    var addItem = function(name, value) {
      if(!value) return;
      dl.insert(Builder.node('dt', name));
      if(Object.isElement(value)) {
        dl.insert(Builder.node('dd', value));
      }else{
        dl.insert($(Builder.node('dd')).update(value.toString().replace(/\n/g, '<br />')));
      }
    };

    addItem('場所', json.place);
    addItem('延べ床面積', json.floor_space + (json.floor_space == '―' ? '' : 'm<sup>2</sup>'));
    addItem('敷地面積', json.site_area + (json.site_area == '―' ? '' : 'm<sup>2</sup>'));
    addItem('カテゴリ', json.category);
    addItem('形態', json.form);
    addItem('竣工', json.completion);
    addItem('施工', json.shop_name);

    if(json.url) {
      var anchor =
      Builder.node('a', { className:'button', href:json.url, target:'_blank' }, [
        json.url,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_url_off.gif', alt:'' })
      ])
      addItem('URL', anchor);
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/detail/'));
    }
    if(json.drawing) {
      var anchor =
      Builder.node('a', { className:'button', rel:'lightbox', href:'http://www.mokkotsu.com/net/upload/' + json.drawing }, [
        'あり',
        Builder.node('img', { className:'icon', src:'/common/imgs/example_detail_plan_off.gif', alt:'' })
      ])
      addItem('プラン図', anchor);
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/search/' + json.shop_id + '/' + json.data_code + '/plan'));
    }

    if(json.architect_name) {
      var charge = $(Builder.node('div', { className:'charge clearfix' }));
      if(json.engineer_name) charge.addClassName('dot');
      container.insert(charge);

      var image = $(Builder.node('div', { className:'image' }));
      charge.insert(image);
      if(json.architect_photo) {
        image.insert(Builder.node('img', { src:'http://www.mokkotsu.com/net/thumbnail/' + json.architect_photo, alt:'設計' }));
      }else{
        image.insert(Builder.node('span', '設計'));
      }
      var content = $(Builder.node('div', { className:'content' }));
      charge.insert(content);
      content.insert($(Builder.node('p', { className:'person' })).update('私が担当しました。<br />設計： ' + json.architect_name));
      if(json.architect_comment) content.insert($(Builder.node('p')).update(json.architect_comment.replace(/\n/g, '<br />')));
    }

    if(json.engineer_name) {
      var charge = $(Builder.node('div', { className:'charge clearfix' }));
      container.insert(charge);

      var image = $(Builder.node('div', { className:'image' }));
      charge.insert(image);
      if(json.engineer_photo) {
        image.insert(Builder.node('img', { src:'http://www.mokkotsu.com/net/thumbnail/' + json.engineer_photo, alt:'施工' }));
      }else{
        image.insert(Builder.node('span', '施工'));
      }
      var content = $(Builder.node('div', { className:'content' }));
      charge.insert(content);
      content.insert($(Builder.node('p', { className:'person' })).update('私が担当しました。<br />施工：SE構法施工管理技士　' + json.engineer_name));
      if(json.engineer_comment) content.insert($(Builder.node('p')).update(json.engineer_comment.replace(/\n/g, '<br />')));
    }

    var top = $(Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/to_top_off.gif', alt:'先頭へ戻る' })));
    top.observe('click', function() { new Effect.Tween(null, container.scrollTop, 0, { duration:0.2 }, function(p){ container.scrollTop = p }); });
    Mokkotsu.Page.setupButton(top);
    container.insert(Builder.node('p', { className:'to_top' }, top));

    this.node.show();
    Searcher.LoaderPanel.hide();
    this.requesting = false;
  }
});

/*
 * 施工店情報 施工店情報 イベント
 * Searcher.Shop.DetailsEvent
 */
Searcher.Shop.DetailsEvent = Class.create({
  initialize: function(container) {
    this.node = container.down('.event_detail_area');
    this.build();
  },
  build: function(){

  },
  /**
   * Ajax request
   */
  request: function(data_code) {
    var params = { id: data_code, datetime: (new Date()).getTime() };
    new Ajax.Request('/cgi-bin/event.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    var json = xhr.responseText.evalJSON();
    this.show.curry(json).bind(this).delay(0.5);
  },
  processTopButton: function(element) {
    var scrollContainer = element.down('.scroll_container');
    if(!scrollContainer) return;
    if(scrollContainer.scrollHeight == 0) return;
    if(scrollContainer.getHeight() >= scrollContainer.scrollHeight) {
      scrollContainer.down('p.to_top').hide();
    }else{
      scrollContainer.down('p.to_top').show();
    }
  },
  show: function(json){
    if(this.details) Element.remove(this.details);
    this.details = $(Builder.node('div'));
    this.node.insert(this.details);

    if(json.chouki_flg) {
      this.details.insert(Builder.node('p', { className:'subtitle' }, json.chouki_flg));
    }
    var returnButton = Builder.node('a', { hrer:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/previous_page_s_off.gif' }));
    Mokkotsu.Page.setupButton(returnButton);
    $(returnButton).observe('click', function(){
      this.details.remove();
      this.node.hide();
    }.bindAsEventListener(this));
    this.details.insert(Builder.node('p', { className:'title clearfix' }, [json.event_title, returnButton]));
    this.details.insert(Builder.node('p', { className:'kubun' }, json.kubun));

    var container = $(Builder.node('div', { className:'scroll_container' }));
    if(json.chouki_flg) container.addClassName('short');
    this.details.insert(container);

    if(json.url) {
      var pplink =  Builder.node('a', { className:'button pplink_img', href:json.url, target:'_blank' }, Builder.node('img', { src:'common/imgs/pp_event_button_off.jpg', alt:'' }));
      Mokkotsu.Page.setupButton(pplink);
      pplink.observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/event/'));
      container.insert(pplink);
    }

    var list = [];
    list.push({ photo:json.photo1, caption:json.photo1_caption });
    list.push({ photo:json.photo2, caption:json.photo2_caption });
    list.push({ photo:json.photo3, caption:json.photo3_caption });
    list.push({ photo:json.photo4, caption:json.photo4_caption });

    var ul = $(Builder.node('ul', { className:'images' }));
    container.insert(ul);
    list.each(function(item, index){
      // var src = 'http://www.ncn-se.co.jp/wm/03/photo.php?pid=' + item.photo;
      var src = 'http://www.mokkotsu.com/net/upload/' + item.photo;
      var li = $(Builder.node('li'));
      ul.insert(li);
      if(index < 5) ul.insert(Builder.node('li', { className:'ph' }, ' '));
      var imgPreloader = new Image();
      imgPreloader.onload = (function(){
        var img = new Image();
        img.src = src;
        if(Prototype.Browser.IE) {
          if((img.width / img.height) > (95 / 65)) {
            img.width = '95';
            img.removeAttribute('height');
          }else{
            img.height = '65';
            img.removeAttribute('width');
          }
        }
        var anchor = Builder.node('a', { href:src, rel:'lightbox[search_shop_event_photo]', title:item.caption }, img);
        $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/search/' + json.shop_id + '/event/' + json.data_code));
        $(li).insert(anchor);
      });
      imgPreloader.src = src;
    }.bind(this));

    var dl = $(Builder.node('dl', { className:'items clearfix' }));
    container.insert(dl);

    var addItem = function(name, value) {
      if(!value) return;
      dl.insert(Builder.node('dt', name));
      if(Object.isElement(value)) {
        dl.insert(Builder.node('dd', value));
      }else{
        dl.insert($(Builder.node('dd')).update(value.toString().replace(/\n/g, '<br />')));
      }
    };

    addItem('期間', json.event_schedule);
    addItem('場所', json.pref + (json.city || ''));
    addItem('概要', json.comment);
    addItem('TEL', json.tel);
    if(json.url) {
      var anchor =
      Builder.node('a', { className:'button', href:json.url, target:'_blank' }, [
        json.url,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_url_off.gif', alt:'' })
      ])
      addItem('URL', anchor);
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/pplink/id/' + json.shop_id + '/event/'));
    }
    if(json.mail) {
      var anchor =
      Builder.node('a', { className:'button', href:'mailto:' + json.mail }, [
        json.mail,
        Builder.node('img', { className:'icon', src:'/common/imgs/icon_mail_off.gif', alt:'' })
      ])
      addItem('MAIL', anchor);
      Mokkotsu.Page.setupButton(anchor);
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/search/' + json.shop_id + '/event/' + json.data_code + 'mail'));
    }
    addItem('交通', json.traffic);

    var top = $(Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/to_top_off.gif', alt:'先頭へ戻る' })));
    top.observe('click', function() { new Effect.Tween(null, container.scrollTop, 0, { duration:0.2 }, function(p){ container.scrollTop = p }); });
    Mokkotsu.Page.setupButton(top);
    container.insert(Builder.node('p', { className:'to_top' }, top));

    this.node.show();
    this.processTopButton(this.details);
    Searcher.LoaderPanel.hide();
  }
});
