var autoTextAreaFix=true;

var font_inc_set = [ 72, 48, 36, 24, 18 ];
var line_inc_factor = 1.2;
  
var tickerSpeed = 50;

var deviceRefreshRate=60;
if ( "getDeviceRefreshRate" in document.documentElement )
  deviceRefreshRate=document.documentElement.getDeviceRefreshRate();
  
var devicePixelSize = 1;
var tickerCTM=document.documentElement.getDeviceCTM();
if ( tickerCTM.getComponent(1)==0 )
	devicePixelSize = tickerCTM.getComponent(0);
else if ( tickerCTM.getComponent(0)==0 )
	devicePixelSize = tickerCTM.getComponent(1);

function resizeTextAreaById( id, maxInc ) {
	autoTextAreaFix=false;
	textArea = document.getElementById( id );
    if ( textArea ) 
        return resizeTextArea( textArea, maxInc );
}
function resizeTextArea( textArea, maxInc ) {
  
    var max_line_inc = maxInc || 0;
    
    textBBox=textArea.getBBox();
    if ( textBBox==null )
        return false;
    viewBox = textBBox;
    
    if ( max_line_inc==0 ) {
        max_line_inc = textArea.getAttribute( 'line-increment' );
        if ( max_line_inc=="" ) {
            max_line_inc = textArea.getAttribute( 'font-size' );
            if ( max_line_inc!="" )
                max_line_inc *= line_inc_factor;
            else
                max_line_inc = font_inc_set[0];
        }
    }
    var font_factor = 1/line_inc_factor;
    var font_size = max_line_inc*font_factor;
    var line_inc = max_line_inc;

    textArea.setAttribute( 'font-size', font_size );
    textArea.setAttribute( 'line-increment', line_inc );
    textArea.setAttribute( "height", "auto" );
    
    textBBox=textArea.getBBox();
    //alert( 'bbox: x='+textBBox.x+' y='+textBBox.y+' w='+textBBox.width+' h='+textBBox.height +' < '+viewBox.height);
      
    if ( textBBox.height+textBBox.y < viewBox.height ){
        textArea.setAttribute( "height", viewBox.height );
        return false; // we are fine
    }
        
    var nbLines = Math.ceil( (textBBox.height+textBBox.y)/line_inc );
    var newNbLines = Math.floor( nbLines*Math.sqrt( viewBox.height/(nbLines*line_inc) ) );
      
      // find the font size
    var idx = 0;
    for ( idx=0; idx<font_inc_set.length-1; idx++ ){
        if ( font_inc_set[idx]<line_inc && font_inc_set[idx]*(newNbLines-1+font_factor)<=viewBox.height ) // we assume that the first line is of the font size
            break;
    }

    while ( true ) {
        font_size = font_inc_set[idx]*font_factor;
        line_inc = font_inc_set[idx];
        textArea.setAttribute( 'font-size', font_size );
        textArea.setAttribute( 'line-increment', line_inc );
        textBBox=textArea.getBBox();
        //alert( 'w='+textBBox.width+' h='+ (textBBox.height+2*textBBox.y) + ' < '+viewBox.height + ' lines='+Math.ceil( (textBBox.height+textBBox.y)/line_inc)+' line_inc='+line_inc );
        if ( textBBox.height+2*textBBox.y > viewBox.height && (idx<font_inc_set.length) ){
          idx++;
        }else
          break;
    }
    textArea.setAttribute( "height", viewBox.height );
    return true;
}

