/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


$(document).ready(function() {
	
	// validation de la recherche (colonne de droite)
	jQuery("#searchForm #searchSubmit").live('click', function () {
		
		// base de l'adresse
		var url = '/';
		
		// gestion du theme
		url += jQuery("#searchForm #searchTheme").val();
		
		// ajout de 2 tildes 
		url += '~~';
		
		// gestion de la date
		// TODO ?
		
		// ajout de 4 tildes
		url += '~~~~';
		
		// ajout de la commune
		url += jQuery("#searchForm #searchCommune").val();
		
		// ajout du dernier tilde et du nom de la page de recherche
		url += '~/recherche';
		
		// gestion mots cles
		if (jQuery("#searchForm #searchKeywords").val().length>2) {
			url += '?m='+jQuery("#searchForm #searchKeywords").val();
		}
		
		// redirection vers la page de resultats
		document.location = url;
		
	}); // fin clic sur btn recherche
	
	/*jQuery("#searchForm #searchKeywords").live('keypress', function(e){
		alert(e.which);
	});*/
	
	// validation de la recherche (colonne de droite)
	jQuery("#searchForm").submit(function(){
		
		// suppression caracteres speciaux et mots de moins de 2 lettres dans les mots cles
		jQuery("#searchForm #searchKeywords").val(keywordsFilter(jQuery("#searchForm #searchKeywords").val()));
		//alert(jQuery("#searchForm #searchKeywords").val());
		//return false;
		
		// base de l'adresse
		var url = '/';
		
		// gestion du theme
		url += jQuery("#searchForm #searchTheme").val();
		
		// ajout de 2 tildes 
		url += '~~';
		
		// gestion de la date
		// TODO ?
		
		// ajout de 4 tildes
		url += '~~~~';
		
		// ajout de la commune
		url += jQuery("#searchForm #searchCommune").val();
		
		// ajout du dernier tilde et du nom de la page de recherche
		url += '~/recherche';
		
		// gestion mots cles
		if (jQuery("#searchForm #searchKeywords").val().length>2) {
			url += '?m='+jQuery("#searchForm #searchKeywords").val();
		}
		
		// redirection vers la page de resultats
		//document.location = url;
		return false;
		
	}); // fin validation recherche
	
	
	alertAddWhilList=0
	/*Gestion des paniers*/
	jQuery(".addSelect").live('click', function () {
		tabId = jQuery(this).attr("id").split('_');
		ajaxWishlist('addLine', 'id='+tabId[1]+'&type=0');
                alertAddWhilList = 1;
                popin.show({id:'popinAddWishlistConfirm'});
                $('#popin').bind('onShown',function() {
                    if (alertAddWhilList==1) {
                        window.setTimeout(function () {
                            popin.hide({id:'popinAddWishlistConfirm'});
                        }, 1500);
                    }
                    alertAddWhilList=0;
                    //jQuery('#popinAddWishlistConfirm').fadeOut(500);
                 });


                    
                //
		return false;
	});
	
	jQuery(".addSelectBp").live('click', function () {
		tabId = jQuery(this).attr("id").split('_');
		ajaxWishlist('addLine', 'id='+tabId[1]+'&type=1');
		return false;
	});

	jQuery(".deleteSelect").live('click', function () {
		tabId = jQuery(this).attr("id").split('_');
		ajaxWishlist('deleteLine', 'id='+tabId[1]);
		return false;
	});
	
	
	/*Gestion des alertes*/
	jQuery(".addAlerte").live('click', function () {
		/*tabId = jQuery(this).attr("id").split('_');
		// masque zone de confirmation si visible
		if (jQuery('#confirmAlerte_'+tabId[1]).is(':visible')) {
			jQuery('#confirmAlerte_'+tabId[1]).slideUp();
		}
		// affiche si non visible
		else {
			jQuery('#confirmAlerte_'+tabId[1]).slideDown();
		}
		return false;*/
		
		// init fk_ot
		tabId = jQuery(this).attr("id").split('_');
		
		$('#popinAlerte #alerteParams #alerteOt').val(tabId[1]);
		
		// affiche la popin, en purgeant la zone de texte, en masquant l'icone de chargement et en for�ant l'affichage du bouton d'enregistrement
		jQuery("#popinAlerte #alerteTexte").empty();
		jQuery("#popinAlerte #alerteParams #ajaxLoader").hide();
		jQuery("#popinAlerte #alerteParams #confirmAddAlerte").show();
		popin.show({id:'popinAlerte'});
		
	});
	
	jQuery("#popinAlerte #alerteParams #confirmAddAlerte").live('click', function () {		
		// masque bouton d'enregistrement pour eviter clic multiple
		$(this).hide();
		// affiche l'icone de chargement
		jQuery("#popinAlerte #alerteParams #ajaxLoader").show();
		// appel ajax pour enregistrement
		ajaxAlerte('add', 'fk_ot='+jQuery('#popinAlerte #alerteParams #alerteOt').val()+'&nb_jours='+jQuery('#popinAlerte #alerteParams #alerteNbJours').val());
		return false;
	});

	jQuery(".deleteAlerte").live('click', function () {
		tabId = jQuery(this).attr("id").split('_');
		ajaxAlerte('delete', 'fk_ot='+tabId[1]);
		return false;
	});


	/*Gestion des WishLists*/
	jQuery("#linkAddWishlist").live('click', function () {
		ajaxWishlist('add', '');
		return false;
	});
	jQuery("#btnAddWishlist").live('click', function () {
		name = encodeURI(jQuery("#wishlist_name").val());
		ajaxWishlist('add', 'mode=save&name='+name);
		return false;
	});


	jQuery("#linkUpdateWishlist").live('click', function () {
		ajaxWishlist('update', '');
		return false;
	});

	jQuery("#btnUpdateWishlist").live('click', function () {
		name = encodeURI(jQuery("#wishlist_name").val());
		ajaxWishlist('update', 'mode=save&name='+jQuery("#wishlist_name").val());
		return false;
	});


	/*jQuery("#linkChangeWishlist").live('click', function () {
		ajaxWishlist('change', '');
		return false;
	});*/

/*	jQuery(".btnChangeWishlist").live('click', function () {
		tabId = jQuery(this).parent("li").attr("id").split('_');
		ajaxWishlist('change', 'id='+tabId[2]+"&mode=change");
		return false;
	});*/


	jQuery(".deleteWishlist").live('click', function () {
		
		id_liste = jQuery(this).attr("id").split('_');
		
		jQuery.ajax({
                type: "POST",
                url: "/ajaxController.php5",
                data: "action=deleteBasket&id="+id_liste,
                success: function(msg) {
                        if (msg=='OK') {
                        } else {
                            alert("Une erreur s'est produite, veuillez ré-essayer plus tard");
                        }
                         //popin.hide();
                }
        });
		
		
		//console.log(tabId);
                //ajaxWishlist('delete', 'id='+tabId[2]);
		return false;
	});



	/*Gestion des boutons*/
	jQuery(".cancelMenu").live('click', function () {
		ajaxWishlist('load', '');
		return false;
	});
        /*Fin modifs technique 31/05/10 */


        jQuery("#renommeParams").submit(function (){
            confirmRenomme();
            return false;
        });

        jQuery("#renommeParamsProfil").submit(function (){
            confirmRenommeProfil();
            return false;
        });

        jQuery("#partageParams").submit(function (){
            confirmPartage();
            return false;
        });

        jQuery("#alerteParams").submit(function (){
            confirmPartage();
            return false;
        });

});


