(function($){
	var ids=[];
	var urls=[];
	var nodes=[];
	var widths=[];
	var heights=[];
	var last=0;
	var rnd;
	var init=false;
	var settings={};
	$.fn.adRefresh = function(options){
		settings = $.extend({}, $.fn.adRefresh.defaults, options);
		var r=settings.adBase.replace(/\./g,'\\.');
		r= new RegExp(r);
		rnd=Math.round(Math.random()*1000000000000);
		$(this).each(function(){
			var found=false;
			var curr=this;
			$('script',this).each(function(){
				if($(this).attr('src')!==undefined && $(this).attr('src').match(r) && !found){
					found=true;
					var src=$(this).attr('src');
					widths[last]=src.replace(/^.*sz=(\d+)x\d+;.*$/,'$1');
					heights[last]=src.replace(/.*sz=\d+x(\d+);.*$/,'$1');
					src=src.replace(/;ord/,'!category=noexpand;ord');
					src=src.replace(/ord=[^;\/]+/,'ord=ORD_VALUE');
					urls[last]=src;
					nodes[last]=curr;
				}
			});
			if(found){
				var id='adRefresh_'+last+'_'+Math.floor(10000*Math.random());
				ids[last]=id;
				
				last++;
			}
		});
		return this.adRefresh;
	};
	$.fn.adRefresh.initIframes = function(){
		for(var i=0;i<ids.length;i++){
			var w='';
			var h='';
			if(widths[i]>0){
				w='width="'+widths[i]+'"';
			}
			if(heights[i]>0){
				h='height="'+heights[i]+'"';
			}
			$(nodes[i]).html('<iframe id="'+ids[i]+'" '+w+' '+h+' scrolling="no" frameborder="0" src="'+($.fn.adRefresh.getAdURL(i))+'"></iframe>');
		}
	};
	$.fn.adRefresh.refreshAll = function(){
		rnd=Math.round(Math.random()*1000000000000);
		if(!init){
			$.fn.adRefresh.initIframes();
			init=true;
			return;
		}
		if(window.pageTracker!==undefined && window.pageTracker._trackPageview !==undefined && typeof(window.pageTracker._trackPageview) == 'function'){
			pageTracker._trackPageview('/vp'+window.location.pathname);
		}
		for(var i=0;i<ids.length;i++){
			$('#'+ids[i]).attr('src',$.fn.adRefresh.getAdURL(i));
		}
	};
	$.fn.adRefresh.getAdURL = function(id){
		return settings.iframeHTML+'?i='+escape(urls[id].replace(/ORD_VALUE/,rnd));
	};

	$.fn.adRefresh.defaults = {
		adBase: 'iv.doubleclick.net',
		iframeHTML: '/php/adframe.php'
	};
})(jQuery);