// Génération dynamique de dégradé css
var gradientInit = false;
var gradientHistory = {
	done: [],
	undone: []
};

// Mise en place
$(document).ready(function() {
						   
	// Couleurs de début et de fin
	$('#start-color').addColorOptions('start', {value:'aaeeff'});
	$('#end-color').addColorOptions('end', {value:'3399cc'});
	
	// Ecouteurs
	$(this).find('#direction input').click(updateCSS);
	$('input[type=text]').live('focus', function() {
							 
		$(this).bind('keyup', function() {
			$(this).checkInputValue();
		});
		
	}).live('blur', function() {
		
	 	$(this).unbind('keyup');
		
	});
	$('input[name^="bg-"], input[name^="extended-"], #comments').click(updateCSS);
	$('#bg-size, #class-name').change(updateCSS);
	
	// Hauteur du fond plafonnée à 800	 pour limiter la charge serveur
	$('#bg-size').change(function() {
		$(this).val(Math.min(800	, Math.max(1, parseInt($(this).val()))));
	});
	
	// Sélecteur Opera
	if ($.browser.opera && $.browser.version >= 9.5) {
		$(document.body).addClass('opera');
	}
	
	// Appel initial
	if (document.location.hash.length > 0)
	{
		buildFromHash(document.location.hash.substring(1));
	}
	else
	{
		gradientInit = true;
		updateCSS();
	}
	
	// Styles pour IE
	if ($.browser.msie)
	{
		$('.block p:last-child').addClass('last-child');
	}
});

// Mise à jour après un changement de langue
function onChangeLocale()
{
	updateCSS();
}

// Vérifie la valeur des champs de texte
$.fn.checkInputValue = function()
{
	var input = $(this);
	var value = input.val();
	if (input.hasClass('type100'))
	{
		value = value.replace(/[^0-9]+/gi, '');
		if (value.length > 0)
		{
			value = Math.min(100, Math.max(0, parseFloat(value)));
		}
		input.val(value);
	}
	else if (input.hasClass('type255'))
	{
		value = value.replace(/[^0-9]+/gi, '');
		if (value.length > 0)
		{
			value = Math.min(255, Math.max(0, parseInt(value)));
		}
		input.val(value);
	}
	else if (input.hasClass('typeHex'))
	{
		input.val(value.replace(/[^0-9a-f]+/gi, ''));
	}
}

// Ajoute un nouveau bloc de couleur
$.fn.addColorAfter = function(options)
{
	settings = $.extend({
		position: 			50
	}, options);
	
	// Bloc de référence
	var block = $(this);
	if (block.get(0).nodeName.toLowerCase() != 'div')
	{
		block = block.parents('div:first');
	}
	
	// Ajout du bloc
	var newBlock = block.after('<div id="new-color" class="block color-block new-color">'+
						'<h3>-</h3>'+
						'<p class="color-position"><label for="new-position" class="lang-position">'+getLocaleText('position')+'</label> <input type="text" name="new-position" id="new-position" value="'+settings.position+'" class="type100" /> %</p>'+
						'<a href="#" onclick="$(this).removeColor(); return false;" title="'+getLocaleText('Remove-this-color')+'" class="remove-color lang-Remove-this-color">'+getLocaleText('Remove-this-color')+'</a>'+
						'<a href="#" onclick="$(this).addColorAfter(); return false;" title="'+getLocaleText('Add-color-here')+'" class="add-color lang-Add-color">'+getLocaleText('Add-color')+'</a>'+
					'</div>').next();
	newBlock.addColorOptions('new', options);
	
	// Réorganisation
	$('.color-block').not(':first, :last').reorderSteps();
	
	// Mise à jour
	updateCSS();
	
	return $('.new-color').removeClass('new-color');
}

// Supprime le bloc de couleur
$.fn.removeColor = function()
{
	// Bloc de référence
	var block = $(this);
	if (block.get(0).nodeName.toLowerCase() != 'div')
	{
		block = block.parents('div:first');
	}
	
	block.remove();
	updateCSS();
}

