// elmClass = E element Cl ss Style

var focusedECF;
var lastHue;
//var lastColor;
//var isSetHistory = false;




function pickColor( color, hidden) // obj and static is possible
{
	if( ! color || color == 'transparent') {
		return false;
	}

	var colorObj = Color.auto( color)

	// rescue/reset/set hue
	if( colorObj.getHue() === undefined) { // grey
		if( lastHue === undefined) {
			colorObj.setHue( 230); // TODO UNCLEAN
		} else {
			colorObj.setHue( lastHue);
		}
	} else {
		lastHue = colorObj.getHue();
	}

	setECF( focusedECF, colorObj);

	render(); // important to be after the setECF. otherwise it select the wrong colors
	
	
	// write color name
	setMixer( colorObj);
	
	/*
	if( lastColor !== undefined) {
		setHistory( lastColor);
	}
	*/
	if( ! hidden) {
		setHistory( colorObj);
	}
}

function setMixer( colorObj) 
{
	// write color name
	document.getElementById( 'inputHex').value = colorObj.toHex();

	document.getElementById( 'inputR').value = colorObj.getRGB()['R'];
	document.getElementById( 'inputG').value = colorObj.getRGB()['G'];
	document.getElementById( 'inputB').value = colorObj.getRGB()['B'];

	document.getElementById( 'inputH').value = colorObj.getHue();
	document.getElementById( 'inputS').value = colorObj.getSaturation();
	document.getElementById( 'inputL').value = colorObj.getLuminance();

	// ausgelagert
	changeHSLMixer( clone( colorObj));
}

function setHistory( color)
{
	tds = document.getElementById( 'history').getElementsByTagName( 'td');
	
	if( Color.auto( tds[0].style.backgroundColor).toString() != color.toHtml()) {

		for( i = tds.length - 1; i > 0; i--) {
			tds[i].style.backgroundColor = tds[i - 1].style.backgroundColor;
		}

		tds[0].style.backgroundColor = color.toHtml();
	}
}




function deleteECF( ECF, event)
{
	if( ECF != null) {
		var color;
		if( color = Color.auto( ECF.style.backgroundColor)) {
			setHistory( color);
		}
		setECF( ECF, undefined);
		render();
	}
	stopEventBubbling( event);
}


// checks if a color is set
function proofECF( ECF) {
	// pick the color from parent color-class
	if( ! ECF.style.backgroundColor || ECF.style.backgroundColor == 'transparent') {
		// which field
		switch( ECF.getAttribute( 'id')) { // nur für die die auch farblos sein können
			case 'color-0':
				var ECF = document.getElementById( 'text-0');
				break;
			case 'color-1':
				if( document.getElementById( 'color-0').style.backgroundColor) {
					var ECF = document.getElementById( 'color-0');
				} else {
					var ECF = document.getElementById( 'text-0');
				}
				break;
			case 'background-1':
				var ECF = document.getElementById( 'background-0');
				break;
		}
	}
	
	return ECF;
}


function pickECFByDisplay( event)
{
	var id = Compat.getAttribute( this, 'class');
	    id = id.slice( 0, id.search( /\d/) + 1);
	
	var newECF = document.getElementById( id); 
	
	// proof means check if a color is set
	newECF = proofECF( newECF);
	
	pickECF( newECF);
	
	window.display.stopEventBubbling( event);
}

function pickECF( newECF) 
{
	var color = focusECF( newECF);
	
	// set color in mixer
	pickColor( color) // TODO , true);
}


// focus to handle this color
function focusECF( newECF)
{
	// set old field back
	if( focusedECF) {
		focusedECF.style.borderWidth = '1px';
		focusedECF.style.margin     = '6px';
	}

	// set new field
	newECF.style.borderWidth = '5px';
	newECF.style.margin     = '2px';
	//newECF.style.borderStyle = 'outset';
	
	colorECF = proofECF( newECF);
	
	var color = Color.auto( colorECF.style.backgroundColor);
	
	// set the old one for later
	focusedECF = newECF
	
	return color;
}

// only change the color
function setECF( ECF, color)
{
	if( color === undefined) { // delete
		ECF.style.color                = '';
		ECF.style.backgroundColor      = '';
		ECF.firstChild.firstChild.data = ' ';
	} else {
		if( color.isDark()) {
			ECF.style.color             = '#BFBFBF';
		} else {
			ECF.style.color             = '#606060';
		}
		ECF.style.backgroundColor      = color.toHtml()
		ECF.firstChild.firstChild.data = color.toHtml()
	}		
}




