/* 

jQuery resize detector

Todo
  - Safari appears to not recognise the difference between the 2 smallest font sizes, the 20em iframe stays the same size for both

*/

jQuery.fontResize = {
  
  callbacks:[],
  
  doResize:function(force){
    
    var newFontSize = jQuery.fontResize.iframe.height();
    
    if (newFontSize != jQuery.fontResize.fontsize || force == true){//only callback if font size has changed
      
      for(var i = 0; i<jQuery.fontResize.callbacks.length; i++){
        
        jQuery.fontResize.callbacks[i](newFontSize/20); //call each callback and pass the fontsize (divide by 100 cause its 100ems)
      }
      
    }
    
    jQuery.fontResize.fontsize = newFontSize;
    
  },
  
  init:function(){
    
    jQuery.fontResize.iframe = jQuery('<iframe></iframe>').css({width:"20em", height:"20em", position:"absolute", left:"-100em", top:"-100em", backgroundColor:'red'}); //build the iframe
    jQuery("body").append(jQuery.fontResize.iframe);
    
    jQuery.fontResize.fontsize = jQuery.fontResize.iframe.height();
    
    var resizeTimeout;
    
    var handleResize = function(){//use a short timeout since some browsers fire resize the entire time the font size is scaling
      if (resizeTimeout) clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(function(){
        jQuery.fontResize.doResize();
      }, 50);
    }
    //attach events using DOM (for some reason jquerys resize() was erroring in ffox and safari)
    jQuery.fontResize.iframe.get(0).onresize = handleResize; //for IE6
    if(jQuery.fontResize.iframe.get(0).contentWindow) jQuery.fontResize.iframe.get(0).contentWindow.onresize = handleResize; //for other browsers
    
  }
  
}

jQuery.fn.fontResize = function(callback){
  
  if (!jQuery.fontResize.iframe) jQuery.fontResize.init(); //make sure the iframe exists
  
  if(callback) jQuery.fontResize.callbacks.push(callback);
  
  return this;
  
}