function tickerTextAreaById( id ) {
	autoTextAreaFix=false;
	textArea = document.getElementById( id );
    if ( textArea ) 
        return tickerTextArea( textArea );
}
function tickerTextArea( textArea ) {
	
	var tickerViewBox=textArea.getBBox();
    if ( tickerViewBox==null )
        return false;
	
	textArea.setAttribute( "width", "auto" );
	var textBBox=textArea.getBBox();
	if ( textBBox==null ){
        textArea.setAttribute( "width", tickerViewBox.width );
        return false;
	}
	if ( textBBox.width<=tickerViewBox.width ){
        textArea.setAttribute( "width", tickerViewBox.width );
		return false; // nothing to do it fits.
    }
		
	var textDistance=0;
	textDistance = textBBox.x+textBBox.width;
	//textDistance *= 1.03;
	
	//var crawlDistance = tickerViewBox.width+textDistance;
	var crawlDistance = textDistance-(tickerViewBox.width+tickerViewBox.x); // we start with the text on the left and end with it on the right
	var pixelsPerRefresh = Math.ceil(tickerSpeed/deviceRefreshRate*devicePixelSize);
	var unitsPerSecond = pixelsPerRefresh*deviceRefreshRate/devicePixelSize;
	var dur=crawlDistance/unitsPerSecond;
	if ( dur < 2 )
		dur = Math.ceil(2/dur)*dur;
	if ( dur > 10 )
		dur = dur/Math.ceil(dur/10);
	//alert( tickerViewBox.width+tickerViewBox.x + " " + textDistance + " " + dur + " " + crawlDistance/dur);
	var animText=document.createElementNS( 'http://www.w3.org/2000/svg', 'animateTransform' );
	animText.setAttribute( 'attributeName', 'transform' );
	animText.setAttribute( 'type', 'translate' );
	animText.setAttribute( 'begin', "indefinite" );
	animText.setAttribute( 'additive', 'sum' );
    animText.setAttribute( 'values', '0,0;0,0;-'+crawlDistance+',0;-'+crawlDistance+',0' );
	animText.setAttribute( 'keyTimes', '0,0.15,0.95,1' );
	animText.setAttribute( 'repeatDur', 'indefinite' );
    animText.setAttribute( 'dur', dur*1.25 );
	
	textArea.appendChild( animText );
	
	var g=document.createElementNS( 'http://www.w3.org/2000/svg', 'g' );
	textArea.parentNode.insertBefore(g, textArea);
	g.appendChild(textArea);
	g.setAttribute("transform", textArea.getAttribute("transform") );
	textArea.setAttribute("transform", "");
	
	var clip=document.createElementNS( 'http://www.w3.org/2000/svg', 'clipPath' );
	var id = textArea.id+"Clip";
	clip.setAttribute( 'id', id );
	var rect=document.createElementNS( 'http://www.w3.org/2000/svg', 'rect' );
	rect.setAttribute( 'x', '0' );
	rect.setAttribute( 'y', '0' );
	rect.setAttribute( 'width', tickerViewBox.width );
	rect.setAttribute( 'height', tickerViewBox.height );
	clip.appendChild( rect );
	g.appendChild( clip );
	g.setAttribute( 'clip-path', 'url(#'+id+')' );
	
	animText.beginElement();
    return true;
    
}

// this function when called, will make sure that all text area under a given node
// are fully visible.
// if the textArea has an height, then the resizeTextAreaById is used
// if the textArea has no height, then the tickerTextAreaById is used
function fixAllTextArea( node ) {
	node_int = node || document.documentElement;
	var toFix = new Array();
	var i=0;
    for ( var ch = node_int.firstChild; ch!=null; ch = ch.nextSibling ) {
        if ( ch.localName=='textArea' ) {
			toFix[i++] = ch;
        }
		if ( ch.localName=='g' )
			fixAllTextArea( ch );
    }
	for ( i in toFix ){
		var el = toFix[i];
		var h = el.getAttribute("height");
		var w = el.getAttribute("width");
        var c = el.getAttribute("class");
        
		if ( w!="auto" && w!="" && c.indexOf("autotextbox")==-1 ){
			var fixed = false;
			if ( h=="auto" || h=="" ) {				
				fixed = tickerTextArea( el ) ;
                //alert("Fixing textArea "+el.id +" using ticker (node="+node_int.id+") fixed="+fixed) ;
			} else {
				fixed = resizeTextArea( el );
                //alert("Fixing textArea "+el.id +" using resize (node="+node_int.id+") fixed="+fixed) ;
			} 
            if (fixed)
                el.setAttribute( "class", "autotextbox" ); // make sure we don't process a textArea twice.            
		}
	}
}

document.documentElement.addEventListener( "load", function(){
	// on load function, normally the script should be in there...	
	if ( autoTextAreaFix )
		fixAllTextArea();
}, false );