function changeHSLMixer( color)
{
	var area = document.getElementById( 'areaColorShades').getElementsByTagName( 'td');

	// vertical
	var sCurve = Array( -0.75, -0.44, -0.15, 0, 0.15, 0.44, 0.75);
	// horizontal
	var lCurve = Array( -0.50, -0.35, -0.2, -0.07, 0, 0.07, 0.2, 0.35, 0.50);

	// field
	var a = 0;
	for( var r = 0; r < sCurve.length; r++) {
		for( var c = 0; c < lCurve.length; c++) {
			area[a++].style.backgroundColor = color.variationRelative(     0, sCurve[r], lCurve[c]).toHtml();
		}
	}


	var area = document.getElementById( 'areaHue').getElementsByTagName( 'td');

	var hCurve = Array( -0.45, -0.31, -0.18, -0.06, 0, 0.06, 0.18, 0.31, 0.45);
	var steps = new Array( 4, 1);

	// hue
	var a = 0;
	for( var r = 0; r < steps.length; r++) {
		for( var c = 0; c < hCurve.length; c++) {
			area[a++].style.backgroundColor = color.variation( hCurve[c] / steps[r], 0, 0, true).toHtml();
		}
	}

	// assure that luminance has not a extreme value
	if( color.getLuminance( true) < 0.2) {
		color.setLuminance( 0.2, true);
	} else if( color.getLuminance( true) > 0.8) {
		color.setLuminance( 0.8, true);
	}

	// assure that saturation has not a extreme value
	if( color.getSaturation( true) < 0.2) {
		color.setSaturation( 0.2, true);
	} else if( color.getSaturation( true) > 0.8) {
		color.setSaturation( 0.8, true);
	}

	// thin hue
	for( var c = 0; c < hCurve.length; c++) {
		area[a++].style.backgroundColor = color.variation( hCurve[c], 0, 0, true).toHtml();
	}
	
	/*
	var cols       = 9
	var rows       = 3;
	               
	var cSteps     = cols - 1;
	var rSteps     = rows - 1;
	
	var cWidth     = 1 / cols;
	var rWidth     = 1 / rows;

	var cStepWidth = 1 / cSteps;
	var rStepWidth = 1 / rSteps;
	
	
	var balance = -Math.floor(cols / 2);
	

	var area1 = document.getElementById( 'areaColor').getElementsByTagName( 'td')

	var a = 0;
	for( var r = 0; r < rows; r++) {
		var b = balance;
		
		var rSpecial = cols / (r + 1) / cols;
		
		//Bug.dump( rFactor);
		
		for( var c = 0; c < cols; c++) {
			var elm = area1[a++];

			var cB = c + balance;
			
			var vColor = clone( color);
			
			vColor.variateHue( b * (cWidth - (cWidth * (r / rows))) * rSpecial, true);
			//vColor.variateSaturation( sCurve[r], true); // makes the color
			vColor.variateSaturation( 1, true); // makes the color
			vColor.variateLuminance( (0.5 - vColor.getLuminance( true)) * ((rSteps - r) / rSteps) / 3, true); // mitteln

			var HTMLColor = vColor.toHtml(); 

			elm.style.backgroundColor = HTMLColor;
			//elm.setAttribute( 'title',  rStepWidth * (rSteps - r) / 4);
			
			b++;
		} 
	} 
	*/

}

function renderCss( colorSet) {
	var css;
	css =  "/*\r\n";
	css += Color.auto( colorSet.color[1]) + " Color 2 (Logo or other special things)\r\n";
	css += Color.auto( colorSet.color[0]) + " Color (Headlines, graphical elements)\r\n";
	css += Color.auto( colorSet.text[0]) + " Text\r\n";
	css += Color.auto( colorSet.background[0]) + " Background\r\n";
	css += Color.auto( colorSet.background[1]) + " Background 2 (special textboxes, sidebars)\r\n";
	css += "*/\r\n";
	css += "\r\n";
	css += "body {\r\n";
	css += "	color: " + Color.auto( colorSet.text[0]) + ";\r\n";
	css += "	background-color: " + Color.auto( colorSet.background[0]) + ";\r\n";
	css += "}\r\n";
	css += "\r\n";
	css += "h1, h2, h3, h4, h5, h6, .color {\r\n";
	css += "	color: " + Color.auto( colorSet.color[0]) + ";\r\n";
	css += "}\r\n";
	css += "\r\n";
	css += ".color2 {\r\n";
	css += "	background-color: " + Color.auto( colorSet.color[1]) + ";\r\n";
	css += "}\r\n";
	css += "\r\n";
	css += ".background2 {\r\n";
	css += "	background-color: " + Color.auto( colorSet.background[1]) + ";\r\n";
	css += "}\r\n";
	css += "\r\n";

	document.getElementById( 'cssCode').value = css;
}


