function stopEvent(e) 
{
	var event = e || window.event;
	if (event.stopPropagation) {
		event.stopPropagation();
	} 
	else 
	{
		event.cancelBubble = true;
	}
	event.returnValue=false;
	return false;
}
      
function RGBtoHex(rgb_string)
{
	if (rgb_string.charAt(0) == '#') {
	  return rgb_string;
	} else
	if (rgb_string.substring(0,3)=='rgb')
	{
	  re = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/;
	  parsed = re.exec(rgb_string);
	  return (parsed[1]*0x010000+ parsed[2]*0x000100+
	    parsed[3]*0x000001 + 0x1000000).toString(16).substring(1,7);
	}
}

function HextoRGB(hex_string)
{
	var triplet = hex_string.toLowerCase().replace(/#/, '');
	if(triplet.length == 6)
	{
		return 'rgb('+parseInt(triplet.substr(0,2), 16)+','+parseInt(triplet.substr(2,2), 16)+','+parseInt(triplet.substr(4,2), 16)+')';
	}
	else if(triplet.length == 3)
	{
		return 'rgb('+parseInt((triplet.substr(0,1) + triplet.substr(0,1)), 16)+','+parseInt((triplet.substr(1,1) + triplet.substr(1,1)), 16)+','+parseInt((triplet.substr(2,2) + triplet.substr(2,2)), 16)+')';
	}else{
		return hex_string;
	}
}

function dspOverlay(obj_todisplay, hexa_overlaycolor, txt_to_add,num_bloc) {

	var overlaycolor = hexa_overlaycolor || 'rgb(0,0,0)';
	var txt_to_add = txt_to_add || '';
	var num_bloc = num_bloc || '';
	if($('overlay'))
	{
		$('overlay').style.backgroundColor = '#'+overlaycolor;
		$('overlay').style.display = 'block';
		if(obj_todisplay && $('popup'))
		{
			$('popup').update();			
			var copy_obj = obj_todisplay.cloneNode(true);
			
			/*ICIIMAGE*/
			var srcimg = obj_todisplay.value;
			var createimage = document.createElement('img');
			createimage.src = srcimg;
			createimage.id = 'large_'+copy_obj.id;
			createimage.className = copy_obj.className;
			
			copy_obj.style.display = 'block';
			
			//var contentW = obj_todisplay.getWidth();
			//var contentH = obj_todisplay.getHeight();
			/*ICIIMAGE*/
			var contentW = $("width_"+copy_obj.id).value;
			var contentH = $("height_"+copy_obj.id).value;
			
			var scr = document.viewport.getDimensions();
			var screenW = scr.width;
			var screenH = scr.height;
			var posL = Math.round((screenW - contentW) / 2);
			var posT = Math.round((screenH - contentH) / 2);
			var txtpresent = false;
			var nextflech = false;
			var prevflech = false;
			var result_next = "";
			var result_prev = "";
			
			$('popup').style.marginLeft = posL+"px";
			$('popup').style.marginTop = posT+"px";
			$('popup').style.width = contentW+"px";
			$('popup').style.height = contentH+"px";
			
			//$('popup').update(copy_obj);
			/*ICIIMAGE*/
			$('popup').update(createimage);
			
/*
 * 			Supression des boutons prev next mais le comportement reste inchanger (clic sur l'image = clic sur le bouton next)
 */
  			result_next = getDefilImage(obj_todisplay.id,1);
			if(result_next != "")
			{
				var flechenext = document.createElement('a');
				flechenext.id = 'flechenext';
				flechenext.className = 'goto_'+result_next+'_'+num_bloc+'_'+hexa_overlaycolor;
				nextflech = true;
			}
			
/*
 * 			Script with btn next 
 * 
			result_prev = getDefilImage(obj_todisplay.id,-1);
			if(result_prev != "")
			{
				var flecheprev = document.createElement('a');
				flecheprev.id = 'flecheprev';
				flecheprev.className = 'goto_'+result_prev+'_'+num_bloc+'_'+hexa_overlaycolor;
				prevflech = true;
			}
*/		
			if(txt_to_add != '')
			{
				if(!$('popuptxt'))
				{
					var msgtxt = document.createElement('div');
					msgtxt.id = 'popuptxt';
					msgtxt.style.display = 'none';
				}

				if(msgtxt)
				{
					msgtxt.update(txt_to_add);
					txtpresent = true;
				}
			}
			
			if(nextflech){$('popup').appendChild(flechenext)};
			if(prevflech){$('popup').appendChild(flecheprev)};

			if(txtpresent){$('popup').appendChild(msgtxt)};
			
			new Effect.Appear($('popup'), {duration: 0.4, afterFinish: function()
				{
					if($('popuptxt'))
					{
						new Effect.Appear($('popuptxt'), {duration: 0.2});
					}
				}
			});
			Behaviour.apply();
		}
	}
}

function getDefilImage(id_image, sens)
{
	var id_image=id_image||"";
	var sens=sens||1;
	var tab = id_image.split('_');
	var numbloc = tab[2];
	var id_db = tab[1];
	//liste des images
	var liste = $$('.defil_'+numbloc);
	var id_goto = "";
	var tab3 = new Array();
	var tab4 = new Array();
	
	if(liste.length > 1)
	{
		var last_ind = parseInt(liste.length) - 1;;
		var first_ind = 0;
		
		for(var i = 0; i < liste.length; i++)
		{
			var tab2 = liste[i].id.split('_');
			var curr_imgid = tab2[1];
		
			if(curr_imgid == id_db)
			{
				//On recule (precedent)
				if(sens == -1)
				{
					if(i == 0)
					{
						//On repart du dernier element
						tab3 = liste[last_ind].id.split('_');
						id_goto = tab3[1];
					}else{
						if(i > 0)
						{
							//On prend le precedent
							tab3 = liste[i-1].id.split('_');
							id_goto = tab3[1];
						}
					}
				}
				else if(sens == 1)
				{
					
					//On avance (suivant)
					if(i == last_ind)
					{
						//On repart du premier si on est au dernier
						tab4 = liste[first_ind].id.split('_');
						id_goto = tab4[1];
					}else{
						if(i < last_ind)
						{
							//On prend le suivant
							tab4 = liste[i+1].id.split('_');
							id_goto = tab4[1];
						}
					}
				}
			}
		}
		return id_goto;
	}else{
		return "";
	}
}
function doDisplayImgBloc(num_bloc, curr_txt_bloc, no_rules_reapply)
{
		new Effect.Appear($(curr_txt_bloc), {duration: 0.2, afterFinish: function()
		{
			//$('txtdisplayed_'+num_bloc).value = '1';
			//Et on affiche les images
			if(no_rules_reapply == false)
			{
				displayImgBloc(num_bloc);
			}else{
				displayImgBloc(num_bloc, true);
			}
			//Affiche la scroll bar
			start_scrollBar("form"+num_bloc);
		}});
}

function displayImgBloc(numbloc, no_btn_close)
{
	var no_btn_close = no_btn_close || false;
	var contents = $$('#bloc_'+numbloc+' .otherimg');
	contents.each(function(c,i) {
		new Effect.Appear(c, {duration: 0.2,	queue: 'end',afterFinish:function(){
			if(i == (contents.length-1))
			{
				if(no_btn_close == false)
				{
					new Effect.Appear($('btnclose_'+numbloc));
				}
			}
		}});
	});
}

function fadeImgBloc(numbloc)
{
	var contents = $$('#bloc_'+numbloc+' .otherimg');
	contents.sort(function() {return 0.5 - Math.random()})
	contents.each(function(c) {
		new Effect.Fade(c, {duration: 0.1,	queue: 'end'});
	});
}

function fadeCloseBtn(numbloc)
{
	new Effect.Fade($('btnclose_'+numbloc), {afterFinish: function(){
    //Appear 0% puce
  	if($('pastille_energie_' + numbloc))
  		new Effect.Appear($('pastille_energie_'+numbloc), {duration: 0.2});
   }});
}

function clicBloc(img_id, no_rules_reapply)
{
	var no_rules_reapply = no_rules_reapply || false;
	var timg = img_id.replace('img_','trueimg_');
	var txttimg = img_id.replace('img_','txtimg_');
	var tabs = img_id.split('_');
	var num_bloc = tabs[2]; //1 => identifiant de l'image	
	if(!num_bloc)
	{
		//on est sur la premiere image d'un bloc focus
		num_bloc = tabs[1];
	}
	var color = 'C0C0C0';
	var continu = false;
	var txtdisp = 'txtdisplayed_'+num_bloc;
	var couleur_popup = 'popupcouleur_'+num_bloc
	var curr_txt_bloc = 'txtcontenu_'+num_bloc;
	var curr_bloc = 'bloc_'+num_bloc;


	// Couleur de fond du pop up
	if($(couleur_popup))
	{
		color = $(couleur_popup).value;
	}else{
		color = '000000';
	}
	
	// Le texte est deja affiché
/*	if($(txtdisp))
	{
		if($(txtdisp).value == '0')
		{
			continu = true;
		}
	}else{
		continu = true;
	}*/
	
	
//	if(continu)
	if($(curr_txt_bloc) && $(curr_txt_bloc).style.display=="none")
	{
		if($(curr_txt_bloc))
		{
	      	//Fade 0% puce
	    	if($('pastille_energie_' + num_bloc))
			{
		      	new Effect.Fade($('pastille_energie_'+num_bloc), {duration:0.2,afterFinish: function(){
		          doDisplayImgBloc(num_bloc, curr_txt_bloc, no_rules_reapply);
		      	}});
		    }
		    else
		    	doDisplayImgBloc(num_bloc, curr_txt_bloc, no_rules_reapply);
		}else{
			if($(timg))
			{
				if($(txttimg))
				{
					dspOverlay($(timg),color,$(txttimg).value,num_bloc);
				}else{
					dspOverlay($(timg), color,num_bloc);
				}
			}
		}
	}else{
		if($(curr_bloc))
		{
			if($(timg))
			{
				if($(txttimg))
				{
					dspOverlay($(timg),color,$(txttimg).value,num_bloc);
				}else{
					dspOverlay($(timg), color,num_bloc);
				}
			}
		}
	}
}

function clicBlocFocus(foc_id, no_rules_reapply)
{
	var no_rules_reapply = no_rules_reapply || false;
	var num_bloc = foc_id.replace('firstimgfocus_','')
	$('firstimg_'+num_bloc).style.display = 'block';
	$(foc_id).update("");
	$(foc_id).remove();
	//$('firstimg_'+num_bloc).style.display = 'block';
	new Effect.Appear($('txt_'+num_bloc), {duration: 0.2, afterFinish: function()
	{
		if($('spacer_'+num_bloc))
		{
			$('spacer_'+num_bloc).style.display = 'block';
		}
		new Effect.Appear($('txtcontenu_'+num_bloc), {duration: 0.2, afterFinish: function()
		{
			//$('txtdisplayed_'+num_bloc).value = '1';
			//Et on affiche les images
			if(no_rules_reapply == false)
			{
				displayImgBloc(num_bloc);
				Behaviour.apply();
			}else{
				displayImgBloc(num_bloc, true);
			}
		}});
	}});
}

var myrules = {
	'.trueimg' : function(image)
	{
		var timg = "";
		var color = "";
		var txt = "";
		var tab = new Array();
		var idimg = "";
		image.onclick = function()
		{
			var suivant = $('flechenext');
			if(suivant)
			{
  			tab = suivant.className.split('_');
  			idimg = 'trueimg_'+tab[1]+'_'+tab[2];
  			txtimg = 'txtimg_'+tab[1]+'_'+tab[2];
  			dspOverlay($(idimg),tab[3],$(txtimg).value,tab[2]);
	      }	
		}
	},

	'#openall' : function(autoopenbloc)
	{
		var blocs = $$('div[id^="bloc_"]');
		var imgsfocus = new Array();
		var imgsnormal = new Array();
		var reglefocus = "";
		var reglenormal = "";

		//alert("Nombre de bloc : "+blocs.length);
		for(var ibloc = 0; ibloc < blocs.length; ibloc++)
		{
			reglefocus = '#'+blocs[ibloc].id+' div.firstimgfocus';
			reglenormal = '#'+blocs[ibloc].id+' div.firstimg';

			imgsfocus = $$(reglefocus);
			imgsnormal = $$(reglenormal);
			for(var ifoc = 0; ifoc < imgsfocus.length; ifoc++)
			{
				//alert("Clic bloc focus : "+imgsfocus[ifoc].id);
				clicBlocFocus(imgsfocus[ifoc].id, true);
			}

			for(var inorm = 0; inorm < imgsnormal.length; inorm++)
			{
				//alert("Clic bloc : "+imgsnormal[inorm].id);
				clicBloc(imgsnormal[inorm].id, true);
			}
		}
	},
	
	'.btnclose': function(bc)
	{
		bc.onclick = function()
		{
			var num_bloc = bc.id.replace('btnclose_','');
			var curr_txt_bloc = 'txtcontenu_'+num_bloc;
			if($(curr_txt_bloc))
			{
				fadeCloseBtn(num_bloc);
				new Effect.Fade($(curr_txt_bloc), {duration: 0.2, queue: 'end', afterFinish: function()
					{
	
						//$('txtdisplayed_'+num_bloc).value = '0';
						fadeImgBloc(num_bloc);
						//On restaure la class du bloc
						if($('bloc_' + num_bloc))
							$('bloc_' + num_bloc).className += " blocopen";
					}
					});
			/* SIFR_apply(); */
			}	
			stop_scrollBar("form"+num_bloc);
		}
	},
	
	'.blocimg': function(img)
	{
		img.onclick = function(event)
		{
			// Clic sur une image
			// Si le texte est affiché on lance les popup
			// sinon on commence par afficher le texte
			if($(img.id.replace('img_','fichierimg_')))
			{
				//Il y a un fichier joint	
			}else{
				//On change la class du bloc
				clicBloc(img.id);
				if(img.className.indexOf("gmap_img")==-1)
				{
					//Annul event propagation
					var event = event || window.event;
				    if (event.cancelBubble)
				      event.cancelBubble = true;
				    else
				      event.stopPropagation();
				}
			}
		}
	},
	
	'.blocopen': function(div)
	{
		div.onclick = function()
		{
			var tab = div.id.split("_");
			var index = tab[1];
			// Clic sur une image
			// Si le texte est affiché on lance les popup
			// sinon on commence par afficher le texte
			if($('fichierimg_' + index))
			{
				//Il y a un fichier joint	
			}else{
				//On change la class du bloc
				div.className = div.className.replace(" blocopen","");
				clicBloc("img_" + index);
			}
		}
	},
	
	'.firstimgfocus': function(foc)
	{
		foc.onclick = function()
		{
			// Clic sur l'image de focus
			// Si le texte est affiché on lance les popup
			// sinon on commence par afficher le texte
			clicBlocFocus(foc.id);
		}
	},
		
	'#overlay' : function(bc)
	{
		//
		// Clic sur le popup = fermeture
		bc.onclick = function()
		{
			bc.style.display = "none";
			$('popup').style.display = "none";
			$('popup').update();
		}
	},
	
	'.popupcontact' : function(pc)
	{
		// Clic sur un bloc qui est celui de contact, ouverture du popup
		pc.onclick = function()
		{
			var tab = pc.id.split('_');
			var site_name = tab[0];
			new Ajax.Request(urlaff, {
				asynchronous: 'true',
				postBody: 'tpl='+site_name+'/contact',
				onSuccess: function (ahr)
				{
					$('popup').update(ahr.responseText);
					$('popup').style.display = 'block';
				}
				});	
		}
	},
	
	'.view' : function(vb)
	{
		vb.onclick = function()
		{
			var bloc = vb.id.replace('view_', '');
			if($(bloc))
			{
				if($(bloc).style.display != "none")
					new Effect.Fade($(bloc), {duration:0.2});
				else
					new Effect.Appear($(bloc), {duration:0.2});
			}
		}
	},
	'.stopevent' : function(a)
	{
		a.onclick = function(event)
		{
			stopEvent(event);
		}
	},
	'#affiche_site' : function(s)
	{
		if(s.style.display=="none")
			s.style.display=""
	}
};

// Enregistrement des regles definies ci dessus dans Behaviour
Behaviour.register(myrules);
