// Ad Generationの広告枠を作成するJavaScriptタグを生成します。
function makeADGTag(adid , divid, width, height){
    console.log("divid:" + divid);
    var adg = document.getElementById(divid);
    var script = document.createElement('script');
    script.type = 'text/javascript';
    
    console.log("adg:" + adg);
    
    // async=trueにすることによって非同期に対応されます
    if (width == null || height == null) {
        script.src ='https://i.socdm.com/sdk/js/adg-script-loader.js?id=' + adid + '&adType=SP&displayid=0&targetID=adg_' + divid + '&async=true';
    } else {
        script.src ='https://i.socdm.com/sdk/js/adg-script-loader.js?id=' + adid + '&adType=FREE&width='+ width +'&height='+ height +'&displayid=0&targetID=adgAd_' + divid + '&async=true';
    }
    
    if(adg != null){
        adg.appendChild(script);
    }else{
        console.log("adg is null");
    };
    adg.style.display = 'none';
    var count = 0;
    var timer = setInterval(function checkAd(){
        count++;
        if(count > 100){
            clearInterval(timer);
            return;
        }
        if(checkADGTag(adg) === true){
            clearInterval(timer);
            adg.style.display = 'inline';
        }
    },100);
}
 
// aタグを探す
function checkADGTag(obj){
    console.log("ad object:" + obj);
    
    var links = obj.getElementsByTagName('a');
    var frms = obj.getElementsByTagName('iframe');
    if(links.length > 0){
        makeADGLink(links);
        return true;
    }
 
    var res = false;
    for(var i = 0; i < frms.length; i++){
        if(checkADGTag(frms[i].contentWindow.document) === true){
            res = true
        }
    }
    return res;
}

var adHref;
var aDiv

// aタグを置換する
function makeADGLink(arr){
    for(var i = 0; i < arr.length; i++){
        (function(a) {
            adHref = a.href;
            a.href = '#';
            a.onclick = function(){
                var ref = window.open(adHref, '_system');
                return false;
            }
            aDiv = a;
        })(arr[i]);
    }
}