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

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

    this.condition = new Searcher.Example.ConditionPanel(this);
    this.result = new Searcher.Example.ResultPanel(this);
  },
  showList: function(json) {
    Searcher.LoaderPanel.hide();
    this.result.showList(json);
  },
  showDetail: function(json) {
    Searcher.LoaderPanel.hide();
    this.result.showDetail(json);
  }
});

/*
 * Searcher.Example.ConditionPanel
 */
Searcher.Example.ConditionPanel = Class.create({
  initialize: function(container) {
    this.container = container;
    this.node = this.container.node.down('.condition.content_panel');

    $('example_previous_button').observe('click', this.previous.bindAsEventListener(this));
    $('form_freeword').observe('submit', function(event){ event.stop(); });
    $('freeword').value = $F('default_freeword');
    $('freeword').observe('focus', function(){
      if($F('freeword') == $F('default_freeword')) $('freeword').value = '';
      $('freeword').removeClassName('default');
    });
    $('freeword').observe('blur', function(){
      if($F('freeword').length == 0) {
        $('freeword').addClassName('default');
        $('freeword').value = $F('default_freeword');
      }
    });
    $('search_by_freeword_button').observe('click', function(){
      this.modeFreeword = true;
      this.modeKeyword = false;
      $('page').value = '1';
      this.request('search_container');
    }.bindAsEventListener(this));
    $('freeword').observe('keydown', function(event){
      if(event.keyCode == 13) {
        this.modeFreeword = true;
        this.modeKeyword = false;
        $('page').value = '1';
        this.request('search_container');
      }
    }.bindAsEventListener(this));

    $('search_by_keyword_button').observe('click', function(){
      this.modeFreeword = false;
      this.modeKeyword = true;
      $('page').value = '1';
      this.request('search_container');
    }.bindAsEventListener(this));
    $('form_keyword').observe('submit', function(event){ event.stop(); });
  },
  show: function(){
    this.container.node.insert(this.node);
    this.node.show();
  },
  previous: function() {
    this.container.result.removePager();
    if(this.container.result.listVisible || this.container.result.fromRandom){
          this.requesting = false;
      this.container.result.fromRandom = false;
          Searcher.LoaderPanel.hide();
          this.show();
      }else{
          Searcher.LoaderPanel.hide();
          this.container.result.showList(this.container.result.listJson);
      }
  },
  /**
   * Ajax request
   */
  request: function(target) {
    if(this.modeFreeword) this.requestForFreeword(target);
    if(this.modeKeyword) this.requestForKeyword(target);
  },
  /**
   * Ajax request
   */
  requestForFreeword: function(target) {
    try{
      var text = $F('freeword').replace(/[\s　]+/g, ' ');
      var keywords = '';
      text.split(' ').each(function(item){
        if(!item) return;
        keywords += '"' + item + '"';
      }.bind(this));
      Mokkotsu.Page.tracker('/search/example/' + keywords);
    }catch(e){
      // alert(e);
    }

    this.requesting = true;
    var params = Form.serialize($('form_freeword')).toQueryParams();
    params.datetime = (new Date()).getTime();
    params.page = $F('page');
    Searcher.LoaderPanel.show(target);
    new Ajax.Request('/cgi-bin/search_by_freeword.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax request
   */
  requestForKeyword: function(target) {
    try{
      var list = $('form_keyword').select('input');
      var keywords = '';
      list.each(function(item) {
        if(!item.checked) return;
        keywords += '"' + item.getAttribute('display') + '"';
      });
      Mokkotsu.Page.tracker('/search/example/' + keywords);
    }catch(e){
      // alert(e);
    }

    this.requesting = true;
    var params = Form.serialize($('form_keyword')).toQueryParams();
    params.datetime = (new Date()).getTime();
    params.page = $F('page');

    var queryString = Object.toQueryString(params);
    queryString = queryString.replace(/keyword\d/g, 'idlist');
    Searcher.LoaderPanel.show(target);
    new Ajax.Request('/cgi-bin/search_by_keyword.cgi', {
      method: 'get',
      parameters: queryString,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });

  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    if(!this.requesting) return;
    this.requesting = false;
    (function(){
      var json = xhr.responseText.evalJSON();
      if(json.example_list.length > 0) {
        this.container.showList(json);
      }else{
        Searcher.MessengerPanel.show('search_container');
        Searcher.LoaderPanel.hide();
      }
    }.bind(this).delay(0.5));
  }
});

/*
 * Searcher.Example.ResultPanel
 */
Searcher.Example.ResultPanel = Class.create({
  initialize: function(container) {
    this.container = container;
    this.node = this.container.node.down('.result.content_panel');
    this.result_detail_container = this.container.node.down('.resutlt_detail_container');
    this.wordsList = this.node.down('ul.search_keywords_list');
    this.clearWordsList();

    this.list = new Searcher.Example.ResultPanel.List(this.node.down('.results'));
    this.detail = new Searcher.Example.ResultPanel.Detail(this.node.down('.example_detail'));

    // $('example_previous_button').observe('click', this.previous.bindAsEventListener(this));
  },
  previous: function() {
    if(!this.container.result.detailVisible) return;
    Searcher.LoaderPanel.hide();
    this.showList(this.listJson);
  },
  removePager: function() {
    if(!this.pager) return;
    Element.remove(this.pager.node);
    this.pager = null;
  },
  showList: function(json){
    this.listJson = json;
    var text = '';
    this.clearWordsList();
    if(this.container.condition.modeFreeword) {
      text = 'フリーワード絞り込み';
      this.buildFreewords();
    }else if(this.container.condition.modeKeyword) {
      text = '検索ワード絞り込み';
      this.buildKeywords();
    }

    this.pager = new Searcher.Pager(this.node, {
      text:text,
      totalCount:parseInt(json.pager.item_count),
      currentPage:parseInt($F('page'))
    });
    this.setupPaging();
    this.list.listup(json);
    this.result_detail_container.insert(this.list.node);
    this.container.node.insert(this.node);
    this.node.show();
    this.listVisible = true;
    this.detailVisible = false;
  },
  showDetail: function(json){
    if(this.fromRandom) this.clearWordsList();
    this.detail.show(json);
    this.result_detail_container.insert(this.detail.node);
    this.container.node.insert(this.node);
    this.node.show();
    this.listVisible = false;
    this.detailVisible = true;
  },
  buildFreewords: function() {
    var text = $F('freeword').replace(/[\s　]+/g, ' ');
    text.split(' ').each(function(item){
      if(!item) return;
      this.wordsList.insert(Builder.node('li', item));
    }.bind(this));
  },
  buildKeywords: function() {
    var list = $('search_area').select('.category li input');
    list.each(function(item){
      if(!item.checked) return;
      var label = item.next();
      this.wordsList.insert(Builder.node('li', label.innerHTML));
    }.bind(this));
  },
  clearWordsList: function(){
    var list = this.wordsList.select('li');
    list.each(Element.remove);
  },
  setupPaging: function() {
    this.pager.previous.observe('click', function(){
      var page = parseInt($F('page')) - 1;
      this.goPage(page);
    }.bindAsEventListener(this));
    this.pager.next.observe('click', function(){
      var page = parseInt($F('page')) + 1;
      this.goPage(page);
    }.bindAsEventListener(this));

    var list = this.pager.node.select('ul.pages li a.number');
    list.each(function(item){
      item.observe('click', function(){
        var page = parseInt(item.innerHTML);
        this.goPage(page);
      }.bind(this));
    }.bind(this));
  },
  goPage: function(page) {
    if(!this.pager.isValidPage(page)) return;
    $('page').value = page;
    this.pager.node.hide();
    this.container.condition.request(this.container.result.list.node);
  }
});

/*
 * Searcher.Example.ResultPanel.List
 */
Searcher.Example.ResultPanel.List = Class.create({
  initialize: function(node) {
    this.node = node;
    this.build();
  },
  build: function(){
    this.upper = Builder.node('ul', { className:'images clearfix' });
    this.node.insert(Builder.node('div', { className:'upper' }, this.upper));

    this.lower = Builder.node('ul', { className:'images clearfix' });
    this.node.insert(Builder.node('div', { className:'lower' }, this.lower));
  },
  listup: function(json){
    this.clear(this.upper);
    this.clear(this.lower);

    var element = this.upper;
    json.example_list.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 imgPreloader = new Image();
      imgPreloader.onload = (function(){
        if(Prototype.Browser.IE) {
          if((imgPreloader.width / imgPreloader.height) > (116 / 78)) {
            imgPreloader.width = '116';
            imgPreloader.removeAttribute('height');
          }else{
            imgPreloader.height = '78';
            imgPreloader.removeAttribute('width');
          }
        }
        var anchor = Builder.node('a', { href:'javascript:void(0);' }, imgPreloader);
        if(item.is_new) anchor.insert(Builder.node('img', { className:'icon_new', src:'/common/imgs/store_new_tag.png' }));
        node.insert(anchor);
      });
      imgPreloader.src = src;
      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', function(){
        this.request(item.data_code);
      }.bind(this));
      element.insert(listItem);
      if((index + 1) % 5 != 0) element.insert($(Builder.node('li', { className:'ph' })).update('&nbsp;'));
    }.bind(this));
  },
  clear: function(element){
    $(element).select('li').each(Element.remove);
  },
  /**
   * Ajax request
   */
  request: function(data_code) {
    var params = {};
    params.datetime = (new Date()).getTime();
    params.id = data_code;
    Searcher.LoaderPanel.show(this.node);
    new Ajax.Request('/cgi-bin/example.cgi', {
      method: 'get',
      parameters: params,
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    (function(){
      var json = xhr.responseText.evalJSON();
      Searcher.Page.exampleSearcher.showDetail(json);
    }.bind(this).delay(0.5));
  }
});

