// B2 common functions 
// Norkay AB 2008

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };



















/**
 * A class to parse color values
 * @author Stoyan Stefanov <sstoo@gmail.com>
 * @link   http://www.phpied.com/rgb-color-parser-in-javascript/
 * @license Use it if you like it
 */
function RGBColor(color_string)
{
    this.ok = false;

    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();

    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            example: ['#00ff00', '336699'],
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            example: ['#fb0', 'f0f'],
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }

    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }

}


































if( !B2 ) var B2 = new Object();

B2.BitmapTextReplacer = new Object();
							
B2.BitmapTextReplacer.AnyErrors = false;

B2.BitmapTextReplacer.GetCombinedStyle = function( el, cssproperty, csspropertyNS )
{								
	//	return el.currentStyle[cssproperty]	;
	if (el.currentStyle) 
	{	
		//if IE5+
		return el.currentStyle[cssproperty]	;
	}
	else if (window.getComputedStyle)
	{
		//if NS6+
		var elstyle = window.getComputedStyle(el, "");
		return elstyle.getPropertyValue(csspropertyNS);
	}
	return undefined;
}					

B2.BitmapTextReplacer.isUpperCase = false;			  
	
B2.BitmapTextReplacer.GetBaseURL = function( el )
{
	var siz = B2.BitmapTextReplacer.GetCombinedStyle( el, 'fontSize', 'font-size' );
	var fam = B2.BitmapTextReplacer.GetCombinedStyle( el, 'fontFamily', 'font-family' );
	var col = new RGBColor( B2.BitmapTextReplacer.GetCombinedStyle( el, 'color', 'color' ) ); 
	var bac = new RGBColor( B2.BitmapTextReplacer.GetCombinedStyle( el, 'backgroundColor', 'background-color' ) );
	var wei = B2.BitmapTextReplacer.GetCombinedStyle( el, 'fontWeight', 'font-weight' ).toString();				   
	var sty = B2.BitmapTextReplacer.GetCombinedStyle( el, 'fontStyle', 'font-style' ).toString();	   		   
	var tra = B2.BitmapTextReplacer.GetCombinedStyle( el, 'textTransform', 'text-transform' ).toString();	

	// alert( "wei="+wei );
	siz = parseInt( siz.replace(/[ptxcm]*/g, '' ) );
	
	if( siz < 2 )
		B2.BitmapTextReplacer.AnyErrors = true;
		
	var fams = fam.split(',');
	var firstfam = fams[0];	   
	
//	alert('>>'+firstfam+'<<');
	
	var famre = new RegExp( "/^([\\s\\\"\\\' ]*)([\\W\\w@]*)([\\s\\\"\\\' ]*)$/" );
	
	firstfam = firstfam.replace(famre, '$2');	
	firstfam = firstfam.replace(famre, '$2');
	
	var famre2 = new RegExp( "/\\\"\\\'/g" );	
	firstfam = firstfam.replace(famre2, '');	
	
///	alert( "firstfam="+firstfam );

//	alert('>>'+firstfam+'<<');

	if( firstfam == "" )
		B2.BitmapTextReplacer.AnyErrors = true;
	
	var baseurl = '';
						   
	B2.BitmapTextReplacer.isUpperCase = (tra == 'uppercase');
		
	baseurl += '/B2.Graphics.RenderText.ashx?s='+escape(siz)+'&f='+escape(firstfam);
	
	if( wei == 'bold' || wei == 'bolder' || wei == '700' )
		baseurl += '&b=1';
		
	if( sty == 'italic' )
		baseurl += '&i=1';
		
	if( col.ok )
		baseurl += '&fg='+escape(col.toHex());
	else
		B2.BitmapTextReplacer.AnyErrors = true;
		
	if( bac.ok )	
		baseurl += '&bg='+escape(bac.toHex());
				
	return baseurl;
}
				
B2.BitmapTextReplacer.GetWordURL = function( el, wurd )
{	
	var baseurl = B2.BitmapTextReplacer.GetBaseURL ( el );						 
	if( B2.BitmapTextReplacer.isUpperCase == true )
		wurd = wurd.toUpperCase();
	baseurl += '&t='+encodeURIComponent(wurd);		
	return baseurl;
}
			 
