So how did it happen? There are two main factors. The first is that Federer cleaned up at ATP 500 events, securing 1500 points with three victories at such events while Djokovic has only contended two such events with poor showings. The second is that Djokovic chose not to defend his title at the Serbia Open after his grandfather died. The easy 250 points from winning that event would have kept Federer stuck at number two even if he wins Wimbledon.
But the biggest factor was the Madrid Masters. The switch to heavily salted blue clay help big servers and hitter and harmed players who move well. Federer won the event while Djokovic crashed out in the QFs.
What would have happened if the Madrid Masters was played on red clay?
We can take a pretty good guess. In all of the other 2012 major clay court tournaments Djokovic met Nadal in the final and lost. At the 2011 edition of the Madrid Masters, Djokovic defeated Nadal at the final. Looking at it this way it seems like a good bet Djokovic would have met Nadal and won with between 0% and 25% chance. I call this the counterfactual case.
Another way to look at it is to consider the past three champions at Madrid prior to 2012: Djokovic, Nadal and Federer. Since each won the event once in the past three years it'd be fair to say they all had equal chances of winning. If there were the case just throwing out the Madrid 2012 results would give an unbiased guess at what the rankings would have looked like.
The table below shows how the rankings would have looked in either case, conditional on Federer winning on Sunday:
A lot of things had to go right for Federer to regain number one. He had to play well at lower tier events. Djokovic's grandfather had to die. But the most important thing was the Blue Clay debacle.