// filtre une chaine (suppression de certains caracteres speciaux)
function keywordsFilter(str) {
	// suppression des signe "&" et "="
	var reg = new RegExp("[\&\=]", "gi");
	
	// retourne la chaine traitee
	return str.replace(reg,'');
}


/* Gestion des soumissions formulaires ajax */
function ajaxCompte(mode) {
	var datas = '';

	switch (mode) {

		case 'login':
			var email = encodeURI(jQuery("#compte_email").val());
			var pwd = encodeURI(jQuery("#compte_pwd").val());
			datas = "action=login&email="+email+"&pwd="+pwd;
			break;

		case 'logout':
			datas = "action=logout";
			break;

		case 'load':
			datas = "action=loadAccount";
			break;
	}

	if (datas != '') {
		jQuery.ajax({
			type: "POST",
			url: "/ajaxController.php5",
			data: datas,
			success: function(msg) {
                                var container = jQuery("#login");
				container.replaceWith(msg);
				ajaxWishlist('load','');
                                updateCufon('#login .link1 .rightBorderDeco');
			}
		});
	}
}


function popinChangeList() {
	// masque image de chargement ajax et affiche la liste des wishlist
	jQuery("#popinChangeListe .ajaxLoader").hide();
	jQuery("#popinChangeListe #changeListe").show();
	// affiche popin
	popin.show({id:'popinChangeListe'});
}

