/**
 * Gestion des popups du site arcadim
 * @author christian@konfiture.com
 * @depend jquery.arcadim-msg-box.js
 */
(function($)
	{
		$.fn.arcadimPopup = function(params)
			{
				var defaults =
					{
						metaName: 'Formulaire de contact',
						formSuccessMessage: 'Formulaire envoyé avec succès !',
						formSubmitValue: 'Envoyer votre message',
						formResetValue: 'Effacer',
						formSubmitIcon: 'ui-icon-mail-closed',
						formResetIcon: 'ui-icon-arrowreturnthick-1-n',
						popupDefaultIcon: 'ui-icon-check',
						popupDefaultValue: 'Ok',
						onSubmit: basicCheckFields // callback en cas de soumission d'un formulaire
					};

				var params = $.extend( defaults, params );

				var ajaxContentReg = new RegExp('<!--BEGIN:ajax-->([\\S\\s]*?)<!--END:ajax-->');
				var ajaxErrorReg = new RegExp('<!--BEGIN:ajaxError-->([\\S\\s]*?)<!--END:ajaxError-->');

				var dlgDiv = 'popup-dialog';
				var dlgSelector = '#' + dlgDiv;

				this.each(function()
					{
						var self = this;
						if ( self.tagName.toUpperCase().trim() !='A')
							return;

						var rel = $(self).attr('rel');
						if ( rel == undefined || rel == '' )
							return;

						var origTitle = $(self).attr('title');
						if (origTitle != undefined && origTitle != '')
							params.metaName = origTitle;

						var popupConf =
							{
								type: 'undefined',
								title: params.metaName,
								onSubmit: params.onSubmit
							}

						var types = ['contact', 'form', 'popup'];

						for (var x in types)
							if ( rel.startsWith( types[x] + ':' ) )
								popupConf.type = types[x];

						if ( popupConf.type == 'undefined' )
							return;

						var dlgHtml = '<div id="' + dlgDiv + '" class="popup-dialog-' + popupConf.type + '"></div>';

						var origLink = $(self).attr('href');

						$.extend(popupConf,
							{
								arguments: rel.substr(popupConf.type.length + 1),
								dataUrl: origLink + (origLink.indexOf('?') == -1 ? '?source=ajax' : '&source=ajax'),
								width: popupConf.type == 'popup' ? '700px' : '700px'
							});

						var dialogButtons = {};

						switch(popupConf.type)
							{
								case 'popup':
									dialogButtons[params.popupDefaultValue] = function()
										{
											$(this).dialog('close');
										};
									break;

								case 'contact':
								case 'form':
									dialogButtons[params.formSubmitValue] = function()
										{
											var theForm = $(this).find('form').first();
											if (theForm.length == 0)
												return;

											if (popupConf.onSubmit != undefined)
												{
													theForm.append('<input type="hidden" name="source" value="ajax" />');
													var errors = popupConf.onSubmit(this);
													if (errors.length > 0)
														{
															var msgs = new Array();
															theForm.find('input, textarea').removeClass('error');

															$(errors).each( function()
																{
																	msgs.push(this.message);
																	theForm.find('input[name=' + this.name + '], textarea[name=' + this.name + ']')
																		.addClass('error');
																});

															arcadimMsgBox.error({message: msgs.join('</p><p>')});
															theForm.find('.error').first().focus().select();
															return;
														}
												}



											var loadingDlg = arcadimMsgBox.loading({message:'Envoi des donnéees'});

											var postUrl = theForm.attr('action');
											var postData = theForm.serialize();

											$.ajax(
												{
													cache: false,
													type: 'POST',
													url: postUrl,
													dataType: 'text',
													data: postData,
													success: function(data, status, xhr)
														{
															loadingDlg.dialog('close');
															var msg = ''; var isError = false;

															var matches = data.match(ajaxErrorReg);
															if ( matches != null )
																{
																	msg = matches[0];
																	isError = true;
																}

															matches = data.match(ajaxContentReg);
															if ( matches != null )
																msg = matches[0];

															if ( msg == '' )
																msg = params.formSuccessMessage;

															if ( isError )
																arcadimMsgBox.error({message: msg});
															else
																{
																	$(dlgSelector).dialog('close');
																	msg = msg.replace('<!--BEGIN:ajax-->', '');
																	msg = msg.replace('<!--END:ajax-->', '');
																	msg = msg.trim();

																	arcadimMsgBox.show({message: msg});
																	if ( postUrl == '/partager' ){
																		envoiAnalytics('/partage-envoye.html');
																	}
																	else{
																			envoiAnalytics('/mail-envoye.html');
																	}
																}
														},
													error: function(data, status, xhr)
														{
															arcadimMsgBox.error({message:'Le formulaire n\'a pu être envoyé suite à un problème réseau. Vérifiez votre connexion à internet'});
														}
												});
										};

									dialogButtons[params.formResetValue] = function()
										{
											$(this).find('form').get(0).reset();
										};

									break;
								default: // ne devrait pas arriver

							}

						$(self)
							.click(function(event)
								{
									event.preventDefault();

									$(dlgSelector).empty().remove();
									$('body').first().append(dlgHtml);

									$(dlgSelector)
										.css(
											{
												padding: '20px',
												'padding-bottom':0,
												position: 'relative',
												overflow: 'hidden',
												'overflow-y': 'auto',
												width: popupConf.width
											})
										.dialog(
											{
												autoOpen: false,
												width: popupConf.width,
												height: 'auto',
												modal: true,
												show: 'clip',
												hide: 'clip',
												maxHeight: 600,
												title: popupConf.title,
												resizable: false,
												buttons: dialogButtons,
												zIndex: 9999,
												open: function()
													{
														Cufon.refresh();

														$('.ui-dialog-titlebar').find('a')
															.attr('title', 'Fermer la fenêtre')
															.tooltip(tooltipOpts);

														var pane = $(this).parents('.ui-dialog').first().find('.ui-dialog-buttonpane');

														switch (popupConf.type)
															{
																case 'popup':
																	pane.find('button:contains("' + params.popupDefaultValue + '")')
																		.button(
																			{
																				icons: { primary: params.popupDefaultIcon }
																			});
																	break;

																case 'form':
																case 'contact':
																	pane.find('button:contains("' + params.formSubmitValue + '")')
																		.button(
																			{
																				icons: { primary: params.formSubmitIcon }
																			});

																	pane.find('button:contains("' + params.formResetValue + '")')
																		.button(
																			{
																				icons: { primary: params.formResetIcon }
																			});
																default:
															}
													}
											})
									; // $(dlgSelector)

									var msgLoading = arcadimMsgBox.loading({message: 'Chargement'});
									var errorMsg = 'Le formulaire de n\'a pu être chargé.<br />Vérifiez votre connexion internet et rééssayéz. Vous pouvez aussi essayer  de vous rendre directement sur la <a href="' + origLink + '">page ' + popupConf.title + '</a>';

									$.ajax(
										{
											cache: false,
											type: 'GET',
											url: popupConf.dataUrl,
											dataType: 'text',
											success: function(data, status, xhr)
												{
													msgLoading.dialog('close');
													var matches = data.match(ajaxContentReg);
													if ( matches != null )
														{
															var html = matches[0];
															var dlg = $(dlgSelector);
															dlg.html(html).find('fieldset.actions').remove();
															dlg.dialog('open');
															envoiAnalytics(popupConf.dataUrl);
														}
													else
														arcadimMsgBox.error({message:errorMsg});
												},
											error: function(data, status, xhr)
												{
													msgLoading.dialog('close');
													arcadimMsgBox.error({message:errorMsg});
												}

										});

								})
						;

					});
			};
	})(jQuery);

