//------------------------------------------------------------------//
//													 				//
//					 		ajaxPopup			 					//
//													 				//
//------------------------------------------------------------------//
// Date de création					: 13/03/2008					//
// Dernière modification 			: 16/04/2008					//
// Auteur 							: Johan Leche					//
// Propriétaire						: Keyrio SARL					//
// Contact							: j.leche@keyrio.fr				//
// Web								: http://www.keyrio.fr			//
//------------------------------------------------------------------//
//																	//
// Dépendances :			- prototype.js 			version 1.6		//
// 							- scriptaculous.js						//
// 							- ajaxpopup.css 						//
//------------------------------------------------------------------//

var aoInstance 		= new Array();
var asTriggersId 	= new Array();
var asPopupStatus 	= new Array();

// lazyInit
function lazyInit(psInstancename, psParams, psTriggerId)
{
	Event.observe(
		psTriggerId,
		'click',
		function()
		{
			if (asTriggersId.indexOf(psTriggerId) == -1)
			{
				var oParams 						= psParams;
				aoInstance[aoInstance.length] 		= new AjaxPopup(oParams);
				asTriggersId[aoInstance.length]		= psTriggerId;
			}	
		}
	);
}


function closeInstances()
{
	var i=0;
	var nLength = aoInstance.length;
	
	
	for(i=0; i<nLength; i++)
	{	
		if (aoInstance[i].getPopupStatus())
		{
			if (aoInstance[i].m_sId)
			{
				$(aoInstance[i].m_sId).hide();
				
				if ($(aoInstance[i].m_sId + '_blackscreen'))
					$(aoInstance[i].m_sId + '_blackscreen').hide();
			}	
				
			asTriggersId.without(aoInstance[i].m_sTrigger);
		}	
	}
}


AjaxPopup = Class.create();

