function replace_input(objet, newtxt )
{
	if( typeof $(document)[0].selection != 'undefined' )
	{
		/* Insertion du code de formatage */
		var range = $(document)[0].selection.createRange();
				
		// on récupère la taille d'origine du texte
		var origi_length	= objet.length;
				
		var range 			= objet[0].createTextRange();
		range.moveToBookmark($(document)[0].selection.createRange().getBookmark());
		range.moveEnd('character', objet.length);
				
		var start			= objet.length - range.text.length;
				
		var range 			= objet[0].createTextRange();
		range.moveToBookmark( $(document)[0].selection.createRange().getBookmark() );
		range.moveStart( 'character', -objet.length );
		
		var end				= range.text.length;
		
		if( end < start )
			end = start;
		
		objet.val( newtxt );
		
		alert(start);
			
		// on récupère la taille du texte
		var dif				= origi_length - objet.val().length;
		
		var range 			= objet[0].createTextRange();
		range.moveStart( 'character', start - dif );
		range.moveEnd( 'character', -objet.val().length + end - dif );
		range.select();
	}
	else
	if( typeof objet[0].selectionStart != 'undefined' )
	{
		// on récupère la position du curseur
		var start			= objet[0].selectionStart;
		var end				= objet[0].selectionEnd;
		
		// on récupère la taille d'origine du texte
		var origi_length	= objet.val().length;
		
		// on retire les retours à la ligne
		objet.val( newtxt );
		
		// on récupère la taille du texte
		var dif				= origi_length - objet.length;
		
		// si il y a une différence c'est qu'on a retiré un retour a la ligne
		if( dif > 0 )
			dif = 1;
	
		// on repositione le curseur
		objet[0].selectionStart	= start - dif;
		objet[0].selectionEnd	= end - dif;
	}
}

/*
	Fonction de remise à zéro des champs
*/
// $("select[name='id_couleur'] option:contains('Non précisé')").val()
function reset_cases(level)
{
	switch(level)
	{
		case 1:
			$('#modele').hide();
		case 2:
			$('#carburant').hide();
		case 3:
			$('#transmission').hide();
		case 4:
			$('#dateconstruct').hide();
		case 5:
			$('#search_options').hide();
		case 6:
			$('#typevoit').hide();
			$('#typevoit_titre').hide();
			$('#e2 .prev').show();
			$('#e2 .next').show();
			//$('#2').hide();
			//$('#3').hide();
			$('#e1 .next').hide();
			$('input[name="photosup"]').attr('disabled',true);
			$("#footer").removeClass().addClass('footer_class');
	}
}

/*
	fonction pour recharger l'event sur les bouttons radio
		de selection des voitures.
*/
function voit_events()
{
	$('input[@name=id_typevoit]').click(function()
	{
		id_typevoit	= $('input[@name=id_typevoit]:checked').val();
		$.ajax({
			type: "GET",
			url: "ajax/insert.php",
			data:	{
				id_typevoit: id_typevoit,
				t: 'options',
				l: langue
			},
			async: false,
			success: function(msg){
				$('#options').html(msg);
				//$('#typevoit').show();
				//$('#typevoit_titre').show();
				
				//voit_events();
				$('#e1 .next').show();
				$('#e1').hide();
				$('#e2').show();
				
				if( $('input[@name=id_typevoit]:checked').val() != "" )
				{
					$('input[name="typetxt"]').val( $('input[name="id_typevoit"]:checked').parent().parent().children('td:eq(1)').text() );
				}
				else
				{
					$('input[name="dateconstructb"]').val($('select[name="dateconstruct"] option:selected').val());
					$('.dateconstructb').show();
				}
			}
		});
	});
}

function select_line_bonus()
{
	if( $('textarea[name="descriptionfr"]' ).val().length > $('textarea[name="descriptionnl"]' ).val().length )
	{
		txt	= $('textarea[name="descriptionfr"]' ).val();	
	}
	else if( $('textarea[name="descriptionfr"]' ).val().length < $('textarea[name="descriptionnl"]' ).val().length )
	{
		txt	= $('textarea[name="descriptionnl"]' ).val();	
	}
	else
	{
		txt	= $('textarea[name="description'+ _LANG + '"]' ).val();
	}
	
	txt		+= "&nbsp;" + $('input[name="contactteldesc"]').val();
	
	//alert(txt.length + " - " + (min_characters) + " | " + max_characters);
	
	$('#5lignes').hide();
	$('#6lignes').hide();
	
	if( txt.length > (min_characters) && txt.length <= (min_characters+characters_by_line) )
	{
		$('.5lignes').attr("checked", true).show();
		$('#5lignes').show();
	}
	else if( txt.length > (min_characters+characters_by_line) && txt.length <= max_characters )
	{
		//alert("arg");
		$('.6lignes').attr("checked", true).show();
		$('#6lignes').show();
	}
}

