/************************************************
 *
 * ameba search
 *
 ************************************************/
 /* プレースホルダ　IE用 */
$(function () {
  var supportsInputAttribute = function (attr) {
    var input = document.createElement('input');
    return attr in input;
  };
  if (!supportsInputAttribute('placeholder')) {
    $('[placeholder]').each(function () {
      var
        input = $(this),
        placeholderText = input.attr('placeholder'),
        placeholderColor = 'GrayText',
        defaultColor = input.css('color');
      input.
        focus(function () {
          if (input.val() === placeholderText) {
            input.val('').css('color', defaultColor);
          }
        }).
        blur(function () {
          if (input.val() === '') {
            input.val(placeholderText).css('color', placeholderColor);
          } else if (input.val() === placeholderText) {
            input.css('color', placeholderColor);
          }
        }).
        blur().
        parents('form').
          submit(function () {
            if (input.val() === placeholderText) {
              input.val('');
            }
          });
    });
  }
});

/* 検索ボックス　クリアボタン */
$(function(){
  $("input.textInput").each(function(i){
    var self = $(this);
    self.wrap("<span id='delval-"+i+"' class='delval-group'></span>");
    $("span#delval-"+i).append("<span class='delval'></span>");

    var btn = $("span.delval", $("span#delval-"+i));

    if(self.val().length<1) btn.hide();

    self.keyup(function(){
      if(self.val().length>0) btn.show();
      else btn.hide();
    });

    btn.click(function(){
      self.val("").focus();
      btn.hide();
    });
  });
});

/* 検索オプション　アコーディオン */
$(function(){
  if($("#searchFilter").hasClass("optSelected")){
    $("#searchFilter").show();
    $("#detailSearch").addClass("opened");
  }
  else	{$("#searchFilter").hide();}

  $("#detailSearch").click(function(){
    $("#searchFilter").slideToggle("fast");
    $(this).toggleClass("opened");

    // イベントトラッキング用
    var category = $(this).attr("class").split(' ')[0];
    var action = 'click_option_close';
    if ($(this).hasClass("opened")) {
      action = 'click_option_open';
    }
    try {
      _gaq.push(['_trackEvent', category, action]);
    }catch(err){}
  });
});

/* 検索オプション グレーアウト */
$(function(){
  $('#targetId').click(function(){
    $('#talentOnly').attr('disabled', 'disabled');
    $('#talentOnlyTxt').css('color', '#ccc');
    $('#notTalent').attr('checked', 'checked');
    $('#targetIdTxt').focus();
    }
  );

  $('#trgtArticle, #trgtTitle').click(function(){
    $('#talentOnly').removeAttr('disabled', 'disabled');
    $('#talentOnlyTxt').css('color', '#333');
    }
  );

  $('#targetIdTxt').click(function(){
    $('#targetId').attr('checked', 'checked');
    $('#talentOnly').attr('disabled', 'disabled');
    $('#talentOnlyTxt').css('color', '#ccc');
    }
  );
  $('#footerTargetId').click(function(){
    $('#footerTalentOnly').attr('disabled', 'disabled');
    $('#footerTalentOnlyTxt').css('color', '#ccc');
    $('#footerNotTalent').attr('checked', 'checked');
    $('#footerTargetIdTxt').focus();
    }
  );

  $('#footerTrgtArticle, #footerTrgtTitle').click(function(){
    $('#footerTalentOnly').removeAttr('disabled', 'disabled');
    $('#footerTalentOnlyTxt').css('color', '#333');
    }
  );

  $('#footerTargetIdTxt').click(function(){
    $('#footerTargetId').attr('checked', 'checked');
    $('#footerTalentOnly').attr('disabled', 'disabled');
    $('#footerTalentOnlyTxt').css('color', '#ccc');
    }
  );
});

/* プロフィール検索　オプションリセット */
$(function(){
  $('.resetBtn').click(function(){
      $(".optionIn :input").each(function() {
        switch (this.type) {
        case "select-one":
        case "text":
            $(this).val("");
            break;
        case "radio":
            this.checked = false;
            break;
        }
      });
      $("#trgtAll, #footerTrgtAll").attr('checked', 'checked');
    }
  );
});

/* amebaIDツールチップ */
$(function(){
  $("body").append(
    '<div id="amebaID">'
    +'<dl>'
    +'<dt>アメーバIDとは？</dt>'
    +'<dd>ブログURLのうしろに書いてあるIDです。このIDを入れるとそのブログの記事がカンタンに検索できるよ！</dd>'
    +'<dd><img src="http://stat100.ameba.jp/search/img/screen/common/thum_amebaid.gif" width="215" height="30" alt=""></dd>'
    +'</dl>'
    +'</div>'
    );
  $("#amebaID").hide();
  $("#amebaIDTxt, #footerAmebaIDTxt").hover(function(){
    $("#amebaID").css({
      "display":"block",
      "top":$(this).offset().top+$(this).height()+"px",
      "left":$(this).offset().left+"px"
    });
    },function(){
    $("#amebaID").hide();
  });
});

