/*
    Dependency:
        /js/lib/jquery-1.6.4.min.js
        /js/src/core.js
        {{ MSN_AD_LIB_HTTP }}
 */

if (typeof B2.Common == "undefined"){
	B2.Common = {};
}

B2.Common.Advertise = function() {
	var init = function(){
		B2.Common.OpenX.init();
		B2.Common.MsnAd.init();
	}
	
	return {
		init: init
	}
}();

B2.Common.OpenX = function() {
	var init = function(){
	    //search for zone containers
	    var zoneContainers = $("div[id*='adZone-']");
	    var zoneIds = new Array();

	    if (zoneContainers.length > 0) {
	        //get all the zone ids from the div ids
	        zoneContainers.each(function(e) {
	            zoneIds.push($(zoneContainers[e]).attr("id").substring(7));
	        });
	    }

	    if (zoneIds.length > 0) {
	        var openXServer = "{0}//d1.openx.org/spc.php?zones={1}&source=&r={2}&charset=ISO-8859-1";
	        
	        $.getScript(String.format(openXServer, location.protocol, zoneIds.join("|"), Math.floor(Math.random() * 99999999999)), function() {
	            B2.Logger.log("Openx Script Loaded");

	            $(zoneIds).each(function(e) {
	                B2.Logger.log("Attempting to load Zone Id", zoneIds[e]);
	                var container = $("#adZone-" + zoneIds[e]);
	                if (container.hasClass('ad-loaded')) return;
	                if (typeof (OA_output) != undefined) {
	                    var content = OA_output[zoneIds[e]];
	                    if (content != "")
	                        container.prepend(content);
	                }
	                container.addClass('ad-loaded');
	            });
	        });
	    }
	}
	
	return {
		init: init
	}
}();

B2.Common.MsnAd = function(){
    var init = function() {
        renderAds();
    }
    
    var renderAds = function() {
        if (typeof (dapMgr) != "undefined") {
        	B2.Logger.log("Msn Ad Loading");
            // HTTP Premium Ads
            $.each($("div[id*='httpPremiumAd-']"), function(i, ad) {
                if (!$(ad).hasClass('ad-loaded')) {
                    var id = $(ad).attr('id');
                    var pg = id.split('-')[1];
                    B2.Logger.log("rendering ad.  id=" + id + ", pg=", pg);
                    dapMgr.enableACB(id, false);
                    dapMgr.renderAd(id, "&PG=" + pg + "&AP=1089", 300, 250);
                    $(ad).addClass('ad-loaded');
                }
            });
            // HTTP Standard Ads
            $.each($("div[id*='httpStandardAd-']"), function(i, ad) {
                if (!$(ad).hasClass('ad-loaded')) {
                    var id = $(ad).attr('id');
                    var pg = id.split('-')[1];
                    B2.Logger.log("rendering ad.  id=" + id + ", pg=", pg);
                    dapMgr.enableACB(id, false);
                    dapMgr.renderAd(id, "&PG=" + pg + "&AP=1390", 728, 90);
                    $(ad).addClass('ad-loaded');
                }
            });
        }
    }
    
    return {
    	init: init
    }
}();
