/* 

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

*/

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

$.fontResize = {
  
  callbacks:[],
  
  doResize:function(){
    
    var newFontSize = this.iframe.height();
    
    if (newFontSize != this.fontsize){//only callback if font size has changed
      
      for(var i = 0; i<this.callbacks.length; i++){
        
        this.callbacks[i](newFontSize/20); //call each callback and pass the fontsize (divide by 100 cause its 100ems)
      }
      
    }
    
    this.fontsize = newFontSize;
    
  },
  
  init:function(){
    
    this.iframe = $('<iframe></iframe>').css({width:"20em", height:"20em", position:"absolute", left:"-100em", top:"-100em", backgroundColor:'red'}); //build the iframe
    $("body").append(this.iframe);
    
    this.fontsize = this.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(){
        $.fontResize.doResize();
      }, 100);
    }
    //attach events using DOM (for some reason jquerys resize() was erroring in ffox and safari)
    this.iframe.get(0).onresize = handleResize; //for IE6
    if(this.iframe.get(0).contentWindow) this.iframe.get(0).contentWindow.onresize = handleResize; //for other browsers
    
  }
  
}

