var Searcher;
if(!Searcher) Searcher = {};

/*
 * Searcher.Page
 */
Searcher.Page = {
  load: function() {
    this.cookieManager = Mokkotsu.Page.getCookieManager();

    Searcher.LoaderPanel.init();
    Searcher.MessengerPanel.init();

    this.tabManager = new Searcher.TabManager();
    this.infomationPanel = new Searcher.InfomationPanel();

    // example
    this.exampleSearcher = new Searcher.Example.Searcher();
    new Searcher.Example.KeywordManager(function() {
      var keys = Mokkotsu.Page.args.key || '';
      keys.split(',').each(function(key) {
        var checkbox = $('keyword' + key);
        if(checkbox) checkbox.checked = true;
      });
      if(keys) {
        this.exampleSearcher.condition.modeFreeword = false;
        this.exampleSearcher.condition.modeKeyword = true;
        this.exampleSearcher.condition.request('search_container');
      }
    }.bind(this));
    new Searcher.Example.RandomList();

    // shop
    this.shopSearcher = new Searcher.Shop.Searcher();

    // restore
    this.restoreDefaultTab();

    var tab = Mokkotsu.Page.args.t || '';
    if(tab == 'e') {
      this.tabManager.changeTab($('top_example_button'));
      this.tabManager.activate('example');
      this.infomationPanel.hide();
    }else if(tab == 's') {
      var menu = Mokkotsu.Page.args.m || '';
      if(menu == 'b') {
        this.tabManager.changeTab($('top_shop_diary_button'));
        this.shopSearcher.menu.activate('blog');
      }else if(menu == 'e') {
        this.tabManager.changeTab($('top_shop_event_button'));
        this.shopSearcher.menu.activate('event');
      }else{
        this.tabManager.changeTab($('top_shop_button'));
      }
      this.tabManager.activate('shop');
      this.infomationPanel.hide();
    }

  },
  restoreDefaultTab: function() {
    // 他のページから来た際、タブを復元する
    var default_tab = this.cookieManager.getCookie('default_tab');
    if(!default_tab) return;
    if(default_tab == 'example') Searcher.Page.tabManager.changeTab($('top_example_button'));
    this.tabManager.activate(default_tab);
    var default_menu = this.cookieManager.getCookie('default_menu');
    if(default_menu) {
      if(default_menu == 'shop') Searcher.Page.tabManager.changeTab($('top_shop_button'));
      if(default_menu == 'blog') Searcher.Page.tabManager.changeTab($('top_shop_diary_button'));
      if(default_menu == 'event') Searcher.Page.tabManager.changeTab($('top_shop_event_button'));
      Searcher.Page.shopSearcher.menu.activate(default_menu);
    }
    this.infomationPanel.hide();
    this.cookieManager.clearCookie('default_tab');
    this.cookieManager.clearCookie('default_menu');
  }
};
document.observe('dom:loaded', Searcher.Page.load.bind(Searcher.Page));

/*
 * Searcher.InfomationPanel
 */
Searcher.InfomationPanel = Class.create({
  initialize: function() {
    this.node = $('infomation');
    this.slideShow = new Searcher.SlideShow();
  },
  collapse: function() {
    Searcher.Page.tabManager.collapse();
    this.node.hide();
    this.slideShow.stop();
  },
  hide: function() {
    this.node.hide();
    this.slideShow.stop();
  }
});

/*
 * Searcher.SlideShow
 */
