//  関連ワードを出力するメソッド
var suggestWord = function (v,commercialTypeParam) {
  $.ajax({
    type: 'GET',
    url: '/common/suggest/v3/json?commercial_type=' + encodeURIComponent(commercialTypeParam) +'&limit=10&q=' + v,
    dataType: 'json'
  }).then(function (json) {
    if ((json.category && json.category.length) || (json.brand && json.brand.length) || (json.brand_category && json.brand_category.length) || (json.shop && json.shop.length) || (json.hotword && json.hotword.length)){
      $.each(json, function(i, v) {
        $.each(v, function(j, x) {
          if(commercialTypeParam != '0|3' && commercialTypeParam != '0|1|2|3'){
            x.commercial_type_param = encodeURIComponent(commercialTypeParam);
          }
          x.brand_name_double_encoded = encodeURIComponent(encodeURIComponent(x.brand_name));
        })
      })
      var template = Handlebars.templates['suggest_pc.template'];
      $('#output_suggestA').html(template(json));
    }
  });
}

//  関連アイテムを出力するメソッド
var suggestItem = function (v,commercialTypeParam) {
  $.ajax({
    type: 'GET',
    url: '/common/auto-complete?commercialType=' + commercialTypeParam + '&q=' + v,
    dataType: 'json'
  }).then(function (json) {
    var template = Handlebars.compile($('#SuggestCommodities').html());
    $('#output_suggestB').html(template({Commodities:json}));
  });
}

//  新・検索履歴出力メソッド
var searchHistory = function () {
  var values = getSearchHistories();
  var newValues = values.slice(0,5);
  var template = Handlebars.compile($('#pcHeader_searchHistory_template').html());
  //Reebokのみ レディース→ウィメンズに変換
  if ( $('#schema').val() == 'reebok' ){
    var newValuesString = JSON.stringify(newValues);
    var newValuesReplace = newValuesString.replace(/レディース/g,'ウィメンズ');
    var newValuesObject = JSON.parse(newValuesReplace);
    $('#output_searchHistory').html(template(newValuesObject)).show();
  } else {
    $('#output_searchHistory').html(template(newValues)).show();
  }
  headerSearchHistoryHeadingPc();
}

// 履歴orサジェストだしわけメソッド
var suggestDist = function () {
  var commercialTypeParam = '0|1|2|3'
  if($('input[name="commercialType"]').length){
    commercialTypeParam = $('input[name="commercialType"]').val();
  }

  var w = $('#searchText').val().length;
  var v = encodeURI($('#searchText').val());

  if(w > 0){
    // サジェスト出す
    suggestWord(v,commercialTypeParam);
    suggestItem(v,commercialTypeParam);
    // 履歴消す
    $('#output_searchHistory').hide();
  }
  if(w == 0){
    // 履歴出す
      searchHistory();
    // サジェスト消す
    $('#output_suggestA').empty();
    $('#output_suggestB').empty();
  }
}

$(function() {
  $('#searchText').focusin(function(e) {
    $('.search_box').addClass('focus');
    // テキストボックスにフォーカス時、入力が0文字だったら検索履歴を出す
    suggestDist();
  });
  $(document).on('click',function(e) {
    if(!$(e.target).closest('.search_box').length) {
      // ターゲット要素の外側をクリックした時の操作
      // フォーカスを外して履歴とサジェストも消す
      $('.search_box').removeClass('focus');
    } else {
      // ターゲット要素をクリックした時の操作
      return;
    }
 });

  $('#searchText').on('keyup', function(e) {
    //　矢印は無効
    switch(e.which){
      case 39: // Key[→]
      return false;
      break;

      case 37: // Key[←]
      return false;
      break;

      case 38: // Key[↑]
      return false;
      break;

      case 40: // Key[↓]
      return false;
      break;
    }
    suggestDist();

  });
});

// #52297 検索結果保存 - テキストの省略メソッド
function headerSearchHistoryHeadingPc (){
  if($('#searchBox #searchHistoryList .indexItemHeading').length){
    $('#searchBox #searchHistoryList .indexItemHeading').each(function () {
    // 複数行を判別
      var H = $(this).height();
      if( H > 30){

        // オリジナルの文章を取得
        var $target = $(this).find('.inner');
        var htmlOrg = $target.html();
        var htmlEdit = htmlOrg;

        // widthを設定して省略
        var W = $target.width();
        if ( W > 290 ){
          $target.after('<span class="displayAll">全て表示</span>' ); 
        
          while ( W > 270 ) {
            htmlEdit = htmlEdit.substr(0, htmlEdit.length - 1);
            $target.html(htmlEdit + "..."); 
            var W = $target.width(); 
          }
        } 
        // 対象の要素を、data-title に入れる
        $target.next('.displayAll').attr('data-title', htmlOrg);
      }
    });

    // 全て表示する
    $('#searchHistoryList .displayAll').on('mousedown', function(){
      var html = $(this).attr('data-title');
      $(this).prev('.inner').html(html);
      $(this).remove();
      return false;
    });

    $('#searchHistoryList .deleteHistoryList').on('click', function(){
      // storageから削除
      var removeItem = $(this).parents('.indexItem');
      var removeItemTitle = $(removeItem).find('.indexItemContent').attr('data-title-localstorage');
      removeSearchHistory(removeItemTitle);
      // 表示されているリスト削除
      $(removeItem).fadeOut(300, function(){
       $(this).remove();
      });
    });

  }
}