function confirmChangeList(idBasket) {
	// affiche image de chargement et masque la liste des wishlist
	jQuery("#popinChangeListe .ajaxLoader").show();
	jQuery("#popinChangeListe #changeListe").hide();
	// appel ajax pour enregistrement
	jQuery.ajax({
        type: "POST",
        url: "/ajaxController.php5",
        data: "action=changeBasket&mode=change&id="+idBasket,
        success: function(msg) {
			// retour = "OK" : changement effectué, rechargement de la liste dans le menu
           if (msg=='OK') {
		   	    // masque le popin
				jQuery("#popinChangeListe .ajaxLoader").fadeOut(1000, function(){
					popin.hide();
				});
				// appel ajax en parallèle pour maj menu
				ajaxWishlist('load','');
            } else {
                alert("Une erreur s'est produite, veuillez ré-essayer plus tard");
            }
           // 

        }
    });
}

/* Gestion des wishlist */
function ajaxWishlist(action, params) {
	
	var datas = '';

	switch (action) {
		case 'load':
			datas = "action=loadBasket";
			break;

		case 'add':
			datas = "action=addBasket&"+params;
			break;

		case 'update':
			datas = "action=updateBasket&"+params;
			break;

		case 'change':
			datas = "action=changeBasket&"+params;
			break;

		case 'delete':
			datas = "action=deleteBasket&"+params;
			break;

		case 'addLine':
			datas = "action=addBasketLine&"+params;
			
			break;

		case 'deleteLine':
			datas = "action=deleteBasketLine&"+params;
			break;
	}

	if (datas != '') {
		jQuery.ajax({
			type: "POST",
			url: "/ajaxController.php5",
			data: datas,
			success: function(msg) {
				var container = jQuery("#eventList");
				updateCufon('#eventList .link1 .rightBorderDeco, #login .link1 .rightBorderDeco');
				
				if(action == "change" || action == "change") {
					jQuery('#changeListe p').html(msg);
					
					popin.show({id: 'popinChangeListe'});
				}
				else if(action == "add") {
					//Rafraichissement de l'onglet ma liste de sorties					
					ajaxWishlist("load","");
					return true;
					
				}
				
				else{
						container.replaceWith(msg);
						updateCufon('#eventList .link1 .rightBorderDeco, #login .link1 .rightBorderDeco');
			
				}
				
				//jQuery("#selection").html(msg);
			}
		});
	}
}



/* Gestion des alertes */
function ajaxAlerte(action, params) {
	
	var datas = '';
	switch (action) {
		
		// ajout
		case 'add':
			jQuery.ajax({
				type: "POST",
				url: "/ajaxController.php5",
				data: "action=addAlerte&"+params,
				success: function(msg) {
					jQuery('#popinAlerte #alerteParams #ajaxLoader').fadeOut(1200, function(){
						jQuery('#popinAlerte #alerteTexte').html(msg);
					});
				}
			});
			break;
			
		// suppression
		case 'delete':
			jQuery.ajax({
				type: "POST",
				url: "/ajaxController.php5",
				data: "action=deleteAlerte&"+params,
				success: function(msg) {
					// message d'alerte si suppresion non valid�e
					if (msg!='DELETE_OK') {
						alert(msg);
					}
				}
			});
			break;
			
		default :
			break;
			
	}
	
}