// Insertion du contenu d'un bloc couleur
$.fn.addColorOptions = function(name, options)
{
	settings = $.extend({
		type:		 		'hex',
		value: 				'FFFFFF'
	}, options);
	
	// Type actif
	var typeHex = (settings.type == 'hex') ? ' checked="checked"' : '';
	var typeName = (settings.type == 'name') ? ' checked="checked"' : '';
	var typeRGBA = (settings.type == 'rgba') ? ' checked="checked"' : '';
	
	// Valeur
	var hexValue = 'FFFFFF';
	var nameValue = '';
	var rgbaValue = {r:255, g:255, b:255, a:100};
	if (settings.type == 'hex')
	{
		hexValue = settings.value;
	}
	if (settings.type == 'name')
	{
		nameValue = settings.value;
	}
	if (settings.type == 'rgba')
	{
		var valueParts = settings.value.toString().split(',');
		rgbaValue.r = valueParts[0] ? valueParts[0] : 255;
		rgbaValue.g = valueParts[1] ? valueParts[1] : 255;
		rgbaValue.b = valueParts[2] ? valueParts[2] : 255;
		rgbaValue.a = valueParts[3] ? valueParts[3] : 100;
	}
	
	// Composition
	var code = '<p class="tags-list clearfix">'+
				'<span><input type="radio" name="'+name+'-type" id="'+name+'-type-hex" value="hex"'+typeHex+' /> <label for="'+name+'-type-hex" class="lang-Hex">'+getLocaleText('Hex')+'</label></span>'+
				'<span><input type="radio" name="'+name+'-type" id="'+name+'-type-name" value="name"'+typeName+' /> <label for="'+name+'-type-name" class="lang-Named">'+getLocaleText('Named')+'</label></span>'+
				'<span><input type="radio" name="'+name+'-type" id="'+name+'-type-rgba" value="rgba"'+typeRGBA+' /> <label for="'+name+'-type-rgba">RGBA</label></span>'+
			'</p>'+
			'<p id="'+name+'-type-hex-options" class="color-value">'+
				'#<input type="text" name="'+name+'-type-hex-value" id="'+name+'-type-hex-value" value="'+hexValue+'" size="10" maxlength="6" class="typeHex" />'+
				'&nbsp; (<span class="lang-ie">'+getLocaleText('ie')+'</span> : #3399cc)'+
			'</p>'+
			'<p id="'+name+'-type-name-options" class="color-value">'+
				'<select name="'+name+'-type-name-value" id="'+name+'-type-name-value" style="width: 100%;">';
				
				var active;
				for (var color in namedColors)
				{
					active = (nameValue == color) ? ' selected="selected"' : '';
					code += '<option value="'+color+'" style="color: #'+namedColors[color]+'"'+active+'>██ '+color+'</option>';
				}
				
			code += '</select>'+
			'</p>'+
			'<p id="'+name+'-type-rgba-options" class="color-value">'+
				'<label for="'+name+'-type-rgba-r">R</label> '+
				'<input type="text" name="'+name+'-type-rgba-r" id="'+name+'-type-rgba-r" value="'+rgbaValue.r+'" maxlength="3" class="mini-input type255" /> '+
				'<label for="'+name+'-type-rgba-g">G</label> '+
				'<input type="text" name="'+name+'-type-rgba-g" id="'+name+'-type-rgba-g" value="'+rgbaValue.g+'" maxlength="3" class="mini-input type255" /> '+
				'<label for="'+name+'-type-rgba-b">B</label> '+
				'<input type="text" name="'+name+'-type-rgba-b" id="'+name+'-type-rgba-b" value="'+rgbaValue.b+'" maxlength="3" class="mini-input type255" /> '+
				'<label for="'+name+'-type-rgba-a">A</label> '+
				'<input type="text" name="'+name+'-type-rgba-a" id="'+name+'-type-rgba-a" value="'+rgbaValue.a+'" maxlength="3" class="mini-input type100" />'+
			'</p>';
	$(this).children('h3').after(code);
	
	// Mise en place
	$(this).find('input[type=radio]').click(function() { this.checked = true; $(this).showTypeOptions(); }).eq(0).showTypeOptions();
	$(this).find('input[type=text], select').change(updateCSS);
}

// Comportement à la sélection d'un type
$.fn.showTypeOptions = function()
{
	// Show options
	$(this).parents('p:first').find('input[type=radio]').each(function(i) {
		if (this.checked)
		{
			$('#'+this.id+'-options').show();
		}
		else
		{
			$('#'+this.id+'-options').hide();
		}
	});
	
	updateCSS();
}

// Applique des paramètres de couleur à un bloc
$.fn.applyColor = function(options)
{
	settings = $.extend({
		type:		 		'hex',
		value: 				'FFFFFF',
		position: 			50
	}, options);
	
	// Type et position
	$(this).find('input[id$="-type-'+settings.type+'"]').click();
	$(this).find('input[id$="-position"]').val(settings.position);
	
	// Valeur
	if (settings.type == 'hex')
	{
		$(this).find('input[id$="-type-hex-value"]').val(settings.value);
	}
	if (settings.type == 'name')
	{
		$(this).find('select[id$="-type-name-value"]').val(settings.value);
	}
	if (settings.type == 'rgba')
	{
		var valueParts = settings.value.toString().split(',');
		$(this).find('input[id$="-type-rgba-r"]').val(valueParts[0] ? valueParts[0] : 255);
		$(this).find('input[id$="-type-rgba-g"]').val(valueParts[1] ? valueParts[1] : 255);
		$(this).find('input[id$="-type-rgba-b"]').val(valueParts[2] ? valueParts[2] : 255);
		$(this).find('input[id$="-type-rgba-a"]').val(valueParts[3] ? valueParts[3] : 100);
	}
}