B2.BitmapTextReplacer._ParseNested = function( root, parent, el )
{
	var newcontent = '';
	
	if( el.nodeType == 3 )
	{						  
		var baseurl = B2.BitmapTextReplacer.GetBaseURL( parent );				
		var words = el.nodeValue;		
		if( words != '' )
		{
			words = words.replace( '\n', '\n ' );
			words = words.split(' ');
			for( var i=0; i<words.length; i++ )
			{
				if( i > 0 )
					newcontent += ' ';
				var word = words[i].trim();
				if( word != '' )
				{						  					 
					if( B2.BitmapTextReplacer.isUpperCase == true )
						word = word.toUpperCase();
					var url = baseurl + '&t='+encodeURIComponent(word);
					newcontent += '<img src=\"'+url+'\" class=\"word\" align=\"absbottom\" />';
				}
			}
		}
	}
	else
	{
		newcontent += '<'+el.nodeName+' ';
							   
		for( var j=0; j<el.attributes.length; j++ )
		{
			newcontent += el.attributes[j].name+'=\"'+el.attributes[j].value+'\" ';
		}

		if( el.childNodes.length > 0 )
		{
			newcontent += '>';	
			for( var j=0; j<el.childNodes.length; j++ )
			{
				var child = el.childNodes[j];
				
				var childcontent = B2.BitmapTextReplacer._ParseNested( root, el, child );
				
				newcontent += childcontent; 
			}
			newcontent += '</'+el.nodeName+'>';
		}
		else
		{
			newcontent += '/>';
		}		  
	}

	return newcontent;		   
}
	
B2.BitmapTextReplacer.ReplaceSingleElement = function( el )
{							
	B2.BitmapTextReplacer.AnyErrors = false;

	var oldsize = B2.BitmapTextReplacer.GetCombinedStyle( el, 'fontSize', 'font-size' );
	
	var cur = el;
	var newcontent = '';
	for( var j=0; j<el.childNodes.length; j++ )
	{
		var child = el.childNodes[j];
		var childcontent = B2.BitmapTextReplacer._ParseNested( cur, cur, child );
		newcontent += childcontent; 
	}
	newcontent += '<br/>';
	
	if( !B2.BitmapTextReplacer.AnyErrors )
	{	
		// skapa diven
		var newel = document.createElement( el.tagName );
		//	newel.className = el.tagName.toLower();
		//	newel.style.fontSize = oldsize;
		newel.innerHTML = newcontent;
	
		// inserta diven ovanför titeln
		var parentel = el.parentNode;
		parentel.insertBefore( newel, el );	
	
		// göm gamla rubriken
		el.style.display = 'none'; 
	}
}
		
B2.BitmapTextReplacer.ReplaceByID = function( id )
{
	var el = document.getElementById( id );
	if( el )
		B2.BitmapTextReplacer.ReplaceSingleElement( el );
}

B2.BitmapTextReplacer.ReplaceByTag = function( tag )
{
	var tagged = document.getElementsByTagName( tag )
	for( var j=0; j<tagged.length; j++ )
			B2.BitmapTextReplacer.ReplaceSingleElement( tagged[j] );		
}
	 		
B2.BitmapTextReplacer.ReplaceWith = function( id, repdata )
{
	var el = document.getElementById( id );
	if( el )
	{
		B2.BitmapTextReplacer.AnyErrors = false;

		var oldsize = B2.BitmapTextReplacer.GetCombinedStyle( el, 'fontSize', 'font-size' );
		
		var cur = el;
		var newcontent = '';
		for( var j=0; j<repdata.length; j++ )
		{				
			if( repdata[j].img )
				newcontent += '<img src=\"'+repdata[j].img+'\" class=\"word\" align=\"absbottom\" /> ';

			if( repdata[j].raw )
				newcontent += repdata[j].raw;
		}
		newcontent += '<br/>';
		
		if( !B2.BitmapTextReplacer.AnyErrors )
		{	
			// skapa diven
			var newel = document.createElement( el.tagName );
			//	newel.className = el.tagName.toLower();
			//	newel.style.fontSize = oldsize;
			newel.innerHTML = newcontent;
		
			// inserta diven ovanför titeln
			var parentel = el.parentNode;
			parentel.insertBefore( newel, el );	
		
			// göm gamla rubriken
			el.style.display = 'none'; 
		}
		
		
		
	}
}


