/*
 * This script gets Google ad tags from ads.xml and calls GA_googleAddSlot on each.
 */

// Get the domain and split it up to determine if we're at the base site or 
// inside one of the BS products. Expects urls w/ subdomains: forum.site.com,
// realestate.site.com, site.com. This is why < 3 and domainArray[0] are used too.
domainArray = document.domain.split(".");
function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}
if(domainArray.length < 3 || domainArray[0] == 'www' || domainArray[1] == 'wpengine') {
	domainName = 'root';
	url = "/wp-content/themes/blankslate/xml/ads.xml";
} else {
	domainName = domainArray[0];	
	url = getBaseURL() + "ad-proxy.php";
}

$.ajax({
	type: "GET",
	url:  url,
	dataType: "xml",
	async: false,
	success: 
		function(data) {
		    adNames = new Object();
			pubId = $(data).find("PubId").text();
			adUnits = $(data).find('Domain[name="' + domainName + '"]').children('AdUnits');
			adUnits.children().each(function() {
				GA_googleAddSlot(pubId, $(this).text());
				adNames[$(this).attr('name')] = $(this).text();
			});
		}
});
GA_googleFetchAds();