Searcher.SlideShow = Class.create({
  duration: 10,
  initialize: function(){
    this.container = $('infomation').down('div.title');
    this.node = this.container.down('ul.slide');
    this.list = this.node.select('li');
    this.node.select('a').each(function(anchor){
      $(anchor).observe('click', Mokkotsu.Page.tracker.curry('/search/banner'));
    });
    if(this.list.length == 1) return;
    this.setupButton();
    this.timer = new PeriodicalExecuter(this.periodHandler.bind(this), this.duration);
  },
  setupButton: function() {
    var list = [];
    this.list.each(function(li){
      var anchor = Builder.node('a', { href:'javascript:void(0);' }, ' ');
      var button = Builder.node('li', anchor);
      li.button = button;
      button.image = li;
      list.push(button);

      button.toggle = $(button).toggleClassName.curry('active');
      $(button).observe('click', function(){
        if(button.hasClassName('active')) return;
        this.timer.stop();
        var pair = this.pair();
        pair.tobe = button.image;
        pair.duration = 0.3;
        this.slide(pair);
        this.timer = new PeriodicalExecuter(this.periodHandler.bind(this), this.duration);
      }.bindAsEventListener(this));
    }.bind(this));
    this.buttonList = list;
    this.buttonList[0].toggle();
    this.container.insert(Builder.node('ul', { className:'slide_button clearfix' }, list));
  },
  periodHandler: function(pe){
    var pair = this.pair();
    this.slide(pair);
  },
  slide_: function(pair) {
    if(this.sliding) return;
    this.sliding = true;
    var effects = [];
    pair.tobe.up().insert(pair.tobe);
    effects.push(new Effect.Appear(pair.tobe, {
      duration: pair.duration,
      transition: Effect.Transitions.sinoidal,
      afterFinish: function(){
        pair.asis.hide();
        pair.asis.removeClassName('active');
        pair.tobe.addClassName('active');
        this.sliding = false;
      }.bind(this),
      queue: { scope: 'slide', limit: 1 }
    }));
    (function(){
      pair.asis.button.removeClassName('active');
      pair.tobe.button.addClassName('active');
    }.delay(pair.duration / 2));

  },
  slide : function(pair) {
    if(this.sliding) return;
    this.sliding = true;
    pair.tobe.up().insert(pair.tobe);

    pair.tobe.button.addClassName('active');
    pair.tobe.addClassName('active');
    pair.tobe.show();

    pair.asis.button.removeClassName('active');
    pair.asis.removeClassName('active');
    pair.asis.hide();

    this.sliding = false;
  },
  pair: function() {
    var asis = this.node.down('li.active');
    var i = this.list.indexOf(asis);
    var tobe = this.list[i + 1];
    if(!tobe) tobe = this.list[0];
    return { asis:asis, tobe:tobe, duration:2.0 };
  },
  stop: function(){
    if(this.timer) this.timer.stop();
  }
});

/*
 * Searcher.TabManager
 */
Searcher.TabManager = Class.create({
  initialize: function() {
    this.node = $('searcher');
    this.anchors = $('tab_area').select('ul.buttons li a.button');
    this.exampleContent = new Searcher.TabContentContainer(this, '.tab_content.example');
    this.shopContent = new Searcher.TabContentContainer(this, '.tab_content.shop');

    $('top_example_button').observe('click', function(ev){
      this.expand();
      this.activate('example');
      this.changeTab($('top_example_button'));
    }.bindAsEventListener(this));

    $('top_shop_button').observe('click', function(ev){
      this.expand();
      this.activate('shop');
      this.changeTab($('top_shop_button'));
      Searcher.Page.shopSearcher.menu.activate('shop');
    }.bindAsEventListener(this));

    $('top_shop_diary_button').observe('click', function(ev){
      this.expand();
      this.activate('shop');
      this.changeTab($('top_shop_diary_button'));
      Searcher.Page.shopSearcher.menu.activate('blog');
    }.bindAsEventListener(this));

    $('top_shop_event_button').observe('click', function(ev){
      this.expand();
      this.activate('shop');
      this.changeTab($('top_shop_event_button'));
      Searcher.Page.shopSearcher.menu.activate('event');
    }.bindAsEventListener(this));
  },
  collapse: function() {
    this.node.removeClassName('expand').addClassName('collapse');
  },
  expand: function() {
    this.node.removeClassName('collapse').addClassName('expand');
  },
  activate: function(tabName) {
    Searcher.Page.infomationPanel.hide();
    Searcher.LoaderPanel.hide();
    this[tabName + 'Content'].show();
    this.expand();
  },
  changeTab: function(item) {
    if(!item.hasClassName('nochange')) {
      var img = item.down();
      img.src=img.src.replace(/_on\./,'_off.');
      if(img.src.match(/_inactive_off\./)) img.src=img.src.replace(/_inactive_off\./,'_off.');
      item.addClassName('nochange');
    }
    this.anchors.each(function(a) {
      if(a == item) return;
      a.removeClassName('nochange');
      var img = a.down();
      if(!img.src.match(/_inactive_off\./)) img.src=img.src.replace(/_off\./,'_inactive_off.');
    });
  }
});

/*
 * Searcher.TabContentContainer
 */
Searcher.TabContentContainer = Class.create({
  initialize: function(tabManager, selector) {
    this.tabManager = tabManager;
    this.node = this.tabManager.node.down(selector);
  },
  show: function(){
    this.tabManager.node.insert(this.node);
    this.node.show();
  }
});

/*
 * Searcher.LoaderPanel
 */
Searcher.LoaderPanel = {
  init: function() {
    this.node = $('loader');
    this.node.hide();
    this.image = this.node.down('img');
  },
  show: function(element) {
    if(this.node.visible()) return;
    try{
      this.node.clonePosition(element);
    }catch(e){
      // alert(e);
    }
    var top = (this.node.getHeight() / 2) - 21;
    var left = (this.node.getWidth() / 2) - 21;
    this.image.setStyle({ top:top + 'px', left:left + 'px' });

    this.node.show();
  },
  hide: function() {
    this.node.hide();
  }
};