AjaxPopup.prototype = 
{
	initialize: function(params)
	{
		// declencheur
		this.m_sTrigger						= params.sTrigger;
		this.m_sTriggerAction				= params.sTriggerAction 			|| 'click';					
		
		// paramètres du composant
		this.m_sId							= params.sPopupId 					|| 'id_' + Math.ceil(Math.random());
		
		// parametres popup principale
		this.m_sPopupStyle 					= params.sPopupStyle 				|| 'ajax_popup_basic';
		this.m_nPopupWidth					= params.nPopupWidth 				|| 350;
		this.m_nPopupHeight					= params.nPopupHeight 				|| 250;
		this.m_bForceFit					= params.bForceFit 					|| false;
		this.m_nPopupOpacityFrom			= params.nPopupOpacityFrom 			|| 0.0;
		this.m_nPopupOpacityTo				= params.nPopupOpacityTo 			|| 1.0;
		this.m_nPopupEffectDuration			= params.nPopupEffectDuration 		|| 1.5;
		
		// parametres barre de titre
		this.m_sTBarStyle					= params.sBarStyle 					|| 'ajax_popup_tbar';
		this.m_bHaveTBar					= params.bHaveTitleBar 				|| false;
		this.m_sTBarLabel					= params.sTitleLabel 				|| 'Ajax popup';
		this.m_sTBarLabelStyle				= params.sBarTitleStyle 			|| 'ajax_popup_tbar_title';
		this.m_sCloseButtonStyle			= params.sCloseButtonStyle			|| 'ajax_popup_close';
		this.m_bHaveCloseButton				= params.bHaveCloseButton			|| true;
		
		this.m_bCloseOnButtonOnly		 	= params.bCloseOnButtonOnly 		|| false;
		
		// paramètres barre du bas
		this.m_sBottomBarStyle				= params.sBottomBarStyle			|| 'ajax_popup_bbar';
		this.m_bHaveBottomBar				= params.bHaveBottomBar 			|| false;
		this.m_sSubmitButtonStyle			= params.sSubmitButtonStyle 		|| 'ajax_popup_bbar_submit';
		this.m_sCancelButtonStyle			= params.sCancelButtonStyle 		|| 'ajax_popup_bbar_cancel';
		
		this.m_bIsForm						= params.bIsForm					|| false;
		
		this.m_bIsDraggable		 			= params.bIsDraggable 				|| false;
		
		// parametres contenu popup
		this.m_sContentStyle				= params.sContentStyle 				|| 'ajax_popup_content';
		this.m_bContentIsUrl				= params.bContentIsUrl				|| false;
		this.m_sUrlToLoad					= params.sUrlToLoad					|| 'undefined';
		this.m_sSubmitUrl					= params.sSubmitUrl					|| 'undefined';
		this.m_bReloadContent				= params.bReloadContent				|| false;
		
		// parametres update
		this.m_bUpdateTrigger				= params.bUpdateTrigger				|| false;
		this.m_sIdToUpdate					= params.sIdToUpdate;
		
		this.m_sSaveSuccessTBarStyle		= params.sSaveSuccessTBarStyle		||'ajax_popup_tbar_success';
		
		this.m_sContent						= params.sContent;
		this.m_oContentElement				= params.oContentElement;
		
		// parametres blackScreen
		this.m_sBlackScreenStyle			= params.sBlackScreenStyle 			|| 'ajax_popup_blackscreen';
		this.m_bHaveBlackScreen				= params.bHaveBlackScreen			|| false;
		this.m_nBlackScreenOpacityFrom 		= params.nBlackScreenOpacityFrom 	|| 0.0;		// de 0.0 à 1.0
		this.m_nBlackScreenOpacityTo 		= params.nBlackScreenOpacityTo 		|| 0.75;	// de 0.0 à 1.0
		this.m_nBlackScreenEffectDuration 	= params.nBlackScreenEffectDuration || 1.5;		// en secondes
		
		this.m_bLoadOnStartup 				= params.bLoadOnStartup 			|| false;
		
		// IDs
		this.m_sIdTitleBar					= this.m_sId + '_tbar';
		this.m_sIdBottomBar					= this.m_sId + '_bbar';
		this.m_sIdBlackScreen				= this.m_sId + '_blackscreen';
		this.m_sIdCloseButton				= this.m_sId + '_close';
		this.m_sIdCancelButton				= this.m_sId + '_bbar_cancel';
		this.m_sIdSubmitButton				= this.m_sId + '_bbar_submit';
		this.m_sIdForm						= this.m_sId + '_form';
		this.m_sIdBody						= document.body.id;

		if (!this.m_sIdBody)
		{
			document.body.id = 'body';
			this.m_sIdBody = document.body.id;
		}	
		
		this.m_oPopup;
		this.m_oTopBar;
		this.m_oBottomBar;
		this.m_oSubmitButton;
		this.m_oCancelButton;
		this.m_oForm;
		this.m_oContent;
		this.m_oBlackScreen;
		this.m_oCloseButton;
		
		this.m_bPopupIsActive				= false;
		this.m_bPopupIsBuilt				= false;
		this.m_nFalseClick					= 0;
		this.m_nBlackScreenBuilt 			= false;
		
		// on construit les éléments 	
		if (!this.m_bPopupIsBuilt)	
			this.buildPopup();
		
		// on lance les listeners
		this.initEvents();
		
		
		if (this.m_bHaveBlackScreen)
		{
			while (!this.m_nBlackScreenBuilt)
			{
				alert('bs pas ok');
			}	
		}
		
		if (this.m_bLoadOnStartup)
			this.launchPopup();
	},
	
	
	getPopupStatus: function()
	{
		return this.m_bPopupIsActive;
	},
	
	
	buildPopup: function()
	{
		this.m_oPopup 			= new Element('div', {'id': this.m_sId, 'class': this.m_sPopupStyle}).hide();
		
		this.buildTopBar();
		this.buildContent();	
		this.buildBottomBar();
		this.buildBlackScreen();
		this.collatePopup();
		
		this.applyPositionement();
	},

	
	getAjaxContent: function()
	{
		var self = this;
		
		if (!this.m_sUrlToLoad)
			alert('Aucune URL spécifiée !');
		else
		{
			new Ajax.Request
			(	
				this.m_sUrlToLoad, 
				{
					onSuccess: function(transport) 
					{
						self.m_sContent = transport.responseText;
			  		},
			  		asynchronous: false,
			  		evalJS: true
				}
			); 		
		}			
	},
	
	
	collatePopup: function()
	{
		if (this.m_bHaveTBar)
		{
			this.m_oPopup.appendChild(this.m_oTopBar);
		}
		else if (this.m_bHaveCloseButton)
		{
			this.m_oPopup.appendChild(this.m_oCloseButton);
		}
		
		this.m_oPopup.appendChild(this.m_oContent);
		
		if (this.m_bHaveBottomBar)
		{
			this.m_oPopup.appendChild(this.m_oBottomBar);
		}
		
		var oBody = document.body;
		
		
		
		oBody.appendChild(this.m_oPopup);
		
		if (this.m_bHaveBlackScreen)
		{
			oBody.appendChild(this.m_oBlackScreen);
		}	
		
		//draggable
		if (this.m_bIsDraggable	)
			new Draggable(this.m_sId);
	},
	
	
	buildTopBar: function()
	{
		// bouton fermer
		var oCloseButton 	= new Element('div', {'class':  this.m_sCloseButtonStyle, 'id': this.m_sIdCloseButton});
		
		if (this.m_bHaveTBar)
		{
			this.m_oTopBar	 	= new Element('div', {'class': this.m_sTBarStyle, 'id': this.m_sIdTitleBar});
			var oTable 			= new Element('table', {'width': '100%', 'cellspacing': 0, 'cellpadding': 0});
			var oTBody			= new Element('tbody');
			var oTr				= new Element('tr');
			var oCellTitle		= new Element('td');
			var oCellButton		= new Element('td');
			
			// titre de la popup
			var oBarTitle		= new Element('div', {'class': this.m_sTBarLabelStyle}).update(this.m_sTBarLabel);
			
			// assemblage
			
			oCellButton.appendChild(oCloseButton);
			oTr.appendChild(oCellButton);
			
			oCellTitle.appendChild(oBarTitle);
			oTr.appendChild(oCellTitle);
			
			oTBody.appendChild(oTr);
			
			oTable.appendChild(oTBody);
			
			this.m_oTopBar.appendChild(oTable);
		}
		else if (this.m_bHaveCloseButton)
		{
			this.m_oCloseButton = oCloseButton;
		}
	},
	
	
	buildContent: function(pbReload)
	{
		if (pbReload)
		{
			this.getAjaxContent();
			this.m_oContent.update(this.m_sContent);
		}
		else if (this.m_oContentElement)
		{
			this.m_oContent = new Element('div', {'class': this.m_sContentStyle});	
			this.m_oContent.appendChild(this.m_oContentElement);
		}
		else
		{
			if (this.m_bContentIsUrl)
				this.getAjaxContent();
			
			this.m_oContent = new Element('div', {'class': this.m_sContentStyle});	
				
			if (this.m_bIsForm)
			{
				this.m_oForm = new Element('form', {'id': this.m_sIdForm, 'method': 'post', 'action': this.m_sSubmitUrl});
				
				this.m_oForm.update(this.m_sContent);
				this.m_oContent.appendChild(this.m_oForm);
			}		
			else
				this.m_oContent.update(this.m_sContent);
		}		
	},
	
	
	buildBottomBar: function()
	{
		if (this.m_bHaveBottomBar)
		{
			// boutons
			var oCancelButton 	= new Element('div', {'class':  this.m_sCancelButtonStyle, 'id': this.m_sIdCancelButton}).update('Cancel');
			var oSubmitButton 	= new Element('div', {'class':  this.m_sSubmitButtonStyle, 'id': this.m_sIdSubmitButton}).update('Submit');
			
			this.m_oBottomBar	= new Element('div', {'class': this.m_sBottomBarStyle, 'id': this.m_sIdBottomBar});
			var oTable 			= new Element('table', {'width': '100%', 'cellspacing': 0, 'cellpadding': 0});
			var oTBody			= new Element('tbody');
			var oTr				= new Element('tr');
			var oCellSubmit		= new Element('td');
			var oCellCancel		= new Element('td');
			
			// assemblage
			oCellCancel.appendChild(oCancelButton);
			oTr.appendChild(oCellCancel);
			
			oCellSubmit.appendChild(oSubmitButton);
			oTr.appendChild(oCellSubmit);
			
			oTBody.appendChild(oTr);
			oTable.appendChild(oTBody);
			
			this.m_oBottomBar.appendChild(oTable);
		}
	},
	
	
	buildBlackScreen: function()
	{
		if (this.m_bHaveBlackScreen)
		{
			this.m_oBlackScreen = new Element('div', {'class': this.m_sBlackScreenStyle, 'id': this.m_sIdBlackScreen}).hide();
			this.m_oBlackScreen.style.zIndex = 500;
			this.m_nBlackScreenBuilt = true;
		}	
	},
	
	
	changePopupStatus: function(pbStatus)
	{
		this.m_bPopupIsActive = pbStatus;
	},
	
	
	runBlackScreen: function()
	{
		if (this.m_bHaveBlackScreen)
		{
			
			var nTopPosition = window.pageYOffset || document.documentElement.scrollTop || 0; 
			var nLeftPosition = window.pageXOffset || document.documentElement.scrollLeft || 0;
			
			
			this.m_oBlackScreen.style.top = nTopPosition + 'px';
			this.m_oBlackScreen.style.left = nLeftPosition + 'px';
//			$(this.m_sIdBody).style.overflow = 'hidden';
			
			Effect.Appear(this.m_sIdBlackScreen, { duration: this.m_nBlackScreenEffectDuration, from: this.m_nBlackScreenOpacityFrom, to: this.m_nBlackScreenOpacityTo});	
		}
	},
	
	
	removeBlackScreen: function()
	{
		if (this.m_bHaveBlackScreen)
		{
			this.m_oBlackScreen.hide();
			this.m_nBlackScreenBuilt = false;
			$(this.m_sIdBody).style.overflow = 'auto';
		}	
	},
	
	
	runPopup: function()
	{
		var nTopPosition 	= window.pageYOffset || document.documentElement.scrollTop || 0; 
		var nLeftPosition 	= window.pageXOffset || document.documentElement.scrollLeft || 0;
		
		var nScreenWidth 	= document.viewport.getDimensions().width;
		var nScreenHeight 	= document.viewport.getDimensions().height;
		
//		alert(nTopPosition +' x ' + nLeftPosition);
//		alert(nScreenWidth +' x ' + nScreenHeight);
		
//		alert(this.m_oPopup.style);
//			
		this.m_oPopup.style.top 	= nTopPosition + (nScreenHeight / 2) + 'px';
		this.m_oPopup.style.left 	= nLeftPosition + (nScreenWidth / 2) + 'px';
//		
//		window.scrollTo(nTopPosition, nLeftPosition);
		
		Effect.Appear(this.m_sId, { duration: this.m_nPopupEffectDuration, from: this.m_nPopupOpacityFrom, to: this.m_nPopupOpacityTo});	
	},
	
	
	removePopup: function()
	{
		$(this.m_sId).hide();
	},
	
	
	launchPopup: function()
	{
		closeInstances();
		this.runPopup();
		this.runBlackScreen();
		this.m_bPopupIsActive = true;
	},
	
	
	hidePopup: function()
	{
		this.m_bPopupIsActive = false;
		this.removeBlackScreen();
		this.removePopup();
		this.m_nFalseClick = 0;
	},
	
	
	initEvents: function()
	{
		var self = this;
		Event.observe(
			self.m_sTrigger,
			self.m_sTriggerAction,
			function()
			{
				self.launchPopup();
			}	
		);
		
		if(this.m_bCloseOnOutsideClick)
		{
			Event.observe(
				self.m_sIdBody,
				'click',
				function()
				{
					if (self.m_bPopupIsActive)
					{
						if (self.m_nFalseClick > 1)
						{
							self.hidePopup();
						}
						
						self.m_nFalseClick++;
					}
				}
			);
		}
		
		
		if (this.m_bHaveTBar || this.m_bHaveCloseButton)
		{
			Event.observe(
				self.m_sIdCloseButton,
				'click',
				function()
				{
					if (self.m_bPopupIsActive)
					{
						self.hidePopup();
					}
				}
			);
		}
		
		
		if(this.m_bIsForm)
		{
			Event.observe(
				self.m_sIdCancelButton,
				'click',
				function()
				{
					if (self.m_bPopupIsActive)
					{
						self.hidePopup();
					}
				}
			);
//			
			Event.observe(
				self.m_sIdSubmitButton,
				'click',
				function()
				{
					if (self.m_bPopupIsActive)
					{
						self.submitForm(self.getFormFields(self.m_oForm));
					}
				}
			);
		}
	},
	
	
	getFormFields: function(poElement)
	{
      	var getstr = "?";
      
      	var sResult = '';
      
		var oForm = $(this.m_sIdForm);
		
		var nLength = oForm.elements.length;
		
		for(var i=0; i< nLength; i++)
		{
			if (oForm.elements[i].tagName == "INPUT") 
			{
		       	if (oForm.elements[i].type == "text" || oForm.elements[i].type == "hidden" || oForm.elements[i].type == "password") 
		    		sResult += oForm.elements[i].name + "=" + oForm.elements[i].value + "&";
		            
		        if (oForm.elements[i].type == "checkbox") 
		        {
		          	if (oForm.elements[i].checked) 
		               	sResult += oForm.elements[i].name + "=" + oForm.elements[i].value + "&";
		        	else 
		        		sResult += oForm.elements[i].name + "=&";
		        }
		            
		        if (oForm.elements[i].type == "radio") 
		        {
	        		if (oForm.elements[i].checked) 
	        			sResult += oForm.elements[i].name + "=" + oForm.elements[i].value + "&";
		        }
		    }   
		    
		         
		    if (oForm.elements[i].tagName == "SELECT") 
		    {
		    	var asOptions 	= oForm.elements[i].options;
		    	var nOLength 	= oForm.elements[i].options.length;

		    	var sOptions = oForm.elements[i].name + '=';
		    	   	
		    	for (var j=0; j<nOLength; j++)
		    	{
		    		if (asOptions[j].selected)
		    		{
		    			if (asOptions[j].value != 0)
		    				sOptions += asOptions[j].value + "-";
		    		}
		    	}
		    	
		    	sResult += sOptions + "&";
		   	}
		}

		return sResult;
	},
	
	
	submitForm: function(psResult)
	{
		var self = this;
		
		new Ajax.Request
			(	
				self.m_sSubmitUrl, 
				{
					onSuccess: function(transport) 
					{
						self.handleSubmissionSuccess(transport);
			  		},
			  		asynchronous: false,
			  		evalJS: true,
			  		parameters: psResult
				}
			); 	
	},
	
	
	handleSubmissionSuccess: function(psTransport)
	{
		// changement classe tbar
		if (!this.m_bUpdateTrigger)
		{
			this.m_oTopBar.removeClassName(this.m_sTBarStyle);
			this.m_oTopBar.addClassName(this.m_sSaveSuccessTBarStyle);
		}	

		// action reload ou close
		if (this.m_bReloadContent)
		{
			this.buildContent(true); // reload = true
		}	
		else if (this.m_bUpdateTrigger)	
		{
			$(this.m_sIdToUpdate).innerHTML = psTransport.responseText;
			this.hidePopup();
		}	
		else
		{
			this.hidePopup();
		}	
	},
	
	
	applyPositionement: function()
	{
		this.m_oPopup.style.position 		= 'absolute';
		this.m_oPopup.style.left 			= '50%';
		this.m_oPopup.style.top 			= '50%';
		this.m_oPopup.style.marginLeft		= (this.m_nPopupWidth / 2) * -1 + 'px';
		this.m_oPopup.style.marginTop		= (this.m_nPopupHeight / 2) * -1 + 'px';
		this.m_oPopup.style.width			= this.m_nPopupWidth + 'px';
		this.m_oPopup.style.height			= this.m_nPopupHeight + 'px';
		this.m_oPopup.style.zIndex			= 1000;
	}
}