// Liste des couleurs nommées
var namedColors =  {
	aliceblue: 'F0F8FF',
	antiquewhite: 'FAEBD7',
	aqua: '00FFFF',
	aquamarine: '7FFFD4',
	azure: 'F0FFFF',
	beige: 'F5F5DC',
	bisque: 'FFE4C4',
	black: '000000',
	blanchedalmond: 'FFEBCD',
	blue: '0000FF',
	blueviolet: '8A2BE2',
	brown: 'A52A2A',
	burlywood: 'DEB887',
	cadetblue: '5F9EA0',
	chartreuse: '7FFF00',
	chocolate: 'D2691E',
	coral: 'FF7F50',
	cornflowerblue: '6495ED',
	cornsilk: 'FFF8DC',
	crimson: 'DC143C',
	cyan: '00FFFF',
	darkblue: '00008B',
	darkcyan: '008B8B',
	darkgoldenrod: 'B8860B',
	darkgray: 'A9A9A9',
	darkgreen: '006400',
	darkkhaki: 'BDB76B',
	darkmagenta: '8B008B',
	darkolivegreen: '556B2F',
	darkorange: 'FF8C00',
	darkorchid: '9932CC',
	darkred: '8B0000',
	darksalmon: 'E9967A',
	darkseagreen: '8FBC8F',
	darkslateblue: '483D8B',
	darkslategray: '2F4F4F',
	darkturquoise: '00CED1',
	darkviolet: '9400D3',
	deeppink: 'FF1493',
	deepskyblue: '00BFFF',
	dimgray: '696969',
	dodgerblue: '1E90FF',
	firebrick: 'B22222',
	floralwhite: 'FFFAF0',
	forestgreen: '228B22',
	fuchsia: 'FF00FF',
	gainsboro: 'DCDCDC',
	ghostwhite: 'F8F8FF',
	gold: 'FFD700',
	goldenrod: 'DAA520',
	gray: '808080',
	green: '008000',
	greenyellow: 'ADFF2F',
	honeydew: 'F0FFF0',
	hotpink: 'FF69B4',
	indianred: 'CD5C5C',
	indigo: '4B0082',
	ivory: 'FFFFF0',
	khaki: 'F0E68C',
	lavender: 'E6E6FA',
	lavenderblush: 'FFF0F5',
	lawngreen: '7CFC00',
	lemonchiffon: 'FFFACD',
	lightblue: 'ADD8E6',
	lightcoral: 'F08080',
	lightcyan: 'E0FFFF',
	lightgoldenrodyellow: 'FAFAD2',
	lightgreen: '90EE90',
	lightgrey: 'D3D3D3',
	lightpink: 'FFB6C1',
	lightsalmon: 'FFA07A',
	lightseagreen: '20B2AA',
	lightskyblue: '87CEFA',
	lightslategray: '778899',
	lightsteelblue: 'B0C4DE',
	lightyellow: 'FFFFE0',
	lime: '00FF00',
	limegreen: '32CD32',
	linen: 'FAF0E6',
	magenta: 'FF00FF',
	maroon: '800000',
	mediumaquamarine: '66CDAA',
	mediumblue: '0000CD',
	mediumorchid: 'BA55D3',
	mediumpurple: '9370DB',
	mediumseagreen: '3CB371',
	mediumslateblue: '7B68EE',
	mediumspringgreen: '00FA9A',
	mediumturquoise: '48D1CC',
	mediumvioletred: 'C71585',
	midnightblue: '191970',
	mintcream: 'F5FFFA',
	mistyrose: 'FFE4E1',
	moccasin: 'FFE4B5',
	navajowhite: 'FFDEAD',
	navy: '000080',
	oldlace: 'FDF5E6',
	olive: '808000',
	olivedrab: '6B8E23',
	orange: 'FFA500',
	orangered: 'FF4500',
	orchid: 'DA70D6',
	palegoldenrod: 'EEE8AA',
	palegreen: '98FB98',
	paleturquoise: 'AFEEEE',
	palevioletred: 'DB7093',
	papayawhip: 'FFEFD5',
	peachpuff: 'FFDAB9',
	peru: 'CD853F',
	pink: 'FFC0CB',
	plum: 'DDA0DD',
	powderblue: 'B0E0E6',
	purple: '800080',
	red: 'FF0000',
	rosybrown: 'BC8F8F',
	royalblue: '4169E1',
	saddlebrown: '8B4513',
	salmon: 'FA8072',
	sandybrown: 'F4A460',
	seagreen: '2E8B57',
	seashell: 'FFF5EE',
	sienna: 'A0522D',
	silver: 'C0C0C0',
	skyblue: '87CEEB',
	slateblue: '6A5ACD',
	slategray: '708090',
	snow: 'FFFAFA',
	springgreen: '00FF7F',
	steelblue: '4682B4',
	tan: 'D2B48C',
	teal: '008080',
	thistle: 'D8BFD8',
	tomato: 'FF6347',
	turquoise: '40E0D0',
	violet: 'EE82EE',
	wheat: 'F5DEB3',
	white: 'FFFFFF',
	whitesmoke: 'F5F5F5',
	yellow: 'FFFF00',
	yellowgreen: '9ACD32'
};

