if ( typeof(BL) == 'undefined') {
	var BL = {};
}

var googletag		= googletag || {};
googletag.cmd		= googletag.cmd || [];

BL.Ads = function()
{
	var _private = {
		static_h:		0,
		static_w:		0,
		dfp_network:	5388645,
		dfp_property:	'ca-pub-6898225050716970',
		ad_slots: 		new Object()
	};

	return {
		setAdSlots: function(_slots) {
			_private.ad_slots = _slots;
		},
		loadAds: function() {
			this.loadGoogleAsync();

			for ( var key in _private.ad_slots) {
				this.addSlot(_private.ad_slots[key]['placement'], _private.ad_slots[key]['size'] , _private.ad_slots[key]['div_id']);
				this.startResizing(_private.ad_slots[key]['div_id'], true); // _private.ad_slots[key]['resize']
			}

			this.enableServices();

			for ( var key in _private.ad_slots) {

				this.displaySlot(_private.ad_slots[key]['div_id']);
			}
		},
		loadGoogleAsync: function() {
			var gads = document.createElement('script');
			gads.async = true;
			gads.type = 'text/javascript';
			var useSSL = 'https:' == document.location.protocol;
			gads.src = (useSSL ? 'https:' : 'http:') + 
			'//www.googletagservices.com/tag/js/gpt.js';
			var node = document.getElementsByTagName('script')[0];
			node.parentNode.insertBefore(gads, node);
		},
		resize: function(_zone, _interval_id, _keep_resizing) {
			obj					= $('#'+ _zone).find('iframe');
			measure_obj 		= obj.contents();

			tmp_h				= parseInt(measure_obj.height());
			_private.static_w	= measure_obj.width();
			body_content		= measure_obj.html();


			//console.log(tmp_h,_private.static_w);

			if (tmp_h > 0) {
				_private.static_h = tmp_h;
			}

			//console.log(body_content);
			if (body_content == '') {
				obj.css('height',0).css('width',0);
				return;
			}

			if (_private.static_h > 0 && _private.static_w > 0) {
				if (_keep_resizing != true)
				{
					//clearInterval(_interval_id);
				}

				obj.css('height',_private.static_h +'px').css('width',_private.static_w +'px');
			}
		},
		startResizing: function(_zone, _keep_resizing) {
			interval_id = setInterval(function(){
				BL.Ads.resize(_zone,interval_id,_keep_resizing);
			},1000);
		},
		reloadAllTheTags: function() {
			if (typeof(googletag.pubads) != 'undefined') {
				googletag.pubads().refresh();
			}
		},
		addSlot: function(_placement, _size, _zone) {
			googletag.cmd.push(function() {
				googletag.defineSlot('/'+ _private.dfp_network +'/'+ _placement, _size, _zone).addService(googletag.pubads());
			});
		},
		displaySlot: function(_zone) {
			googletag.cmd.push(function() {
				googletag.display(_zone);
			});
		},
		enableServices: function() {
			googletag.cmd.push(function() {
				googletag.enableServices();
			});
		}
	};
}();

