//v1 if there are too few ads, they are not repeated 
//v2 if there are too few ads, they get repeated

gfeedfetcher.prototype.last_feed_is_ad=function(separation)
{
	this.feedadposition   = this.feedlabels.length-1;
	this.feedadseparation = (separation? separation:2);
	
	gfeedfetcher.prototype.last_object = this;
}

gfeedfetcher._sortarray=
function(old_sortarray)
{ 
	return function(a,b) 
	{ var r,label4ads,o,i,ind_ad,inserted,all_ads_inserted;
		var ad_feeds=[],all_feeds=[],final_feeds=[];
 	 		  
		r=old_sortarray(a,b);
		
		if (gfeedfetcher.prototype.last_object) //there are ads
		{ 		 
			o=gfeedfetcher.prototype.last_object;
			label4ads=o.feedlabels[ o.feedadposition ];
		 										
			for (i=0; i<o.feeds.length; i++) //pop ads from the array
			{				
				if ( o.feeds[i].ddlabel == label4ads)	{	 ad_feeds.push(o.feeds[i]);}
				else                                 	{	all_feeds.push(o.feeds[i]);}
			}							
					
			final_feeds=[];
			inserted=0;
			all_ads_inserted=false;
			ind_ad=0;
			for (i=0 ; i<all_feeds.length ; i++) //mixing ads
			{
				inserted++; 
				final_feeds.push(all_feeds[i]);
				if ((inserted==o.feedadseparation) && !(all_ads_inserted && (i==(all_feeds.length-1))))
				{	                                      // if cycle is already done, not necessary to add an ad at the very end when data is already finish
					inserted=0; 
					final_feeds.push(ad_feeds[ind_ad]);
					ind_ad = (ind_ad + 1) % ad_feeds.length;
					if (ind_ad===0) {all_ads_inserted=true;} //cycle completed, all ads have been inserted at least once
					  
				}	
			}
			if (all_ads_inserted==false)
			{
				for (;ind_ad < ad_feeds.length ; ind_ad++)
				{	   
					final_feeds.push(ad_feeds[ind_ad]); //rest of ads to be added to the list: grouped at the end.
				}
			}
						
			for (i=0 ; i<final_feeds.length ; i++)	//final copy to destination
			{
				o.feeds[i]=final_feeds[i];	//es un error pretender cambiar o.feeds, hay que atacar el contenido
			}
							
		}
		//else{	alert("no ads here, ok");	}						
								
		return r;
	}
}(gfeedfetcher._sortarray);