function basicCheckFields(dialog)
	{

		var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var theForm = $(dialog).find('form').first();

		if (theForm.length == 0)
			return false;

		var errors = new Array();
		theForm.find('input, textarea').each(function()
			{
				var name = $(this).attr('name').toLowerCase();
				var title = $(this).attr('title');
				var val = $(this).val().trim();
				var isMandatory = $(this).attr('rel') != 'facultatif';

				if ( val == '' && isMandatory )
					errors.push(
						{
							name: name,
							message: (title ? title : name) + ' est un champ obligatoire.'
						});

				if ( val != '' && name.indexOf('email') != -1 && ! emailReg.test(val) )
					errors.push(
						{
							name: name,
							message:(title ? title : name) + ' est invalide.'
						});

				if ( val != '' && name.indexOf('tel') != -1 && (val.stripNonNumeric().length < 7 || val.stripNonNumeric().length > 20) )
					errors.push(
						{
							name: name,
							message: (title ? title : name) + ' n\'est pas un numéro de téléphone valide.'
						});
			});

		return errors;
	}

$(document).ready( function()
	{
		$('a[rel^=contact]').arcadimPopup();
		$('a[rel^=popup]').arcadimPopup();
		$('a[rel^=form]').not('.important a').arcadimPopup({metaName:'Partager un bon plan'});
		$('.important a[rel^=form]').arcadimPopup({formSubmitValue:'Je m\'inscris à l\'alerte email'});
	});
