﻿jQuery(function($){
  var flight = false;
  if(location.hostname == "jatns.tokyo-airport-bldg.co.jp"){
    flight = true;
  }
  var official_site_url = "";
  if(flight){
    $("link").each(
      function(){
        if($(this).attr("rel") == "home"){
          official_site_url = $(this).attr("href");
          official_site_url = official_site_url.slice(0, official_site_url.length - 1);
        }
      }
    );
  }
  if(0 < $("div.ad_agency").size()){
    $.get("/advertisement/config.tsv", function(data) {
      var advertisement_data = data.split(String.fromCharCode(13) + String.fromCharCode(10));
      var tmp; var target_path; var target; var i=0;
      $("div.ad_agency").prepend("<ul/>");
      for(var i = 0; i < advertisement_data.length; i++){
        if(advertisement_data[i] != ""){
          var tmp = advertisement_data[i].split(String.fromCharCode(9));
          var display_page;
          if(flight){
            display_page = tmp[3];
            exclude_page = tmp[4];
          }else{
            display_page = tmp[1];
            exclude_page = tmp[2];
          }
          var target_path = display_page.split(",");
          var target_regex_tmp = new Array();
          for(var j = 0; j < target_path.length; j++){
            target_regex_tmp.push("^" + target_path[j].replace("*", ".*", "g") + "$");
          }
          var target_regex_match = new RegExp(target_regex_tmp.join("|"));
          target_path = exclude_page.split(",");
          target_regex_tmp = new Array();
          for(var j = 0; j < target_path.length; j++){
            target_regex_tmp.push("^" + target_path[j].replace("*", ".*", "g") + "$");
          }
          var target_regex_not_match = new RegExp(target_regex_tmp.join("|"));
          if(target_regex_match.test(location.pathname) && !target_regex_not_match.test(location.pathname)){
            var link_url = tmp[5];
            if(!tmp[5].match(/^https?:\/\//)){
                link_url = official_site_url + link_url;
            }
            $("div.ad_agency ul").append($("<li/>").append($("<a/>").append($("<img/>").attr("src", official_site_url + tmp[6]).attr("alt", tmp[7]).attr("width", tmp[8]).attr("height", tmp[9])).attr("href", link_url)));
          }
        }
      }
    });
  }
});