function render()
{
	var fields = document.getElementById( 'grid').getElementsByTagName( 'td')
	
	var colorSet = new Object;
	colorSet.background = new Array(2);
	colorSet.text       = new Array(1);
	colorSet.color      = new Array(2);

	var backupBackground = new Color( 'white');
	var backupForeground = new Color( 'darkgray');
	              
	colorSet.background[0] = Color.auto( document.getElementById('background-0' ).style.backgroundColor) || backupBackground; //( ! document.getElementById('background-0' ).style.backgroundColor ? backupBackground : document.getElementById('background-0').style.backgroundColor);
	colorSet.text[0]       = Color.auto( document.getElementById('text-0'       ).style.backgroundColor) || backupForeground; // : document.getElementById('text-0'      ).style.backgroundColor);
	                                                                                
   
	backupBackground = colorSet.background[0];                                                             
	backupForeground = colorSet.text[0];                                                         
	                                                                                                                                   
	colorSet.background[1] = Color.auto( document.getElementById('background-1' ).style.backgroundColor) || backupBackground; //? backupBackground : document.getElementById('background-1').style.backgroundColor);
	colorSet.color[0]      = Color.auto( document.getElementById('color-0'      ).style.backgroundColor) || backupForeground; //? backupForeground : document.getElementById('color-0'     ).style.backgroundColor); 
	                                                                                
   
	backupForeground = colorSet.color[0];                                                   
	                                                                                
	colorSet.color[1]      = Color.auto( document.getElementById('color-1'      ).style.backgroundColor) || backupForeground; // : document.getElementById('color-1'     ).style.backgroundColor);
	

	
	window.display.RenderTemplate( colorSet);
	renderCss( colorSet);

	renderURL();
}

// original style http://colors.flo.local/?text[0]=696969&color[0]=0051C1&color[1]=36C100&background[0]=FFFFFF&background[1]=D6C2C5&template=blog
// new            http://colors.flo.local/?t0=353535&c0=C1AA00&c1=36C100&b0=C2D3D6&b1=D6C2D6&t=bar
function renderURL()
{
	var URL = 'http://' + window.location.host + '?';
	
	// because the normal set includes the duplets for child-styles
	for( name in renderURL.names) {
		for( var i = 0; i < renderURL.names[name]; i++) {
			var c = document.getElementById( name + '-' + i).style.backgroundColor;
			
			var color;
			if( c && (color = Color.auto( c))) {
				URL += name.charAt( 0) + i + '=' + color.toHex() + '&';
			}
		}
	}
	
	URL += 't=' + document.getElementById( 'template').value;
	
	document.getElementById( 'URLLink').setAttribute( 'href', URL);
	document.getElementById( 'URLInput').value = URL;
	
	Framework.changeUri( URL);
}

renderURL.names = {
	'text'       : 1,
	'color'      : 2,
	'background' : 2
	};
	
	
	
function init() 
{
	var startField = document.getElementById( 'color-0');
	
	if( ( ! startField.style.backgroundColor) || startField.style.backgroundColor == 'transparent') {
		startField = document.getElementById( 'text-0');
	}
	
	pickECF( startField); // includes pickColor
}




function inputHex( v) 
{
	if( ! (color = Color.auto( v))) {
		cleanHex = v.replace( /[^0-9a-f]/i, '');
	
		if( cleanHex.length < 6) {
			cleanHex = cleanHex.charAt( 0) + cleanHex.charAt( 0) + cleanHex.charAt( 1) + cleanHex.charAt( 1) + cleanHex.charAt( 2) + cleanHex.charAt( 2)
		}
	
		cleanHex = '#' + cleanHex;
		
		color = Color.hex( cleanHex)
	}
	
	if( color instanceof Color) {
		pickColor( color);
	} else {
	}
}

function inputRGB() 
{
	var values = new Array( 3)

	values[0] = document.getElementById( 'inputR').value;
	values[1] = document.getElementById( 'inputG').value;
	values[2] = document.getElementById( 'inputB').value;

	for( var i = 0; i < values.length; i++) {
		values[i] = parseFloat( values[i]);

		if( values[i] == NaN) {
			values[i] = 0;
		}
	}
	
	color = Color.RGB( values[0], values[1], values[2]);
	
	pickColor( color);
}

function inputHSL() 
{
	var values = new Array( 3)
	
	values[0] = document.getElementById( 'inputH').value;
	values[1] = document.getElementById( 'inputS').value;
	values[2] = document.getElementById( 'inputL').value;

	for( var i = 0; i < values.length; i++) {
		values[i] = parseFloat( values[i]);

		if( values[i] == NaN) {
			values[i] = 0;
		}
	}
		
	color = Color.HSL( values[0], values[1], values[2]);
	
	pickColor( color);
}

function blinkArea( id)
{
	Anime.blink( document.getElementById( id), { 'color':'#545454'});
}

/*
                                   
function drag( elm) {
	window.event.dataTransfer.setData( 'color', elm.style.backgroundColor);
	window.event.dataTransfer.effectAllowed = 'copy';                 
}

function dropIntoECF( ECF) {
	window.event.returnValue = false;                           
	window.event.dataTransfer.dropEffect = 'copy';
	              
	var colorObj = Color.auto( window.event.dataTransfer.getData( 'color'));

	setECF( ECF, colorObj)
	renderDisplay();
}

function showDragCursor() {
	window.event.returnValue = false;	
	window.event.dataTransfer.dropEffect = 'copy';
}


*/
