/*
 * This script is included when the FrontControllerCustomizer implements getSifrFlashUrl().
 * It will convert all header elements with sifr by using the styles specified in the CSS.
 * 
 * @author Paul Middelkoop
 */

Ext.namespace('nl', 'nl.caiw', 'nl.caiw.toolbox', 'nl.caiw.toolbox.cms');

nl.caiw.toolbox.cms.Sifr = {
	init: function(flashUrl) {
		this.flashUrl = flashUrl;
	},

	replace: function() {
		var flash = {src: this.flashUrl};
		sIFR.prefetch(flash);
		sIFR.activate(flash);
		
		for (var heading = 1; heading <= 6; heading++) {	
			$$('h' + heading).each(function(element) {
				var color = this.getColor(element);			
				var textTransform = this.getStyle(element, 'textTransform');
				var fontSize = this.getStyle(element, 'fontSize');
				
				var css = '.sIFR-root {color: ' + color + '; padding: 0px; z-index: 1; text-transform: ' + textTransform + '; font-size: ' + fontSize + ';';
				var letterSpacing = this.getLetterSpacing(element);			
				if (letterSpacing) {
					css += 'letter-spacing: ' + letterSpacing + ';';
				}
				css += '}';
	
				sIFR.replace(flash, {
					elements: [element],
					wmode: 'transparent', 
					fitExactly:'true',
					css: css
				})
			}.bind(this));
		}
	},
		
	// private methods
	getStyle: function (element, style) {
		return Ext.isIE ?
			element.currentStyle[style] :
			window.getComputedStyle(element, null)[style];
	},

	getColor: function(element) {
		var color = this.getStyle(element, 'color');
		
		if (color.toLowerCase().startsWith('rgb')) {
			var redEnd = color.indexOf(',');
			var red = color.substring(4, redEnd);
			var greenEnd = color.indexOf(',', redEnd + 1);
			var green = color.substring(redEnd + 1, greenEnd);
			var blue = color.substring(greenEnd + 1, color.length - 1);  
			color = '#' + this.RGBtoHex(red, green, blue);
		}
		
		return color;		
	},

	getLetterSpacing: function(element) {
		var letterSpacing = this.getStyle(element, 'letterSpacing');
		
		return letterSpacing == 'normal' ? null : letterSpacing.replace('px', '');   
	},

	// got convert functions from http://www.linuxtopia.org/online_books/javascript_guides/javascript_faq/rgbtohex.htm
	RGBtoHex: function(R,G,B) {
		return this.toHex(R) + this.toHex(G) + this.toHex(B);
	},

	toHex: function(N) {
	 	if (N == null) { 
	 		return "00";
	 	}
	 	
	 	N = parseInt(N); 
	 	if (N == 0 || isNaN(N)) { 
	 		return "00";
	 	}
	 	
	 	N=Math.max(0,N); 
	 	N=Math.min(N, 255); 
	 	N=Math.round(N);
	 	
	 	return "0123456789ABCDEF".charAt((N - N % 16) / 16)
	      + "0123456789ABCDEF".charAt(N % 16);
	}	
};