function make_total()
{
	total	= 0;
	if( $('select[name="journalouinternet"]').val() == 2 )
	{
		total += 0.5;
	}
	
	if( $('input[name="bonusline"]:checked').val() != undefined )
	{
		total += parseFloat( $('input[name="bonusline"]:checked').val() );
	}
	
	if( $('input[name="photosup"]:checked').val() != undefined )
	{
		total += parseFloat( $('input[name="photosup"]:checked').val() );
	}
	
	total += parseFloat( $('input[name="annprix"]:checked').val() );
	
	//alert( total );
	
	$('.total').html( total.toString().replace('.',',') + " Euro" );
	$('input[name="total"]').val( total );
}

/*
	Fonction pour charger la liste des version de la voiture
*/
function load_voit()
{
	$('.descr').each(function(){
		if( $(this).attr('lang') != _LANG )
		{
			$(this).hide();
		}
	});

	reset_cases(6);
	
	id_transmission = $("select[@name=id_transmission]").val();
	id_marque		= $("select[@name=id_marque]").val();
	id_modele		= $("select[@name=id_modele]").val();
	id_transmission	= $("select[@name=id_transmission]").val();
	id_carburant	= $("select[@name=id_carburant]").val();
	typenbporte		= $("select[@name=typenbporte]").val();
	ladateconstruct	= $('select[name="dateconstruct"]').val();
	
	// on charge les options
	$.ajax({
		type: "GET",
		url: "ajax/insert.php",
		data:	{
					id_marque: id_marque,
					id_modele: id_modele,
					id_transmission: id_transmission,
					id_carburant: id_carburant,
					typenbporte: typenbporte,
					dateconstruct: ladateconstruct,
					t: 'type',
					l: langue },
		async: false,
		success: function(msg){
			$('#typevoit td:eq(0)').html(msg);
			$('#typevoit').show();
			$('#typevoit_titre').show();
			
			voit_events();
		}
	});
}