/* サムネイル　余白 */
$(function(){
  $("#blogTitle .blogTitleImg img").each(function(){
    var iconHeight = Number($(this).attr("_height"));
    var iconWidth = Number($(this).attr("_width"));
    var imgWidth = (68/iconHeight)*iconWidth;
    var imgHeight = (68/iconWidth)*iconHeight;

    if(iconHeight == iconWidth){
      $(this).width(68);
    }
    else if(iconHeight > iconWidth){
      $(this).height(68);
      $(this).css("margin-left", Math.round((68-imgWidth)/2) +"px");
    }
    else if(iconHeight < iconWidth){
      $(this).width(68);
      $(this).css("margin-top", Math.round((68-imgHeight)/2) +"px");
    }
  });

  $("#profileResult .profileImg img").each(function(){
    $(this).css({
      "margin-top":Math.round(($(this).parent().height()-$(this).height())/2) +"px",
      "margin-left":Math.round(($(this).parent().width()-$(this).width())/2) +"px"
    });
  });
});


/* サムネイル　縦横計84px以下の画像削除、回り込みさせない */
$(window).load(function(){
  $("#blogEntry .entryImg img").each(function(){
    var imgWidth = Number($(this).width());
    var imgHeight = Number($(this).height());

    if(imgWidth + imgHeight < 85){
      $(this).parent().remove();
    }
  /* ブログ記事検索、画像横テキストの幅指定 */
  $(".descriptionArea").each(function(){
    if($(this).next().size() == 1){
    $(this).css("width", 650 - $(this).next().width() -12 + "px");
    }
    });
  });
});

/* 検索結果　hover時にclass="hoverContents"を付与 */
$(function(){
  if($("#profileResult").size() !== 1 ){
    $(".seachResult li").hover(function(){
      $(this).addClass("hoverContents");
    },function(){
      $(this).removeClass("hoverContents");
    });
  }else{
    $(".profileAreaClick").hover(function(){
      $(this).addClass("hoverContents");
      $(this).parent().parent().find(".profileImg").addClass("hoverContents");
    },function(){
      $(this).removeClass("hoverContents");
      $(this).parent().parent().find(".profileImg").removeClass("hoverContents");
    });
    $(".profileImg").hover(function(){
      $(this).addClass("hoverContents");
      $(this).parent().find(".profileAreaClick").addClass("hoverContents");
    },function(){
      $(this).removeClass("hoverContents");
      $(this).parent().find(".profileAreaClick").removeClass("hoverContents");
    });
  }
});

/* 表示件数切替用 */
function searchRowChange(target, author) {
  if ($("[name=target]:radio:checked").length == 0) {
    var targetRadio = $("[name=target][value=" + target + "]:radio");
    if (targetRadio) {
      targetRadio.attr("checked", "checked");
    }
  }
  if ($("[name=author]:radio:checked").length == 0) {
    var authorRadio = $("[name=author][value=" + author + "]:radio");
    if (authorRadio) {
      authorRadio.attr("checked", "checked");
    }
  }
  $("#searchMainForm").submit();
}
function searchRowChangeFooter(target, author) {
  if ($("[name=target]:radio:checked").length == 0) {
    var targetRadio = $("[name=target][value=" + target + "]:radio");
    if (targetRadio) {
      targetRadio.attr("checked", "checked");
    }
  }
  if ($("[name=author]:radio:checked").length == 0) {
    var authorRadio = $("[name=author][value=" + author + "]:radio");
    if (authorRadio) {
      authorRadio.attr("checked", "checked");
    }
  }
  $("#searchFooterForm").submit();
}

/* イベントトラッキング(外部サイトへの遷移) */
function recordOutboundLinkClicked(link, category, action) {
  try {
    _gaq.push(['_trackEvent', category, action]);
    // document.locationで画面遷移するとIEではリファラがなくなるためダミーのformタグを生成/submitして画面遷移する
    // chromeの場合formタグにhiddenでリクエストパラメータを設定せずに画面遷移すると遷移後のURLに?がついてしまうためIE以外はdocument.locationで遷移
    //    http://hoge/fuga/ というURLに遷移した場合 http://hoge/fuga/? となってしまう
    setTimeout(function() {
    	if ($.browser.msie) {
          var url = link.href;
          var formTag = $("<form/>");
          var idx = url.indexOf("?");
          if (idx > -1) {
            var baseUrl = url.substr(0, idx);
            var paramStr = url.substr(idx + 1);
            var params = paramStr.split("&");
            formTag.attr("action", baseUrl);
            for (i = 0; i < params.length; i++) {
              var param = params[i].split("=");
              formTag.append($("<input type='hidden'/>").attr("name", param[0]).attr("value", decodeURIComponent(param[1].replace(/\+/g," "))));
            }
          } else {
             formTag.attr("action", url);
          }
          formTag.appendTo("body");
          formTag.submit();
    	} else {
    		document.location = link.href;
    	}
      },
      100);
  }catch(err){}
}

/* イベントトラッキング(formサブミット) */
function recordFormSubmit(form, category, action) {
  try {
    _gaq.push(['_trackEvent', category, action]);
    setTimeout(function(){form.submit();}, 100);
  }catch(err){}
}