/*
 * Searcher.Example.ResultPanel.Detail
 */
Searcher.Example.ResultPanel.Detail = Class.create({
  initialize: function(node) {
    this.node = node;
  },
  show: function(json){
    Mokkotsu.Page.tracker('/search/' + json.shop_id + '/example/' + json.data_code);
    if(this.details) Element.remove(this.details);
    this.details = $(Builder.node('div'));
    this.node.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 + '/' + json.data_code + '/example/'));
      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) > (95 / 65)) {
            img.width = '95';
            img.removeAttribute('height');
          }else{
            img.height = '65';
            img.removeAttribute('width');
          }
        }
        var anchor = Builder.node('a', { href:src, rel:'lightbox[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' }));
    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 + '/' + json.data_code + '/example/'));
    }
    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));
  }
});

/*
 * Searcher.Example.KeywordManager
 */
Searcher.Example.KeywordManager = Class.create({
  initialize: function(callback) {
    this.callback = callback;
    this.request();
  },
  /**
   * Ajax request
   */
  request: function() {
    new Ajax.Request('/cgi-bin/category_keyword.cgi', {
      method: 'get',
      parameters: 'datetime=' + (new Date()).getTime(),
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    var json = xhr.responseText.evalJSON();
    this.listup(json);
    if(Object.isFunction(this.callback)) {
      this.callback();
    }
  },
  listup: function(json) {
    // 価格帯を固定で追加
    json.push({
      "category":"価格帯","check_type":"radio",
      "category_id":"cost",
      "keyword_list":[
        {"keyword":"〜2,000万円","keyword_id":"1"},
        {"keyword":"2,000〜2,500万円","keyword_id":"2"},
        {"keyword":"2,500〜3,000万円","keyword_id":"3"},
        {"keyword":"3,000〜3,500万円","keyword_id":"4"},
        {"keyword":"3,500〜4,000万円","keyword_id":"5"},
        {"keyword":"4,000万円〜","keyword_id":"6"},
        {"keyword":"指定なし","keyword_id":"0"}
      ]
    });
    json.push({
      "category":"コンテスト","check_type":"checkbox",
      "category_id":"special",
      "keyword_list":[
        {"keyword":"2010コンテスト物件","keyword_id":"contest"}
      ]
    });
    var list = [];
    json.each(function(category){
      var keyword_list = [];
      category.keyword_list.each(function(keyword){
        var keyword_id = 'keyword' + keyword.keyword_id;

        if(category.category_id == 'cost') {
          keyword_list.push(
            Builder.node('li', { className:'clearfix' }, [
              Builder.node('input', { type:category.check_type, id:'cost' + keyword.keyword_id, value:keyword.keyword_id, name:'cost', display:keyword.keyword }),
              Builder.node('label', { 'for':'cost' + keyword.keyword_id }, keyword.keyword)
            ])
          );
        }else if(category.category_id == 'special') {
          keyword_list.push(
            Builder.node('li', { className:'clearfix' }, [
              Builder.node('input', { type:category.check_type, id:keyword.keyword_id, value:keyword.keyword_id, name:keyword.keyword_id, display:keyword.keyword }),
              Builder.node('label', { 'for':keyword.keyword_id }, keyword.keyword)
            ])
          );
        }else{
          keyword_list.push(
            Builder.node('li', { className:'clearfix' }, [
              Builder.node('input', { type:category.check_type, id:keyword_id, value:keyword.keyword_id, name:'keyword' + category.category_id, display:keyword.keyword }),
              Builder.node('label', { 'for':keyword_id }, keyword.keyword)
            ])
          );
        }
      });
      var item = Builder.node('li', [
        Builder.node('img', { src:'/common/imgs/example_search_category_' + category.category_id + '.gif', alt:category.category }),
        Builder.node('ul', { className:'keyword' }, keyword_list)
      ]);
      list.push(item);
    });
    $('form_keyword').insert(Builder.node('ol', { className:'category clearfix' }, list));
  }
});

/*
 * Searcher.Example.RandomList
 */
Searcher.Example.RandomList = Class.create({
  initialize: function() {
    this.node = $('searcher').down('.example_list_area ul.images');
    this.request();
  },
  /**
   * Ajax request
   */
  request: function() {
    new Ajax.Request('/cgi-bin/random_image_list.cgi', {
      method: 'get',
      parameters: 'datetime=' + (new Date()).getTime(),
      onComplete: this.requestComplete.bindAsEventListener(this)
    });
  },
  /**
   * Ajax requestComplete
   */
  requestComplete: function(xhr) {
    var json = xhr.responseText.evalJSON(true);
    this.listup(json);
  },
  listup: function(json) {
    json.each(function(item){
      if(!item.photo1 || !item.name) return;

      var node = $(Builder.node('li', { className:'photo' }));
      this.node.insert(node);
      this.node.insert($(Builder.node('li', { className:'ph' })).update('&nbsp;'));

      // 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 imgPreloader = new Image();
      imgPreloader.onload = (function(){
        if(Prototype.Browser.IE) {
          if((imgPreloader.width / imgPreloader.height) > (100 / 67)) {
            imgPreloader.width = '100';
            imgPreloader.removeAttribute('height');
          }else{
            imgPreloader.height = '67';
            imgPreloader.removeAttribute('width');
          }
        }

        var anchor = Builder.node('a', { href:'javascript:void(0);', title:item.name }, imgPreloader);
        if(item.is_new) anchor.insert(Builder.node('img', { className:'icon_new', src:'/common/imgs/store_new_tag.png' }));
        node.insert(anchor);
      });
      imgPreloader.src = src;

      node.observe('click', function(){
        Searcher.MessengerPanel.hide();
        Searcher.LoaderPanel.show('search_container');
        Searcher.Page.exampleSearcher.result.fromRandom = true;
        Searcher.Page.exampleSearcher.result.list.request(item.data_code);
      }.bind(this));
    }.bind(this));
  }
});