$(document).ready(function(){


	$('#left form').bind('keypress', function(event) {
   	 	if (String.fromCharCode(event.which).match(/\r/i))
    		    return false;
	});

	langue	= _LANG;
	
	savetxt		= $('.save').html();
	savephoto	= $('.savephoto').html();
	
	$('input[name="flashok"]').val( FlashDetect.major + "." + FlashDetect.minor + "r" + FlashDetect.revision );
	
	/* Nettoyage des champs */
	$('input.numeric').keyup(function()
	{
		$(this).val( $(this).val().replace(/[^0-9]/ig,"") );
	}).focus(function()
	{
		if( parseInt( $(this).val() ) == 0)
		{
			$(this).val("");
		}
	});
	
	$('input.tel').keyup(function()
	{
		$(this).val( $(this).val().replace(/[^0-9|\/|\.|+|(|)]/ig,"") );
	}).focus(function()
	{
		if( parseInt( $(this).val() ) == 0)
		{
			$(this).val("");
		}
	});
	
	$('select[@name=id_marque]').change(function()
	{
		reset_cases(1);
		id_marque	= $(this).val();
		
		if( id_marque != 0 )
		{
			// on charge les options
			$.ajax({
				type: "GET",
				url: "ajax/insert.php",
				data:	{ w: ("id_marque = " + id_marque), t: 'modele', l: langue },
				async: false,
				success: function(msg){
					$('select[@name=id_modele]').html(msg);
					$('select[@name=id_modele]')[0].selectedIndex = 0;
					//alert( $(this).text() );
					$('input[name="marqutxt"]').val( $('select[name="id_marque"] option:selected').text() );
					$('#modele').show();
				}
			});	
		}
	});
	
	$('select[@name=id_modele]').change(function()
	{
		reset_cases(2);
		
		id_modele	= $(this).val();
		
		if( id_modele != 0 )
		{
			// on charge les options
			$.ajax({
				type: "GET",
				url: "ajax/insert.php",
				data:	{ w: ("id_modele = " + id_modele), t: 'carburant', l: langue },
				async: false,
				success: function(msg){
					$('select[@name=id_carburant]').html(msg);
					$('select[@name=id_carburant]')[0].selectedIndex = 0;
					$('input[name="modeltxt"]').val( $('select[name="id_modele"] option:selected').text() );
					$('#carburant').show();
				}
			});	
		}
	});
	
	$('select[@name=id_carburant]').change(function()
	{
		reset_cases(3);
		
		id_carburant	= $(this).val();
		id_modele		= $("select[@name=id_modele]").val();
		
		if( id_carburant != 0 )
		{
		
			if( $(this).val() != 0 )
			{
				$.ajax({
					type: "GET",
					url: "ajax/insert.php",
					data:	{ w: " id_modele = " + id_modele + " AND  id_carburant = " + id_carburant, t: 'date' },
					async: false,
					success: function(msg){
						//alert(msg);
						$('#dateconstruct').show();
						$('select[@name=dateconstruct]').html(msg);
						$('select[@name=dateconstruct]')[0].selectedIndex = 0;
					}
				});
			}
		}
	});
	
	
	
	$('select[@name=dateconstruct]').change(function()
	{
		reset_cases(5);
		
		if( $(this).val() != 0 )
		{
			id_carburant	= $("select[@name=id_carburant]").val();
			id_modele		= $("select[@name=id_modele]").val();
			_dateconstruct	= $('select[name="dateconstruct"]').val();
		
			$.ajax({
				type: "GET",
				url: "ajax/insert.php",
				data:	{ w: ("id_modele = " + id_modele + " AND id_carburant = " + id_carburant + " AND ( SUBSTRING( ISNULL( datedebut, 1985 ) ,0,5) <= " + _dateconstruct + " AND SUBSTRING( ISNULL( datefin, (CAST(year(getdate()) as varchar(4))+1)) ,0,5) >= " + _dateconstruct + ")"), t: 'transmission', l: langue },
				async: false,
				success: function(msg){
					$('select[@name=id_transmission]').html(msg);
					$('select[@name=id_transmission]')[0].selectedIndex = 0;
					
					$.ajax({
						type: "GET",
						url: "ajax/insert.php",
						data:	{ w: "id_modele = " + id_modele + " AND  id_carburant = " + id_carburant, t: 'typenbporte', l: langue },
						async: false,
						success: function(msg){
							//alert(msg);
							$('#search_options').show();
							$('select[@name=typenbporte]').html(msg);
							$('select[@name=typenbporte]')[0].selectedIndex = 0;
						}
					});
				}
			});
			
			load_voit();
		}
	});
	
	
	$('select[@name=id_transmission]').change(function()
	{
		load_voit();
	});
	
	$('select[@name=typenbporte]').change(function()
	{
		load_voit();
	});
	
	$('.next').click(function()
	{
		if($(this).parent().attr('id') !== 'e3')
		{
			page	= parseInt( $(this).parents('div').attr('id').substr(1,2) );
			next	= page+1;
			
			$('#e'+page).hide();
			$('#e'+next).show();
		}
	});
	
	$('.prev').click(function()
	{
		page	= parseInt( $(this).parents('div').attr('id').substr(1,2) );
		prev	= page-1;
		
		$('#e'+page).hide();
		$('#e'+prev).show();
	});
	
	characters_by_line	= 30;
	line_numbers		= 4;
	bonus_lines			= 2;
	min_characters		= line_numbers*characters_by_line;
	max_characters		= (line_numbers+bonus_lines)*characters_by_line;
	
	$('.descriptions th').each(function()
	{
		if( $(this).attr('lang') == _LANG )
		{
			$(this).addClass("selected");
		}
	})
	.click(function()
	{
		lang = $(this).attr('lang');

		$('.descriptions th').each(function()
		{
			if( $(this).attr('lang') == lang )
			{
				$('.descr[@lang='+$(this).attr('lang')+']').show();
				$(this).addClass("selected");
			}
			else if( $(this).attr('lang') != undefined && $(this).attr('lang') != "none" )
			{
				$('.descr[@lang='+$(this).attr('lang')+']').hide();
				$(this).removeClass("selected");
			}
		});
		
		$('input[name="nbrdesc"]').val( max_characters-characters_by_line-$('textarea[name="description'+lang+'"]').val().length );
		
	});
	
	$('input[name="nbrdesc"]').val( max_characters-characters_by_line );
	
	$('#e3 .next').click(function(){
		contactteldesc		= $('input[name="contactteldesc"]').val();
		if(contactteldesc == "" || contactteldesc == 0)
		{
			alert( "Remplissez tous les champs marqués d'un * rouge.\n\nDe velden met een rode * dienen ingevuld te worden" );
			//$('#e3').show();
			//$('#e4').hide();
			return false;
		}
	
		t = ' array( ';
		
		$("input[name^='opt']").each(function(){
			t += ' "' + $(this).attr("name") + '" => ' + $(this)[0].checked + ',';
		});
		
		$("textarea[name^='description']").each(function()
		{
			$(this).val( $(this).val().substr( 0, max_characters-characters_by_line) );
		});
		
		t = t.substr(0, t.length-1);
		t += ' );'
		
		id_typevoit				= $('input[name="id_typevoit"]:checked').val();
		ladateconstruct			= $('select[name="dateconstruct"]').val();
		laid_couleur			= $('select[name="id_couleur"]').val();
		id_etatvoit				= $('select[name="id_etatvoit"]').val();
		km						= $('input[name="nbkm"]').val();
		controltechniquemois	= $('select[name="controltechniquemois"]').val();
		controltechniqueannee	= $('select[name="controltechniqueannee"]').val();
		prix					= $('input[name="prix"]').val();
		id_client				= $('input[name="clientuser_id"]').val();
		
		if( $('textarea[name="descriptionfr"]' ).val().length > $('textarea[name="descriptionnl"]' ).val().length )
		{
			txt	= $('textarea[name="descriptionfr"]' ).val();	
		}
		else if( $('textarea[name="descriptionfr"]' ).val().length < $('textarea[name="descriptionnl"]' ).val().length )
		{
			txt	= $('textarea[name="descriptionnl"]' ).val();	
		}
		else
		{
			txt	= $('textarea[name="description'+ _LANG + '"]' ).val();
		}
		
		txt	+= " " + contactteldesc;
		
		if( id_typevoit == "" )
		{
			id_typevoit = $('select[name="id_marque"] option:selected').text() + "¥" + $('select[name="id_modele"] option:selected').text() + "¥" + $('input[name="typetxt"]').val();
		}
		
		$.ajax({
			type: "GET",
			url: "ajax/getdescmini.php",
			data:	{ date: ladateconstruct, id_couleur: laid_couleur, l: langue, id_etatvoit: id_etatvoit, km: km, options: t, id_typevoit: id_typevoit, description: txt, prix: prix, id_client: id_client  },
			async: false,
			success: function(msg){

				$('th.markmodel').html($("select[@name=id_marque] option:selected()").text() + " - " + $("select[@name=id_modele] option:selected()").text());
				$('td.descmini').html(msg+"<hr/>");
			}
		});
		
		//br = "<br />";
		
		//txt		= $('textarea[name="description' + _LANG + '"]' ).val();
		/*if( $('textarea[name="descriptionfr"]' ).val().length > $('textarea[name="descriptionnl"]' ).val().length )
		{
			txt	= $('textarea[name="descriptionfr"]' ).val();	
		}
		else if( $('textarea[name="descriptionfr"]' ).val().length < $('textarea[name="descriptionnl"]' ).val().length )
		{
			txt	= $('textarea[name="descriptionnl"]' ).val();	
		}
		else
		{
			txt	= $('textarea[name="description'+ _LANG + '"]' ).val();
		}*/

		start	= txt.substr(0, min_characters).replace(/\n/g, '').replace(/\n\n+/g, '');
		ligne1	= "<span style=\"color: brown\">" + txt.substr(min_characters, max_characters) + "</span>";
		//ligne2	= "<span style=\"color: red\">" + txt.substr(min_characters+characters_by_line) + "</span>";

		$('.desctxt').html( start + ligne1 );
		
		select_line_bonus();
		make_total();
		
		
		$('#e3').hide();
		$('#e4').show();
	});
	
	$('#e4 .prev').click(function(){
		$('input[name="bonusline"]:checked').removeAttr('checked');
	});
	
	$('#e4 .save').click(function(){
		clientnom			= $("input[name='clientnom']").val();
		clientadresse		= $("input[name='clientadresse']").val();
		clienttel			= $("input[name='clienttel']").val();
		clientpays			= $("input[name='clientpays']").val();
		clientcodepostal	= $("input[name='clientcodepostal']").val();
		clientville			= $("input[name='clientville']").val();
		facturation			= $("input[name='facturation']:checked").val();
		titulairecarte		= $("input[name='titulairecarte']").val();
		numerocarte			= $('input[name="numerocarte"]').val();
		dateexptmois		= $('select[name="dateexptmois"]').val();
		dateexptann			= $('select[name="dateexptann"]').val();
		
		
		if( clientnom == "" || clientadresse == "" || clienttel == "" || clientpays == "" || clientcodepostal == "" || clientville == "" || (facturation == "credit" && (titulairecarte == "" || numerocarte == "" || dateexptmois == 0 || dateexptann == 0 )) )
		{
			alert( "Remplissez tous les champs marqués d'un * rouge.\n\nDe velden met een rode * dienen ingevuld te worden" );
			return false;
		}
		else
		{
			$('form[name="inspost"]').submit();
		}
		
	});
	
	$('select[name="journalouinternet"]').change(function(){
		if( $(this).val() < 1 )
		{
			$('input[pa="autos"]').parent().parent().hide();
			$('input[pa="encadre"]').parent().parent().hide();
			$('input[pa="rouge"]').parent().parent().hide();
			$('input[pa="rougephoto"]').parent().parent().hide();
			
			if( $('input[name="annprix"]:checked').attr("pa") != "simple" && $('input[name="annprix"]:checked').attr("pa") != "photo" )
			{
				$('input[pa="simple"]:eq(0)').attr("checked", true);
				
				$('input[name="photosup"]').removeAttr('checked');
				$('input[name="photosup"]').attr('disabled',true);
				$('.save').html(savetxt);
			}
			
			//$('input[pa="simple"]:eq(0)').attr("checked", true);
		}
		else
		{
			$('input[pa="autos"]').parent().parent().show();
			$('input[pa="encadre"]').parent().parent().show();
			$('input[pa="rouge"]').parent().parent().show();
			$('input[pa="rougephoto"]').parent().parent().show();
		}
		
		make_total();
	});
	
	$('input[name="annprix"]').click(function(){
		make_total();
		
		if( $(this).attr('class') == "avecphoto" )
		{
			$('input[name="photosup"]').removeAttr('disabled');
			$('.save').html(savephoto);
		}
		else
		{
			$('input[name="photosup"]').removeAttr('checked');
			$('input[name="photosup"]').attr('disabled',true);
			$('.save').html(savetxt);
		}
		
		$('input[name="typepa"]').val($(this).attr("pa"));
		
		//alert((this).attr("parution"));
		
		$('input[name="parutions"]').val($(this).attr("parution"));
	});
	
	$('input[name="photosup"]').click(function(){
		make_total();
	});
	
	$('input[name="facturation"]').click(function(){
		if( $(this).val() == "credit" )
		{
			$("#methodepayement").show();
		}
		else
		{
			$("#methodepayement").hide();		
		}
	});
	
	$("textarea[name^='description']").keyup(function()
	{
		//replace_input( $(this), $(this).val().substr(0, min_characters).replace(/\n/g, '').replace(/\n\n+/g, '') );
		
		if( typeof $(document)[0].selection != 'undefined' )
		{
			/* Insertion du code de formatage */
			var range = $(document)[0].selection.createRange();
			
			// on récupère la taille d'origine du texte
			var origi_length	= $(this).val().length;
			
			var range 			= $(this)[0].createTextRange();
			range.moveToBookmark($(document)[0].selection.createRange().getBookmark());
			range.moveEnd('character', $(this).val().length);
			
			var start			= $(this).val().length - range.text.length;
			
			var range 			= $(this)[0].createTextRange();
			range.moveToBookmark( $(document)[0].selection.createRange().getBookmark() );
			range.moveStart( 'character', -$(this).val().length );
			
			var end				= range.text.length;
			
			if( end < start )
				end = start;
			
			$(this).val( $(this).val().substr(0, (max_characters-characters_by_line)).replace(/\n/g, '').replace(/\n\n+/g, '') );
				
			// on récupère la taille du texte
			var dif				= origi_length - $(this).val().length;
			
			var range 			= $(this)[0].createTextRange();
			range.moveStart( 'character', start - dif );
			range.moveEnd( 'character', -$(this).val().length + end - dif );
			range.select();
			
			
		}
		else
		if( typeof $(this)[0].selectionStart != 'undefined' )
		{
			// on récupère la position du curseur
			var start			= $(this)[0].selectionStart;
			var end				= $(this)[0].selectionEnd;
			
			// on récupère la taille d'origine du texte
			var origi_length	= $(this).val().length;
			
			// on retire les retours à la ligne
			$(this).val( $(this).val().substr(0, (max_characters-characters_by_line)).replace(/\n/g, '').replace(/\n\n+/g, '') );
			
			// on récupère la taille du texte
			var dif				= origi_length - $(this).val().length;
			
			// si il y a une différence c'est qu'on a retiré un retour a la ligne
			if( dif > 0 )
				dif = 1;
		
			// on repositione le curseur
			$(this)[0].selectionStart	= start - dif;
			$(this)[0].selectionEnd		= end - dif;
		}
		
		$('input[name="nbrdesc"]').val( (max_characters-characters_by_line)-$(this).val().length );
	});
	
	reset_cases(1);
});