// Réorganisation des étapes intermédiaires
$.fn.reorderSteps = function()
{
	// On renomme les radios pour éviter les interférences
	$(this).find('input[type=radio]').each(function(i) {
	
		this.id = 'temp'+i+this.id.substring(this.id.indexOf('-'));
		this.name = 'temp'+i+this.name.substring(this.name.indexOf('-'));
	
	});
	
	// Réorganisation
	$(this).each(function(i) {
		
		var block = $(this);
		var step = i+1;
		block.children('h3').html('<span class="lang-Step">'+getLocaleText('Step')+'</span> '+step);
		this.id = 'step'+step+this.id.substring(this.id.indexOf('-'));
		
		// Renommage
		block.find('input, select').each(function() { 
			
			this.id = 'step'+step+this.id.substring(this.id.indexOf('-'));
			this.name = 'step'+step+this.name.substring(this.name.indexOf('-'));
			
		});
		block.find('label').each(function() {
			$(this).attr('for', 'step'+step+$(this).attr('for').substring($(this).attr('for').indexOf('-')));
		});
		block.find('p[id$="-options"]').each(function() {
			this.id = 'step'+step+this.id.substring(this.id.indexOf('-'));
		});
		
	});
}

// Met en place un dégradé à partir d'une chaîne
function buildFromHash(hash)
{
	// Préparation
	gradientInit = false;
	
	// Récupération
	var options = {};
	var hashParts = hash.split('&');
	var optionParts;
	for (var i = 0; i < hashParts.length; ++i)
	{
		optionParts = hashParts[i].split('=');
		if (optionParts[1] && optionParts[1].length > 0)
		{
			options[optionParts[0]] = optionParts[1];
		}
	}
	hashParams = $.extend({
		startType:		 	'hex',
		startValue: 		'FFFFFF',
		endType:		 	'hex',
		endValue: 			'000000',
		direction: 			'bottom',
		bgColor:			'auto',
		alignv:				'top',
		alignh:				'left',
		size:				200,
		className:			'.gradient',
		comments:			1,
		extOpera:			0,
		extIE:				0
	}, options);
	
	// Nettoyage
	$('.color-block').not(':first, :last').remove();
	
	// Direction
	$('#direction-'+hashParams.direction).click();
	
	// Couleur de fond et alignement
	$('#bg-color-'+hashParams.bgColor).click();
	$('#bg-alignv-'+hashParams.alignv).click();
	$('#bg-alignh-'+hashParams.alignh).click();
	$('#bg-size').val(hashParams.size);
	
	// Nom de classe
	$('#class-name').val(hashParams.className);
	$('#comments').attr('checked', (hashParams.comments == 1));
	
	// Compatibilité Opera/IE
	$('#extended-opera-'+hashParams.extOpera).click();
	$('#extended-ie-'+hashParams.extIE).click();
	
	// Couleur de début
	$('#start-color').applyColor({
		type: hashParams.startType,
		value: hashParams.startValue
	});
	
	// Couleur de fin
	$('#end-color').applyColor({
		type: hashParams.endType,
		value: hashParams.endValue
	});
	
	// Couleurs intermédiaires
	var step = 1;
	var lastBlock = $('#start-color');
	while (hashParams['step'+step+'Type'] != undefined)
	{
		lastBlock = lastBlock.addColorAfter({
			type: hashParams['step'+step+'Type'],
			value: hashParams['step'+step+'Value'] ? hashParams['step'+step+'Value'] : 'FFFFFF',
			position: hashParams['step'+step+'Position'] ? hashParams['step'+step+'Position'] : 50
		});
		
		// Etape suivante
		++step;
	}
	
	// Mise à jour
	gradientInit = true;
	updateCSS();
}

