// httpsに変換するディレクトリの一覧
/* var arr = [ "mypage", "shopping", "entry", "forgot", "contact", "cart" ]; */
var arr = [ "shopping", "entry", "forgot", "contact" ];

/**
 * リンクやアクションのURLをhttpsから始まるURLへ変換する.
 * 
 * @param target 変換するディレクトリ.
 * @param mode 絶対パスか相対パスか.
 */
function httpToHttps(target, mode) {
  switch (mode) {
    case "absolute":
      var basepath = siteurl + target;
      break;
    case "relative":
    default:
      var basepath = urldir + target;
      break;
  }

  // 正規表現の中で変数を使用するため
  re = new RegExp("^" + basepath);

  // <a>タグのhref属性を変換
  $("a[href^='" + basepath + "']").each(function(){
    $(this).attr("href", $(this).attr("href").replace(re, sslurl + target));
  });
  // <form>タグのaction属性を変換
  $("form[action^='" + basepath + "']").each(function(){
    $(this).attr("action", $(this).attr("action").replace(re, sslurl + target));
  });
}

/**
 * httpsでなくともよい相対パスをhttpから始まるURLへ変換する.
 */
function httpRelative() {
  // <a>タグのhref属性を変換
  $("a[href^='" + urldir + "']").each(function(){
    $(this).attr("href").match(/^\/([_a-zA-Z0-9 .]+)\//);
    if (jQuery.inArray(RegExp.$1, arr) == -1) {
      $(this).attr("href", $(this).attr("href").replace(/^\//, siteurl));
    }
  });
  // <form>タグのaction属性を変換
  $("form[action^='" + urldir + "']").each(function(){
    $(this).attr("action").match(/^\/([_a-zA-Z0-9 .]+)\//);
    if (jQuery.inArray(RegExp.$1, arr) == -1) {
      $(this).attr("action", $(this).attr("action").replace(/^\//, siteurl));
    }
  });
}

// プロトコルがhttpsかどうかの判定
if("https:" == document.location.protocol){
  // httpsの場合
  // httpsであるべきところがhttpになっているリンクを変換
  jQuery.each(arr, function(){
    httpToHttps(this, "absolute");
  });
  // httpsでなくともよい相対パスをhttpから始まるURLへ変換
  httpRelative();
}
else {
  // httpの場合
  jQuery.each(arr, function() {
    // httpsであるべき相対リンクを変換
    httpToHttps(this, "relative");
    // httpsであるべきところがhttpになっているリンクを変換
    httpToHttps(this, "absolute");
  });
}