/*
 * Searcher.MessengerPanel
 */
Searcher.MessengerPanel = {
  init: function() {
    this.node = $('messenger');
    this.hide();
    this.messsage = this.node.down('.message');
    this.image = this.node.down('img');
    this.image.observe('click', this.hide.bindAsEventListener(this));
  },
  show: function(element) {
    try{
      this.node.clonePosition(element);
    }catch(e){
      // alert(e);
    }

    var top = (this.node.getHeight() - 12) / 2;
    var width = this.node.getWidth();
    this.messsage.setStyle({ top:top + 'px', width:width + 'px' });

    this.node.show();
  },
  hide: function() {
    this.node.hide();
  }
};

/*
 * Searcher.Pager
 */
Searcher.Pager = Class.create({
  initialize: function(container, paramOpt) {
    this.container = container;
    var tmpOpt = Object.extend({
      text: '全一覧',
      currentPage: 1,
      countPerPage: 10,
      totalCount: 0,
      enumPagesCount: 20
    }, paramOpt || { });

    this.options = tmpOpt;
    this.options.pages = Math.ceil(this.options.totalCount / this.options.countPerPage);
    this.build();
  },
  build: function(){
    this.previous = $(Builder.node('li', Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/page_arrow_left_off.gif', alt:'前へ' }))));
    this.previousSkip = $(Builder.node('li', Builder.node('span', '…')));
    this.next = $(Builder.node('li', Builder.node('a', { href:'javascript:void(0);', className:'button' }, Builder.node('img', { src:'/common/imgs/page_arrow_right_off.gif', alt:'次へ' }))));
    this.nextSkip = $(Builder.node('li', Builder.node('span', '…')));

    this.previousSkip = $(this.previousSkip).hide();
    this.nextSkip = $(this.nextSkip).hide();

    var halfSize = (this.options.enumPagesCount / 2);
    var previousSkipCapacity = halfSize;
    var nextSkipCapacity = halfSize;

    if(this.options.currentPage > this.options.pages - halfSize) {
      previousSkipCapacity = this.options.enumPagesCount - (this.options.pages - this.options.currentPage);
      nextSkipCapacity += this.options.enumPagesCount - previousSkipCapacity;
    }
    if(this.options.currentPage < halfSize) {
      nextSkipCapacity = this.options.enumPagesCount - this.options.currentPage;
      previousSkipCapacity = this.options.enumPagesCount - nextSkipCapacity;
    }

    var list = [];
    list.push(this.previous);
    list.push(this.previousSkip);
    $R(1, this.options.pages).each(function(page){
      if(page < this.options.currentPage - previousSkipCapacity){
        this.previousSkip.show();
        return;
      }
      if(page > this.options.currentPage + nextSkipCapacity){
        this.nextSkip.show();
        return;
      }
      var anchor = Builder.node('a', { href:'javascript:void(0);', className:'number' }, page.toString());
      anchor = $(anchor);
      if(this.options.currentPage == page) anchor.addClassName('current');
      list.push(Builder.node('li', anchor));

    }.bind(this));
    list.push(this.nextSkip);
    list.push(this.next);

    this.text = Builder.node('span', { className:'text' }, this.options.text);

    this.node = Builder.node('div', { className:'pager' },[
      this.text,
      Builder.node('ul', { className:'pages clearfix' }, list),
      Builder.node('span', { className:'count' }, '全' + this.options.totalCount + '件')
    ]);
    this.container.insert(this.node);
    this.node = $(this.node);
    if(this.options.pages <= 1) this.node.down('ul.pages').hide();
    if(this.options.currentPage == 1) this.previous.hide();
    if(this.options.currentPage == this.options.pages) this.next.hide();
    Mokkotsu.Page.setupButton(this.previous.down('a.button'));
    Mokkotsu.Page.setupButton(this.next.down('a.button'));
  },
  isValidPage: function(page) {
    if(page < 1) return false;
    if(this.options.pages < page) return false;
    if(this.options.currentPage == page) return false;
    return true;
  }
});

/*
 * Searcher.Map
 */
Searcher.Map = {
  find: function(map_id) {
    var ret = { map_id:'', name:'', image:'/common/imgs/jmap_default.gif' };
    Searcher.MapList.each(function(area){
      area.items.each(function(item){
        if(item.map_id == map_id) ret = item;
      });
    });
    return ret;
  }
};

/*
 * Searcher.MapList
 */
Searcher.MapList = [
  { name: '北海道', items:[
    { map_id:1, name:'北海道', image:'/common/imgs/jmap_hokkaido.gif' }
  ]},
  { name: '東北', items:[
    { map_id:2, name:'青森県', image:'/common/imgs/jmap_aomori.gif' },
    { map_id:3, name:'岩手県', image:'/common/imgs/jmap_iwate.gif' },
    { map_id:4, name:'宮城県', image:'/common/imgs/jmap_miyagi.gif' },
    { map_id:5, name:'秋田県', image:'/common/imgs/jmap_akita.gif' },
    { map_id:6, name:'山形県', image:'/common/imgs/jmap_yamagata.gif' },
    { map_id:7, name:'福島県', image:'/common/imgs/jmap_fukushima.gif' }
  ]},
  { name: '関東', items:[
    { map_id:8, name:'茨城県', image:'/common/imgs/jmap_ibaraki.gif' },
    { map_id:9, name:'栃木県', image:'/common/imgs/jmap_tochigi.gif' },
    { map_id:10, name:'群馬県', image:'/common/imgs/jmap_gunma.gif' },
    { map_id:11, name:'埼玉県', image:'/common/imgs/jmap_saitama.gif' },
    { map_id:12, name:'千葉県', image:'/common/imgs/jmap_chiba.gif' },
    { map_id:13, name:'東京都', image:'/common/imgs/jmap_tokyo.gif' },
    { map_id:14, name:'神奈川県', image:'/common/imgs/jmap_kanagawa.gif' }
  ]},
  { name: '中部', items:[
    { map_id:15, name:'新潟県', image:'/common/imgs/jmap_niigata.gif' },
    { map_id:16, name:'富山県', image:'/common/imgs/jmap_toyama.gif' },
    { map_id:17, name:'石川県', image:'/common/imgs/jmap_ishikawa.gif' },
    { map_id:18, name:'福井県', image:'/common/imgs/jmap_fukui.gif' },
    { map_id:19, name:'山梨県', image:'/common/imgs/jmap_yamanashi.gif' },
    { map_id:20, name:'長野県', image:'/common/imgs/jmap_nagano.gif' },
    { map_id:21, name:'岐阜県', image:'/common/imgs/jmap_gifu.gif' },
    { map_id:22, name:'静岡県', image:'/common/imgs/jmap_shizuoka.gif' },
    { map_id:23, name:'愛知県', image:'/common/imgs/jmap_aichi.gif' }
  ]},
  { name: '近畿', items:[
    { map_id:24, name:'三重県', image:'/common/imgs/jmap_mie.gif' },
    { map_id:25, name:'滋賀県', image:'/common/imgs/jmap_shiga.gif' },
    { map_id:26, name:'京都府', image:'/common/imgs/jmap_kyoto.gif' },
    { map_id:27, name:'大阪府', image:'/common/imgs/jmap_osaka.gif' },
    { map_id:28, name:'兵庫県', image:'/common/imgs/jmap_hyogo.gif' },
    { map_id:29, name:'奈良県', image:'/common/imgs/jmap_nara.gif' },
    { map_id:30, name:'和歌山県', image:'/common/imgs/jmap_wakayama.gif' }
  ]},
  { name: '中国', items:[
    { map_id:31, name:'鳥取県', image:'/common/imgs/jmap_tottori.gif' },
    { map_id:32, name:'島根県', image:'/common/imgs/jmap_shimane.gif' },
    { map_id:33, name:'岡山県', image:'/common/imgs/jmap_okayama.gif' },
    { map_id:34, name:'広島県', image:'/common/imgs/jmap_hiroshima.gif' },
    { map_id:35, name:'山口県', image:'/common/imgs/jmap_yamaguchi.gif' }
  ]},
  { name: '四国', items:[
    { map_id:36, name:'徳島県', image:'/common/imgs/jmap_tokushima.gif' },
    { map_id:37, name:'香川県', image:'/common/imgs/jmap_kagawa.gif' },
    { map_id:38, name:'愛媛県', image:'/common/imgs/jmap_ehime.gif' },
    { map_id:39, name:'高知県', image:'/common/imgs/jmap_kochi.gif' }
  ]},
  { name: '九州', items:[
    { map_id:40, name:'福岡県', image:'/common/imgs/jmap_fukuoka.gif' },
    { map_id:41, name:'佐賀県', image:'/common/imgs/jmap_saga.gif' },
    { map_id:42, name:'長崎県', image:'/common/imgs/jmap_nagasaki.gif' },
    { map_id:43, name:'熊本県', image:'/common/imgs/jmap_kumamoto.gif' },
    { map_id:44, name:'大分県', image:'/common/imgs/jmap_oita.gif' },
    { map_id:45, name:'宮崎県', image:'/common/imgs/jmap_miyazaki.gif' },
    { map_id:46, name:'鹿児島県', image:'/common/imgs/jmap_kagoshima.gif' }
  ]},
  { name: '沖縄', items:[
    { map_id:47, name:'沖縄県', image:'/common/imgs/jmap_okinawa.gif' }
  ]}
];