function renommeListe(id_liste) {
    $('#popinRenommeListe #renommeParams #renommeId').val(id_liste);
    $('#popinRenommeListe #renommeParams #renommeNom').val($('#wishListName').text());
    popin.show({id:'popinRenommeListe'});
}
function confirmRenomme() {
    jQuery.ajax({
                type: "POST",
                url: "/ajaxController.php5",
                data: "action=renommeListe&id="+$('#popinRenommeListe #renommeParams #renommeId').val() + '&name=' + $('#popinRenommeListe #renommeParams #renommeNom').val(),
                success: function(msg) {
                        if (msg=='OK') {
                            $('#wishListName').text($('#popinRenommeListe #renommeParams #renommeNom').val());
                        } else {
                            alert("Une erreur s'est produite, veuillez ré-essayer plus tard");
                        }
                         popin.hide();
                }
        });
}

function renommeListeProfil(id_liste) {
    $('#popinRenommeListeProfil #renommeParamsProfil #renommeIdProfil').val(id_liste);
    $('#popinRenommeListeProfil #renommeParamsProfil #renommeNomProfil').val($('#wishlist_' + id_liste).text());
    popin.show({id:'popinRenommeListeProfil'});
}
function confirmRenommeProfil() {
    jQuery.ajax({
                type: "POST",
                url: "/ajaxController.php5",
                data: "action=renommeListe&id="+$('#popinRenommeListeProfil #renommeParamsProfil #renommeIdProfil').val() + '&name=' + $('#popinRenommeListeProfil #renommeParamsProfil #renommeNomProfil').val(),
                success: function(msg) {
                        if (msg=='OK') {
                          $('#wishlist_' +  $('#popinRenommeListeProfil #renommeParamsProfil #renommeIdProfil').val()).text($('#popinRenommeListeProfil #renommeParamsProfil #renommeNomProfil').val());
                        } else {
                            alert("Une erreur s'est produite, veuillez ré-essayer plus tard");
                        }
                         popin.hide();
                }
        });
}


function supprimeListe(id_liste) {
	jQuery.ajax({
                type: "POST",
                url: "/ajaxController.php5",
                data: "action=deleteBasket&id="+id_liste,
                success: function(msg) {
                    if (msg=='OK') {
						// suppression de la ligne dans la popin de changement
						jQuery('#popinChangeListe #changeListe #wishlist_change_'+id_liste).remove();
                    } else {
                        alert("Une erreur s'est produite, veuillez ré-essayer plus tard");
                    }
                     popin.hide();
                }
        });
}

/* Partage d'une liste (popin) */
function partageListe(id_liste) {
	$('#popinPartage #partageParams #partageId').val(id_liste);
	// affiche la popin, en purgeant la zone de texte, en masquant l'icone de chargement et en for�ant l'affichage du bouton d'enregistrement
	jQuery("#popinPartage #partageTexte").empty();
	//jQuery("#popinPartage #partageParams #partageEmails").empty();
	jQuery("#popinPartage #partageParams #ajaxLoader").hide();
	jQuery("#popinPartage #partageParams #confirmPartage").show();
	popin.show({id:'popinPartage'});
}

function confirmPartage() {
	// masque bouton d'enregistrement pour eviter clic multiple
	jQuery("#popinPartage #partageParams #confirmPartage").hide();
	// affiche l'icone de chargement
	jQuery("#popinPartage #partageParams #ajaxLoader").show();
	// appel ajax pour enregistrement
	ajaxPartage('send', 'wishlist='+jQuery('#popinPartage #partageParams #partageId').val()+'&emails='+jQuery('#popinPartage #partageParams #partageEmails').val());
	return false;
}

/* Partage de wishlist*/
function ajaxPartage(action, params) {
	
	var datas = '';
	switch (action) {
		
		// envoi
		case 'send':
			jQuery.ajax({
				type: "POST",
				url: "/ajaxController.php5",
				data: "action=partageListe&"+params,
				success: function(msg) {
					jQuery('#popinPartage #partageParams #ajaxLoader').fadeOut(1200, function(){
						jQuery('#popinPartage #partageTexte').html(msg);
					});
				}
			});
			break;
			
		default :
			break;
			
	}
	
}