// Génère le code CSS
function updateCSS()
{
	// Si en cours d'initialisation
	if (!gradientInit)
	{
		return;	
	}
	
	// Récupération
	var direction = $('input[name="direction"]:checked').val();
	var startColor = getColor('start', 'FFFFFF');
	var endColor = getColor('end', 'FFFFFF');
	var stepsFF = '';
	var stepsWebkit = '';
	var hash = [];
	var hasAlpha = false;
	
	// Correspondance des directions
	var dirFF = 'top';
	var dirWebkit = 'left top, left bottom';
	var dirIE = '0';
	var repeat;
	var align;
	switch (direction)
	{
		case 'bottom-right':
			dirFF = 'left top';
			dirWebkit = 'left top, right bottom';
			hash.push('direction=bottom-right');
			$('#alignv').show();
			$('#alignh').hide();
			repeat = 'x';
			align = $('input[id^="bg-alignv-"]:checked').val();
			if (align != 'top')
			{
				hash.push('alignv='+align);
			}
			break;
		
		case 'right':
			dirFF = 'left';
			dirWebkit = 'left top, right top';
			dirIE = '1';
			hash.push('direction=right');
			$('#alignv').hide();
			$('#alignh').show();
			repeat = 'y';
			align = $('input[id^="bg-alignh-"]:checked').val();
			if (align != 'left')
			{
				hash.push('alignh='+align);
			}
			break;
		
		case 'top-right':
			dirFF = 'left bottom';
			dirWebkit = 'left bottom, right top';
			dirIE = '1';
			hash.push('direction=top-right');
			$('#alignv').hide();
			$('#alignh').show();
			repeat = 'y';
			align = $('input[id^="bg-alignh-"]:checked').val();
			if (align != 'left')
			{
				hash.push('alignh='+align);
			}
			break;
		
		default:
			$('#alignv').show();
			$('#alignh').hide();
			repeat = 'x';
			align = $('input[id^="bg-alignv-"]:checked').val();
			if (align != 'top')
			{
				hash.push('alignv='+align);
			}
			break;
	}
	
	// Couleur de début
	hash.push('startType='+startColor.type);
	hash.push('startValue='+convertColorForHash(startColor.color));
	if (startColor.alpha < 100)
	{
		hasAlpha = true;
	}
	
	// Couleur de fin
	hash.push('endType='+endColor.type);
	hash.push('endValue='+convertColorForHash(endColor.color));
	if (endColor.alpha < 100)
	{
		hasAlpha = true;
	}
	
	// Couleurs intermédiaires
	var step = 1;
	var stepColor;
	while (stepColor = getColor('step'+step, 'FFFFFF'))
	{
		// Ajout
		stepsFF += stepColor.color+' '+stepColor.position+'%,'+"\n"+'		';
		stepsWebkit += ','+"\n"+'		color-stop('+(stepColor.position/100)+', '+stepColor.color+')';
		if (stepColor.alpha < 100)
		{
			hasAlpha = true;
		}
		
		// Hash
		hash.push('step'+step+'Type='+stepColor.type);
		hash.push('step'+step+'Value='+convertColorForHash(stepColor.color));
		hash.push('step'+step+'Position='+stepColor.position);
		
		// Etape suivante
		++step;
	}
	
	// Couleur de fond
	var bgColor = $('input[name="bg-color"]:checked').val();
	var bgColorValue = '#FFFFFF';
	var bgColorValueOld = bgColorValue;
	switch (bgColor)
	{
		case 'trans':
			bgColorValue = '';
			bgColorValueOld = '';
			hash.push('bgColor=trans');
			break;
		
		case 'start':
			bgColorValue = startColor.color;
			bgColorValueOld = startColor.colorOld;
			hash.push('bgColor=start');
			break;
		
		case 'end':
			bgColorValue = endColor.color;
			bgColorValueOld = endColor.colorOld;
			hash.push('bgColor=end');
			break;
		
		default:
			if (hasAlpha)
			{
				bgColorValue = '';
				bgColorValueOld = '';
			}
			else if (direction == 'bottom' || direction == 'bottom-right')
			{
				if (align != 'bottom')
				{
					bgColorValue = endColor.color;
					bgColorValueOld = endColor.colorOld;
				}
				else
				{
					bgColorValue = startColor.color;
					bgColorValueOld = startColor.colorOld;
				}
			}
			else
			{
				if (align != 'right')
				{
					bgColorValue = endColor.color;
					bgColorValueOld = endColor.colorOld;
				}
				else
				{
					bgColorValue = startColor.color;
					bgColorValueOld = startColor.colorOld;
				}	
			}
			break;
	}
	var bgColorValueAlone = bgColorValueOld;
	if (bgColorValue.length > 0)
	{
		bgColorValue = bgColorValue+' ';
	}
	if (bgColorValueOld.length > 0)
	{
		bgColorValueOld = bgColorValueOld+' ';
	}
	if (bgColorValueAlone.length == 0)
	{
		bgColorValueAlone = 'none';
	}
	
	// Taille
	var size = parseInt($('#bg-size').val());
	if (size != 200)
	{
		hash.push('size='+size);
	}
	
	// Compatibilité Opera/IE
	var extOpera = $('input[name="extended-opera"]:checked').val();
	if (extOpera != 0)
	{
		hash.push('extOpera='+extOpera);
		$('#svg-link').parent().show();
	}
	else
	{
		$('#svg-link').parent().hide();
	}
	var extIE = $('input[name="extended-ie"]:checked').val();
	if (extIE != 0)
	{
		hash.push('extIE='+extIE);
	}
	
	// Nom de classe et options
	var className = $('#class-name').val();
	if (className != '.gradient')
	{
		hash.push('className='+className);
	}
	
	// Commentaires
	if ($('#comments').attr('checked'))
	{
		var addTab = (extOpera == 0) ? '' : '		';
		var commentLegacy = '	/* '+getLocaleText('Legacy-browsers')+' */'+"\n";
		var commentRecent = addTab+'	/* '+getLocaleText('Recent-browsers')+' */'+"\n";
		var commentIE = '	/* Internet Explorer */'+"\n";
		var commentOpera = addTab+'	/* Opera */'+"\n";
	}
	else
	{
		hash.push('comments=0');
		var commentLegacy = '';
		var commentRecent = '';
		var commentIE = '';
		var commentOpera = '';
	}
	
	// Hash final
	var finalHash = hash.join('&');
	var fileName = className.replace(/[^a-z0-9\-_]+/gi, '-').replace(/^-/, '');
	
	// Timestamp
	var date = new Date();
	var timestamp = date.getMilliseconds();
	
	// Composition
	if (extOpera == 0 && extIE == 0)
	{
		var code = '#selector# {'+"\n"+
		commentLegacy+
		'	background: '+bgColorValueOld+'url("'+fileName+'-bg.png") repeat-'+repeat+' '+align+';'+"\n"+
		'	-o-background-size: 100% 100%;'+"\n"+
		'	-moz-background-size: 100% 100%;'+"\n"+
		'	-webkit-background-size: 100% 100%;'+"\n"+
		'	background-size: 100% 100%;'+"\n"+
		commentRecent+
		'	background: -webkit-gradient('+"\n"+
		'		linear,'+"\n"+
		'		'+dirWebkit+','+"\n"+
		'		from('+startColor.color+'),'+"\n"+
		'		to('+endColor.color+')'+stepsWebkit+"\n"+
		'	);'+"\n"+
		'	background: -webkit-linear-gradient('+"\n"+
		'		'+dirFF+','+"\n"+
		'		'+startColor.color+','+"\n"+
		'		'+stepsFF+endColor.color+''+"\n"+
		'	);'+"\n"+
		'	background: -moz-linear-gradient('+"\n"+
		'		'+dirFF+','+"\n"+
		'		'+startColor.color+','+"\n"+
		'		'+stepsFF+endColor.color+''+"\n"+
		'	);'+"\n"+
		'	background: -o-linear-gradient('+"\n"+
		'		'+dirFF+','+"\n"+
		'		'+startColor.color+','+"\n"+
		'		'+stepsFF+endColor.color+''+"\n"+
		'	);'+"\n"+
		'	background: linear-gradient('+"\n"+
		'		'+dirFF+','+"\n"+
		'		'+startColor.color+','+"\n"+
		'		'+stepsFF+endColor.color+''+"\n"+
		'	);'+"\n"+
		'}';
	}
	else if (extOpera == 0)
	{
		// Type de fond pour IE
		if (step > 1)
		{
			bgIE = 'filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+fileName+'-bg.png", sizingMethod="scale");';
		}
		else
		{
			bgIE = 'filter: progid:DXImageTransform.Microsoft.gradient(gradientType='+dirIE+', startColorstr='+startColor.colorIE+', endColorstr='+endColor.colorIE+');';
		}
		
		var code = '#selector# {'+"\n"+
		commentLegacy+
		'	background: '+bgColorValueOld+'url("'+fileName+'-bg.png") repeat-'+repeat+' '+align+';'+"\n"+
		'	-o-background-size: 100% 100%;'+"\n"+
		'	-moz-background-size: 100% 100%;'+"\n"+
		'	-webkit-background-size: 100% 100%;'+"\n"+
		'	background-size: 100% 100%;'+"\n"+
		commentIE+
		'	*background: '+bgColorValueAlone+';'+"\n"+
		'	background: '+bgColorValueAlone+'\\0/;'+"\n"+
		'	'+bgIE+"\n"+
		commentRecent+
		'	background-image: -webkit-gradient('+"\n"+
		'		linear,'+"\n"+
		'		'+dirWebkit+','+"\n"+
		'		from('+startColor.color+'),'+"\n"+
		'		to('+endColor.color+')'+stepsWebkit+"\n"+
		'	);'+"\n"+
		'	background-image: -webkit-linear-gradient('+"\n"+
		'		'+dirFF+','+"\n"+
		'		'+startColor.color+','+"\n"+
		'		'+stepsFF+endColor.color+''+"\n"+
		'	);'+"\n"+
		'	background-image: -moz-linear-gradient('+"\n"+
		'		'+dirFF+','+"\n"+
		'		'+startColor.color+','+"\n"+
		'		'+stepsFF+endColor.color+''+"\n"+
		'	);'+"\n"+
		'	background-image: -o-linear-gradient('+"\n"+
		'		'+dirFF+','+"\n"+
		'		'+startColor.color+','+"\n"+
		'		'+stepsFF+endColor.color+''+"\n"+
		'	);'+"\n"+
		'	background-image: linear-gradient('+"\n"+
		'		'+dirFF+','+"\n"+
		'		'+startColor.color+','+"\n"+
		'		'+stepsFF+endColor.color+''+"\n"+
		'	);'+"\n"+
		'}';
	}
	else
	{
		var code = '#selector# {'+"\n"+
		commentLegacy+
		'	background: '+bgColorValueOld+'url("'+fileName+'-bg.png") repeat-'+repeat+' '+align+';'+"\n"+
		'	-o-background-size: 100% 100%;'+"\n"+
		'	-moz-background-size: 100% 100%;'+"\n"+
		'	-webkit-background-size: 100% 100%;'+"\n"+
		'	background-size: 100% 100%;'+"\n";
		
		if (extIE == 1)
		{
			// Type de fond pour IE
			if (step > 1)
			{
				bgIE = 'filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+fileName+'-bg.png", sizingMethod="scale");';
			}
			else
			{
				bgIE = 'filter: progid:DXImageTransform.Microsoft.gradient(gradientType='+dirIE+', startColorstr='+startColor.colorIE+', endColorstr='+endColor.colorIE+');';
			}
			
			code += commentIE+
			'	*background: '+bgColorValueAlone+';'+"\n"+
			'	background: '+bgColorValueAlone+'\\0/;'+"\n"+
			'	'+bgIE+"\n";
		}
		
		code += '	}'+"\n"+
		'	@media all and (min-width: 0px) {'+"\n"+
		'		#selector# {'+"\n"+
		commentOpera+
		'			background: '+bgColorValue+'url("'+fileName+'-bg.svg");'+"\n"+
		commentRecent+
		'			background-image: -webkit-gradient('+"\n"+
		'				linear,'+"\n"+
		'				'+dirWebkit+','+"\n"+
		'				from('+startColor.color+'),'+"\n"+
		'				to('+endColor.color+')'+stepsWebkit+"\n"+
		'			);'+"\n"+
		'			background-image: -webkit-linear-gradient('+"\n"+
		'				'+dirFF+','+"\n"+
		'				'+startColor.color+','+"\n"+
		'				'+stepsFF+endColor.color+''+"\n"+
		'			);'+"\n"+
		'			background-image: -moz-linear-gradient('+"\n"+
		'				'+dirFF+','+"\n"+
		'				'+startColor.color+','+"\n"+
		'				'+stepsFF+endColor.color+''+"\n"+
		'			);'+"\n"+
		'			background-image: -o-linear-gradient('+"\n"+
		'				'+dirFF+','+"\n"+
		'				'+startColor.color+','+"\n"+
		'				'+stepsFF+endColor.color+''+"\n"+
		'			);'+"\n"+
		'			background-image: linear-gradient('+"\n"+
		'				'+dirFF+','+"\n"+
		'				'+startColor.color+','+"\n"+
		'				'+stepsFF+endColor.color+''+"\n"+
		'			);'+"\n"+
		'		}'+"\n"+
		'	}';
	}
	
	// Gestion de SyntaxHighlighter
	$('#code-block').empty().append('<pre class="brush: css" id="code"></pre>');
	$('#code').html(code.replace(/#selector#/g, className));
	SyntaxHighlighter.highlight();
	
	// Application à la prévisualisation
	code = code.replace(new RegExp(fileName+'-bg.png', 'g'), 'images/gradient-png.php?time='+timestamp+'&'+finalHash);
	code = code.replace(new RegExp(fileName+'-bg.svg', 'g'), 'images/gradient-svg.php?time='+timestamp+'&'+finalHash);
	code = code.replace(/#selector#/g, '.block-preview div#preview');
	
	$('style#preview-css').remove();
	$('head').append('<style type="text/css" id="preview-css">'+code+'</style>');
	
	// Lien
	document.location.hash = '#'+finalHash;
	
	// Historique
	if (gradientHistory.done.length == 0 || gradientHistory.done[gradientHistory.done.length-1] != finalHash)
	{
		gradientHistory.done.push(finalHash);
		gradientHistory.undone = [];
	}
	$('#undo-button').attr('disabled', (gradientHistory.done.length < 2));
	$('#redo-button').attr('disabled', (gradientHistory.undone.length == 0));
	
	// Lien de téléchargement des images
	$('#png-link').attr('href', 'images/gradient-png.php?time='+timestamp+'&'+finalHash+'&download='+fileName+'-bg');
	$('#svg-link').attr('href', 'images/gradient-svg.php?time='+timestamp+'&'+finalHash+'&download='+fileName+'-bg');
}

// Convertit un code couleur pour son utilisation dans un shash
function convertColorForHash(color)
{
	if (color.substr(0, 1) == '#')
	{
		color = color.substring(1);
	}
	else if (color.indexOf('(') > -1)
	{
		color = color.substring(color.indexOf('(')+1, color.lastIndexOf(')'));
	}
	
	return color;
}

// Annule le dernier changement
function undoChange()
{
	if (gradientHistory.done.length > 1)
	{
		gradientHistory.undone.push(gradientHistory.done.pop());
		buildFromHash(gradientHistory.done[gradientHistory.done.length-1]);
	}
}

// Rétablit le dernier changement
function redoChange()
{
	if (gradientHistory.undone.length > 0)
	{
		gradientHistory.done.push(gradientHistory.undone.pop());
		buildFromHash(gradientHistory.done[gradientHistory.done.length-1]);
	}
}

/**
 * Récupère la valeur d'un champ couleur, ou renvoie false si elle n'est pas définie
 * @param string name le nom de la couleur
 * @param string defaultHex la couleur par défaut, sous forme hexa
 * @return Object|boolean false si la couleur n'est pas définie, sinon un objet avec les clés :
 * 							- type : le type de code : hex, name ou rgba
 * 							- color : le code couleur pour tous les navigateurs modernes
 * 							- colorIE : le code couleur avec alpha pour les filtres d'IE
 * 							- colorOld : le code couleur pour les anciens navigateurs
 * 							- alpha : la valeur alpha (en %)
 * 							- position : la position en % (si existante, sinon vaut 0)
 */
function getColor(name, defaultHex)
{
	// Test si la couleur existe
	if ($('#'+name+'-color').length === 0)
	{
		return false;
	}
	
	var type;
	var color;
	var colorIE;
	var colorOld;
	var alpha;
	var hexReg = new RegExp('^#?[0-9A-F]{3,6}$', 'gi');
	switch ($('input[name="'+name+'-type"]:checked').val())
	{
		case 'name':
			type = 'name';
			color = $('#'+name+'-type-name-value').val();
			colorIE = '#FF'+namedColors[color];
			colorOld = color;
			alpha = 100;
			break;
			
		case 'rgba':
			// Récupération
			var r = parseInt($('#'+name+'-type-rgba-r').val());
			if (isNaN(r)) { r = 0; }
			var g = parseInt($('#'+name+'-type-rgba-g').val());
			if (isNaN(g)) { g = 0; }
			var b = parseInt($('#'+name+'-type-rgba-b').val());
			if (isNaN(b)) { b = 0; }
			var a = parseFloat($('#'+name+'-type-rgba-a').val());
			if (isNaN(a)) { a = 1; }
			
			// Limites
			r = Math.min(255, Math.max(0, r));
			g = Math.min(255, Math.max(0, g));
			b = Math.min(255, Math.max(0, b));
			a = Math.min(100, Math.max(0, a));
			if (a > 1)
			{
				var ie_a = Math.round(a*2.55);
				alpha = a;
				a = a/100;
			}
			else
			{
				var ie_a = Math.round(a*255);
				alpha = a*100;
			}
			
			type = 'rgba';
			color = 'rgba('+r+','+g+','+b+','+a+')';
			colorIE = '#'+d2h(ie_a)+d2h(r)+d2h(g)+d2h(b);
			colorOld = '#'+d2h(r)+d2h(g)+d2h(b);
			break;
		
		default:
			type = 'hex';
			color = $.trim($('#'+name+'-type-hex-value').val());
			alpha = 100;
			if (!color.match(hexReg))
			{
				color = defaultHex;
			}
			
			colorIE = '#FF'+color;
			color = '#'+color;
			colorOld = color;
			if (color.length < 6)
			{
				colorIE = '#FF'+color.substr(0, 1)+color.substr(0, 1)+color.substr(1, 1)+color.substr(1, 1)+color.substr(2, 1)+color.substr(2, 1);
			}
			break;
	}
	
	// Position
	var posInput = $('#'+name+'-position');
	var position = 0;
	if (posInput.length > 0)
	{
		position = parseFloat(posInput.val());
		if (isNaN(position))
		{
			position = 50;
		}
	}
	
	return {
		type: type,
		color: color,
		colorIE: colorIE,
		colorOld: colorOld,
		alpha: alpha,
		position: position
	};
}

// Conversions Hex <-> Dec
function d2h(d) {
	var hex = d.toString(16);
	if (hex.toString().length < 2)
	{
		hex = '0'+hex;
	}
	return hex;
}
function h2d(h) { return parseInt(h,16); } 

// Efface le dégradé
function resetGradient()
{
	buildFromHash('startType=hex&startValue=aaeeff&endType=hex&endValue=3399cc');
}

// Inverse l'odre du dégradé
function reverseGradient()
{
	// Init
	gradientInit = false;
	
	// Récupération des couleurs
	var startColor = getColor('start', 'FFFFFF');
	var endColor = getColor('end', 'FFFFFF');
	
	// Couleur de début
	var startBlock = $('#start-color');
	startBlock.applyColor({
		type: endColor.type,
		value: convertColorForHash(endColor.color)
	});
	
	// Couleur de fin
	$('#end-color').applyColor({
		type: startColor.type,
		value: convertColorForHash(startColor.color)
	});
	
	// Inversion des étapes
	$('.color-block').not(':first, :last').each(function() {
		
		var position = $(this).find('input[id$="-position"]');
		position.val(100-parseInt(position.val()));
		startBlock.after($(this));
		
	});
	$('.color-block').not(':first, :last').reorderSteps();
	
	// Mise à jour
	gradientInit = true;
	updateCSS();
}
