$(document).ready(function(){

	// -----------------------------------------------------------------
	// - [FORM ACCUEIL] Options afficher/masquer
	$('#text').css('width',815);
	$('#options').hide();
	$('button#toggle_options').removeClass().addClass('afficher');
	$('div#accueil_droite').css('margin-left',0);
	
	var options_displayed=false;
	function optionsToggle()
	{
		options_displayed=!options_displayed;
		$('div#options').toggle(); // display none todo
		$('textarea#text').css('width',options_displayed ? 598 : 815);
		// $('div#accueil_droite').css('margin-left',options_displayed ? 220 : 0); // c'est en float donc auto
		$('button#toggle_options').removeClass().addClass(options_displayed ? 'masquer' : 'afficher' );
		
	}
	$('button#toggle_options')	.click(optionsToggle)
								.focus(function(){$(this).blur();});
						
						/*			
	$('textarea#text').focus(function(){ $(this).parent().find('div#bbc_bar').add($(this)).css('border-color', 'black') })
	$('textarea#text').blur(function(){ console.log('blur'); $(this).parent().find('div#bbc_bar').add($(this)).css('border-color', 'transparent') })
	*/
	$('textarea#text').trigger('focus');
	
	// $('div#bbc_bar').mousedown(function(){ $('textarea#text').css('border-color', 'red'); console.log('done'); });
						   
	// -----------------------------------------------------------------
	// - [FORM ACCUEIL] Liste de liens <> Liens cliquables
	// - [FORM ACCUEIL] Liste de liens <> Bouton nouvelle catégorie
	// - [FORM ACCUEIL] Sortie liste de liens <> Revenue à un textarea

	var selectTpl_LastVal =$('div#options select#template').val();
	var lastTextAreaId=0; // 0 = textarea premier
	
	$('div#options select#template').change(function()
										{
											var isLdl = ($(this).val()=='listedeliens');
											if (isLdl) $('div#options input#cliquable').attr('checked',true);

											// On confirme si on veut bien enlever la formation blocsdeliens si on sort de LDL
											if (selectTpl_LastVal=='listedeliens' && !isLdl)
											{
												if (!confirm('Attention, les différents listes de lien ainsi que leur contenu vont être supprimés. Continuer ?'))
												{
													$(this).val('listedeliens');
													return;
												}
												else
												{
													$('textarea.blocliens').remove();
													$('textarea#text').show();
													lastTextAreaId=0;
												}
											}

											/* Passage à la listedeliens */

											$('div#options input#cliquable').parent().css('display',isLdl ? 'none' : 'block'); // parent = clearfixbloc

											/*
											if (isLdl) $('div#options select#bbcode').val('transform');
											$('div#options select#bbcode').parent().css('display',isLdl ? 'none' : 'block');
											*/

											$('button#new_blocliens').css('display',isLdl ? 'block' : 'none');
											
											selectTpl_LastVal = $(this).val();
										});

	$('div#options select#template').triggerHandler('change'); // Pour le repost
	
	// -----------------------------------------------------------------
	// [FORM ACCUEIL] Liste de liens <> Textareas
	$('button#new_blocliens').click(function()
									{
										if (lastTextAreaId==0)
										{
											var textAreaBase =	$('form#creer textarea#text')
																	.css('display','none');

											var textArea2 = $('<textarea />')
															.attr('name','')
															.attr('id','blocliens_'+(lastTextAreaId+1))
															.addClass('blocliens')
															.css('display','inline-block');

											// newTextarea contient le textarea 1 et le textarea 2
											var appendContent = textArea2
																.clone()
																	.attr('id','blocliens_'+(lastTextAreaId))
																	.val(textAreaBase.val())
																	.andSelf(); // on sélectionne le 2 en meme temps

										}
										else
										{
											var appendContent =	$('form#creer textarea#blocliens_'+lastTextAreaId)
																	.clone()
																		.addClass('blocliens')
																		.attr('id','blocliens_'+(lastTextAreaId+1));												   ;
										}
										
										lastTextAreaId++;
										$('#accueil_droite').append(appendContent);
										$('div#accueil_droite textarea:last-child').focus();
										return false;
									});

	$('form#creer').submit(function()
							{
								if (lastTextAreaId>0)
								{
									var finalContent='';
									for (var i=0; i<lastTextAreaId+1; i++)
									{
										finalContent+='[bloc]'+($('#blocliens_'+i).val())+'[/bloc]';
									}

									$('form#creer textarea#text').val(finalContent);
								}
							})

	//- Coloration syntx <> Template code
	$('div#options select#lang').change(function()
										{
											var locked = ($(this).val()!='none');
											if (locked) $('div#options select#template').val('code');
											$('div#options select#template').triggerHandler('change');
	
											/*
											$('div#options select#template').attr('disabled',locked);
											$('div#options input#cliquable').attr('disabled',false);
											* */
										});
								
	// -----------------------------------------------------------------
	// [FORM ACCUEIL] Insertions BBCODE
	
	$('select[name=bbcode]').change(function(){
		if ($(this).val()=='transform') 
			$('div#bbc_bar').show();
		else
			$('div#bbc_bar').hide();
	});
	
	var el_textarea = $('textarea#text');
	$('div#accueil_droite button.bbc_srr').each(function(){
		$(this).click(
			(function(bbc_tagname)
			{
				return function() {
					el_textarea.surroundSelectedText('['+bbc_tagname+']', '[/'+bbc_tagname+']'); // ,true
					el_textarea.focus();
					}
			})($(this).attr('id').substr(5))
		);
	})
	
	$('div#accueil_droite button').each(function(){
		$(this).attr('title',$(this).text());
	})
	
	$('div#accueil_droite select[name=bbc_size] option').nextAll().each(function(){
		$(this).css('font-size',$(this).text()+'px');
		
		$(this).click(
			(function(bbc_tagname)
			{
				return function() {
					el_textarea.surroundSelectedText('[size='+bbc_tagname+']', '[/size]'); // ,true
					el_textarea.focus();
					$(this).parent().find('option:first').attr('selected',true);
					}
			})($(this).text())
		);
	})
	
	$('div#accueil_droite button#bbcb_listitem').click(function(){
		el_textarea.surroundSelectedText('\n[*]', ''); // ,true
		el_textarea.focus();
		// el_textarea.replaceSelectedText('\n[*]')
	})
	
	$('div#accueil_droite button#bbcb_url').click(function(){
		var url = prompt('Veuillez insérer l\'URL du lien.','http://')
		if (url!=null)
		{
			if (el_textarea.getSelection().length==0)
			{
				contenu=prompt('Veuillez insérer le texte menant à l\'URL.',url);
				if (contenu==null)
					contenu=url;			
				el_textarea.replaceSelectedText('[url='+url+']'+contenu+'[/url]'); // ,true
			}
			else
			{
				el_textarea.surroundSelectedText('[url='+url+']', '[/url]'); // ,true
			}
		}
		el_textarea.focus();
		// el_textarea.replaceSelectedText('\n[*]')
	})
	
	

	// -----------------------------------------------------------------
	// - [CODE]/[LOG] - Sélectionner le code
	var is_textarea = false;
	var content = $('div#codewrapper ol').text();
	var obj_textarea =	$('<textarea />')
						.css('width','90%')	
						.css('height','570px')
						.val(content)
						.attr('readonly',true);

	$('a#select').text('Sélectionner le code');
	$('a#select').click(	function()
								{
									if (!is_textarea)
									{
										$(this).text('Affichage normal');
										$('div#codewrapper ol').hide();
										$('div#codewrapper').prepend(obj_textarea);
										obj_textarea.focus();
										obj_textarea.select();
									}
									else // true
									{
										$(this).text('Sélectionner le code');
										$('div#codewrapper textarea').remove();
										$('div#codewrapper ol').show();
									}
									is_textarea = !is_textarea;
									$(this).blur();
									return false;
								}
						)

	// -----------------------------------------------------------------
	// - [LISTE DE LIENS] - Tout ouvrir
	$('p#toutouvrir a').click(	function()
								{
									$('div#readbox a').each(function()
																	{
																		window.open( $(this).attr('href'));
																	});
									return false;
								}
							);

	// -----------------------------------------------------------------
	// - [LISTE DE LIENS] Swap target self/blank
	var blank = 0;
	var targetA = new Array('_self','_blank');
	var targetIndicatorTextA = new Array('Les liens s\'ouvriront dans cette même fenêtre',
										 'Les liens s\'ouvriront dans une nouvelle fenêtre');

	// Le comportement vis-à-vis des liens est régi par le navigateur et l'internaute
	function updateTargetIndicatorText()
	{
		$('span#targetIndicator').text(targetIndicatorTextA[blank]);
	}

	updateTargetIndicatorText();
	
	$('a#targetChanger').click(	function()
									{
										blank = (blank==1) ? 0 : 1;
										$('div#readbox a').each(function()
																		{
																			$(this).attr('target',targetA[blank]);
																		});
										updateTargetIndicatorText();
										$(this).blur();
										return false;
									}
								);

	// -----------------------------------------------------------------
	// - [LISTE DE LIENS] Anti phishing

	$('div#readbox a strong').css('font-weight', 'normal');
	$('div#readbox a').hover(function()
							{
								$(this).find('strong').addClass('active')
								$(this).find('span').addClass('active')
							},
							function()
							{
								$(this).find('strong').removeClass()
								$(this).find('span').removeClass()
							});
	

	// -----------------------------------------------------------------
	// - [FORM EDITION] "Supprimer le texte"
	$('a#prune_now').click ( function()
								{
									if(!confirm('Cette action est irréversible !\nÊtes-vous sûr de vouloir supprimer le texte ?'))
									{
										$(this).parent().hide();
									}
									else
									{
										return true;
									}
									$(this).blur();
									return false;
								} );

	// -----------------------------------------------------------------
	// [READBOX BBCODE] Balise spoiler

	/*
	var revealed_count = 0;
	var total_count = $('div#readbox.bbcode span.bbcode_spoiler_bloc').size();
	$('div#readbox.bbcode span.bbcode_spoiler_bloc span.bbcode_spoiler_link').each(spoilerMinimize);
	function spoilerMinimize()
	{
		$(this).parent().parent().find('.bbcode_spoiler').hide();
		$(this).parent().parent().find('.bbcode_spoiler_link').empty()
											.append($('<a href="#" title="Cliquez pour réveler." class="bbcode_spoiler_warning" />')
											.text('[ Réveler le spoiler ]')
											.click(spoilerReveal)
													);
		return false;
	}

	function spoilerReveal()
	{
		$(this).parent().parent().find('.bbcode_spoiler').show();
		$(this).parent().parent().find('.bbcode_spoiler_link').empty()
											.prepend($('<a href="#" class="bbcode_spoiler_minimize" />')
											.text(' - Cacher le spoiler')
											.click(spoilerMinimize)
													);


		return false;
	}

	// todo lien réveler spoiler si span.bbcode existe

	if ($('div#readbox.bbcode span.bbcode_spoiler').size()>0)
	{
		$('p#spoiler_warning').fadeIn(1000).find('a#reveler_tout').click(
													function()
													{
														$('div#readbox.bbcode span.bbcode_spoiler_bloc a.bbcode_spoiler_warning').each( function() { $(this).triggerHandler('click'); } );
														$(this).parent().fadeOut() // parent() = span
																	   .queue(function()
																			  {
																			  $(this).remove();
																			  });
														return false;
													});


		$('p#spoiler_warning a#close').click(function()
											 {
												$(this).parent().fadeOut() // parent() = span
																	   .queue(function()
																			  {
																			  $(this).remove();
																			  });
												return false;
											 }
											);								
	}
*/

	$('div.bbcode_spoiler p.bbcode_text').hide();
	$('div.bbcode_spoiler p.bbcode_sub a').click(function(){
													$(this).parent().parent().find('p.bbcode_text').slideToggle();
													if ($(this).text()==='Cacher')
														$(this).text('Réveler');
													else
														$(this).text('Cacher');
													
													$(this).blur();
													return false;
												});

	// -----------------------------------------------------------------
	// [READBOX] Textinfo

	$('div#textinfo_and_bait').height(22);
	$('div#textinfo_and_bait p#textinfo').css({  position: 'absolute', display: 'block' });

	var hiddenTop=-$('#textinfo').outerHeight(true);
	$('#textinfo_and_bait #textinfo').css('top',hiddenTop)
	$('#textinfo_and_bait #bait, #textinfo_and_bait #textinfo').hover(showInfo,hideInfo)

	function showInfo()
	{
		$('#textinfo_and_bait #textinfo').stop().animate({ top : 0});
	}

	function hideInfo()
	{
		$('#textinfo_and_bait #textinfo').stop().animate({ top : hiddenTop});
	}

	// $('#textinfo_and_bait #bait').mouseOut(function(){$(this).parent().append('l');});

	// - Submit text et bbcode !
			
}) // document.ready

