
// JavaScript Document

$(document).ready( function(){

  
  // add detailinfo_box de Perrine
  
  // plutot setté ds class
  
  
  if(       $('#unknow_hour').attr("checked") == true) {$('#hour_birth , #min_birth').val('');} ;
  
  
  if(typeof(show_message)!= 'undefined' && show_message == true && browser != 'light')
  {
  
  message_context = new Array();
  
  message_context['email'] = "Votre email doit être <strong>valide</strong> afin de confirmer votre inscription. <br/> Il ne sera jamais communiqué au voyant";
  message_context['login'] ="Le pseudo vous permet de garder votre anonymat" ; 
  message_context['pass1'] ="Choisissez  un mot de 6 caractères minimum, sans espaces, accents, ou caractères spéciaux" ;
  message_context['pass2'] = message_context['pass1'];
  message_context['hour_birth'] = "Votre <strong>heure et ville de naissance</strong> permet de calculer votre ascendant et d’obtenir des prédictions plus précises";
  message_context['min_birth'] = message_context['hour_birth'] ;
  message_context['city_birth'] = message_context['hour_birth'] ;
   
    
   
  $("#email , #login , #pass1 , #pass2 , #hour_birth , #min_birth , #city_birth").focus(function () {
																								  
																								  
			
			var pos_input = $('#login').offset();
			
			var decal_top = -27 ;
			var decal_left = 0 ; 
			/*
			if( $(this).attr('id') == 'city_birth' ){  decal_top = -30 ;  }
			if( $(this).attr('id') == 'pass2' ){  decal_top = -26 ;  }
			if( $(this).attr('id') == 'min_birth' ){  decal_left = -70 ;  }
			*/
			
			top_pos_message_list =  pos_input.top + decal_top ; 
			left_pos_message_list =  pos_input.left + 170  + decal_left ;
			
			
			// top_pos_message_list =  150 ; 
			// left_pos_message_list =   350 ;
			
			
			
			
		   $('body').prepend("<div id='info_box'>Hello</div>");
		   $('#info_box').addClass('info_box');
           $('#info_box').css({ 'position':'absolute', 'z-index' :60 , 'top':top_pos_message_list , 'left':left_pos_message_list , 'opacity':0}) 
		   // if( $(this).attr('id') == 'login') {$('#info_box').css({ 'height':20 }) ;} 
           $('#info_box').hide();
			
																								  
																								  
			message_id = $(this).attr('id');
		   $('#info_box').html(message_context[message_id]);
		   $('#info_box').show().css("opacity",0).animate({ opacity: 1 },500);
    });
  
  $("#email , #login , #pass1 , #pass2 , #hour_birth , #min_birth , #city_birth").blur(function () {  
		   $('#info_box').hide();
		   $('#info_box').html('');
		   $('#info_box').remove('');
    });
  
  
  }


  // virer auto complete 
   // $('input').attr('autocomplete' , 'off') ; // marche Pô
   
   
  //  $('#astro_icon_line').hide();
  
  
 
  
  $('#submit_bt').click( 
									   			   			   
			function () 
			{
				
				$("#info_box").hide();
				
				if(typeof(callBackError) == 'undefined') { callBackError =  highLightError ; }					
				check_form( this , callBackError  )   ; 
			}	
			
	);



function check_form (trigger , callBackError)
 {
		 	 
		 // $('body').append('*') ;
		 
		 var form_id =   '#' + $(trigger).parents("form").attr("id") ; 	
		 var form_values = $(form_id ).serialize() ;
		 var page =  $(form_id).attr('action') ;

		$.post(    page ,     
					       form_values  ,  	  
								function(response)  
								{ 
								 var statut =  response.statut  ; 
								 	
								 
								 // debug pour empecher ENTER sur index , zarb
								 $('#check_enter').remove(); 
								 $('#form_inscription').append("<input type='hidden' name='check_enter' id='check_enter'  value='false'/>");

								 
								 if(statut ==  true)
								 {
								  
								  $('#check_enter').val('true');  // debug pour empecher ENTER sur index , zarb
								 
								
								 
								 
								 // last working
								 /*
								 if(response.wanted ==  'inscription_chat' || response.wanted ==  'pre_inscription' || response.wanted ==  'go_to_page')
								 {
								 $(form_id + ' #mode' ).val('submitForm') ;
								 $("#form_inscription").submit(); 
								 }
								 */
								 
								 
								 if(response.wanted ==  'pass_chat_recovery')
								 {
								   var page =  '_mail_recovery' ; 
								   info = new Object ;
	                               info.mail_to_recover = response.data_collection.email ;
								   
								$.post(   page ,
										  info ,
											function(retour_mail_recovery)  
											{ 		   
												// cleanage
											 // $("div[id='mail_recover_mess']").remove(); 
											 // $("#mail_recover_mess'").remove();  
											 $('#form_inscription #email_line').before(retour_mail_recovery.message);
											 
											 $('#mail_recover_mess').hide();
											 $('#mail_recover_mess').addClass('errorMessage');
											 $('#mail_recover_mess').css('width' , '450px');
											 $('#mail_recover_mess').show('fast');
											 
											 $('#form_inscription #email_line').remove();
												$('#form_inscription #submit_bt_line').remove();
												

											} 
											  , "json"
										);
								 } else { // new dev
								 
								 $(form_id + ' #mode' ).val('submitForm') ;
								 $("#form_inscription").submit(); 
								 
								 }
								
	  
								 } else {	 
								 
								 $('#check_enter').val('false');  // debug pour empecher ENTER sur index , zarb
								 
								 callBackError(response) ;
								 }
			 
								 } 
				       , "json"
				  );
		
		}


	
	function highLightError(response )
	{  
		 
		  data_collection = response.data_collection ; // tout les datas retournés , trimés
		  error_collection =  response.error_collection ; // les champs a probléme
		  
	//clean last class ok/error
	$("span[id='icon_field']").remove();
	$(".valideElement").removeClass("valideElement");
	$(".errorElement").removeClass("errorElement");
	 
	   $.each( data_collection, function(key, value)
				{ 
					$verif = error_collection[key] ;
			
					if(typeof($verif) == 'undefined') // pas trouvé dans l'objet erreur => champs ok
					{
					var classToAdd =  "valideElement" ;
					} else {
					var classToAdd =  "errorElement" ;
					}
					
					$( ' #' + key).addClass(classToAdd) ;
		

				 });	 // end each 
	  
	
	
	
	
	}
	








// CITY_BIRTH

 city_birth_show(); 
 
 function city_birth_show() // loading et Affichage du module city_birth  avec auto_complete
 {
		if ( $("#city_birth").length ==  0  )  { return false ; }  // si le input n'a pas été affiché par la class  FormInscription -> stop
		
		// Auto Complete proposition ville
		$("#city_birth").keyup(function(event){
		var text = $(this).val();
		
		$('#city_birth_id').val('') ;
		   
		$("#city_complement").remove();
		$("#city_birth").css("color","#7E7E7E");
		   
		// timer on keyup , déclenche le call ajax uniquement si pause de 700 ms entre 2 frappes
		$(this).stopTime('timer_keyup'); // kill le precedent timer 
		$(this).oneTime( 500, 'timer_keyup', function() { 
													  city_suggest(text);  
													  });    
		 });
		

		
		// sur Blur , si aucune ville selectionné par le user , checke si une ville dans la liste correspond 100 % avec ville tapée
		$("#city_birth").blur(function () {

			var info_city_selected = false ; // default
			
			if(typeof(global_city_response)!= 'undefined')
				{  				 	
				 
				 var city_asked = $("#city_birth").val().toLowerCase() ; 				  
				  
				  $.each(global_city_response.city_result, function(key, value) 
				   {
					 var city_name_elem  = split_city_name_propo(value.city_name_propo) ;
					 var city_name_elem_1 = city_name_elem[0] ;
					 var city_name_elem_2 = city_name_elem[1] ;
					 var city_name_compare  = city_name_elem_1.toLowerCase() ;
					 
					 if( city_name_compare == city_asked )
					   { 	
							completeCityBirth (city_name_elem_1 , city_name_elem_2 ) ;
							info_city_selected = global_city_response.city_result[key] ;			 		
					   } 
				   }
						 
				  ); // end each					 	  
				   
				 // getAstro() ;
				
				} // end if
				
				
			attribute_city_values(info_city_selected) ;
			hide_city_list() ;	
   		   
        });

		
 }



function city_suggest(txt) {
    
	 
	 // alert('city_suggest => delete global_city_response') ;
	 delete global_city_response;

	if(txt.length <= 3) 
	{
    // $("#suggestions").hide();
    } else {
    
	var page =  '_get_city' ;
	post_value = new Object ;
	post_value.city_to_complete =  txt ;
	

	var city_to_complete =  txt ;
	$.post(    page ,
			   post_value ,
			   function(city_response)  
			   { 		 		
				
				// ----- To Create the Div List --------
				var pos_input_city = $('#city_birth_line').offset();
				
				
				if(browser!= 'light')
			   {
				var decal_top = 20 ;
				var decal_left = 170 ;
			   } else { // iphone
			    var decal_top = 20 ;
				var decal_left = 100 ;
			   }
				var top_pos_city_list = pos_input_city.top  + decal_top ;
				var left_pos_city_list = pos_input_city.left  + decal_left ;
				
				var page =  '_html_stuff' ;
		        info_html = new Object ;
	            info_html.ask_for =  'div_city_list' ;
				info_html.element_name =  'city_list_cont' ;
				
				if(city_response.statut == true) // on a une liste a afficher 
				{
				// Set la liste sur objet global accéssible depuis autre partie du script
				global_city_response = new Object ;
				global_city_response = city_response ;
				
				
				

				$.post( page , info_html ,
						function(div_city_html)  
						{ 		 
						
						if ( $('#'+ info_html.element_name).length == 0 ) 
						{
						$('body').append(div_city_html) ;
						$('#'+ info_html.element_name).css({'top':top_pos_city_list , 'left':left_pos_city_list , 'opacity':0}) ;
						$('#'+ info_html.element_name).animate({ opacity: 1 },200);
						} else {
						 $('#'+ info_html.element_name + ' #city_propo').remove(); // refresh de la liste proposée
						}
						
						
							var city_list = city_response.city_result ;
							var ind = 1 ;
							$.each(city_list, function(key, value) 
							{  
							var city_info = city_list[key] ;
						//  var city_propo ='key:'+ key +',value:' + value + '->'+city_info.city_name_propo +'/' + city_info.lat +'/'+ city_info.long ;
							var city_propo =  city_info.city_name_propo ;
						 
						   city_propo = boldMe( city_propo , txt ); 
						 
							// Add la Row City à la Liste
							city_propo = "<div id='city_propo' value='"+  key  +"' > <span>" +  city_propo + " </span> </div>" ;
							$('#'+ info_html.element_name +' #main').append(city_propo) ;
							
							// Alternate color row 1/2 
							if(is_int(ind/2)){$("div[id='city_propo'][value='"+ key +"']").addClass('classWhiteFond'); }
							ind ++ ;
							
							// Bind le Behavior Click, passe en param l'object city_info, contient lat/long etc ..
							$("div[id='city_propo'][value='"+ key +"']").bind( "click", { info:city_info } , clickCity );	
							
							}) ; // end each
				
						} 
						  , "html"
				);


				}  else { // end if(city_response.statut == true)				
				$('#'+ info_html.element_name).remove(); 
				}
				
				} 
				  , "json"
			);
	
	
	//---------------
	} // end Else




} // end propo_ville func 

 
  function clickCity(event) 
  {
	var info = event.data.info ;
	var name_city = info.city_name_propo ;
	
	var city_name_elem  = split_city_name_propo(name_city) ;
	var city_name_elem_1 = city_name_elem[0] ;
	var city_name_elem_2 = city_name_elem[1] ;
	
	completeCityBirth (city_name_elem_1 , city_name_elem_2 ) ;
	hide_city_list() ;
	var value = $(this).attr('value');
	var info_city_selected = global_city_response.city_result[value] ; 
	
	
	//---
	// $.each(info_city_selected, function(key, value) {$('body').append(key + '-->' + value ) })
	// $('body').append('<br/>');
	//-----
	
	attribute_city_values(info_city_selected) ;

  }
  

  function completeCityBirth ( city_name_elem_1 , city_name_elem_2 )
  {
	$("#city_birth").val(city_name_elem_1);
	$("#city_birth").css("color","#006093"); 
	
	$('#city_complement').remove() ; 
	var city_complement = "<span id='city_complement'>" + city_name_elem_2 + "</span>" ;
	
	if(browser != 'light')
	{
	$("#city_birth").after(city_complement);
	$('#city_complement').css({ opacity: 0 }).addClass('city_complement').animate({ opacity: 1 },200);
	}  
	
	// hide_city_list() ;
  }
  
  
  function hide_city_list()
  {
	 var cont  = "#city_list_cont" ;
	$(cont).animate({ opacity: 0 },400,function(){$(cont).remove();}) ; // fade out and destroy
	// alert('hide_city_list');
  }
  
  
  function split_city_name_propo(city_name_propo)
  {
	var pos_split = stripos(city_name_propo , '(') ;
	var city_name_elem_1 = trim(city_name_propo.substr(0, pos_split-1)) ;
	var city_name_elem_2 = trim(city_name_propo.substr( pos_split )) ;
	
	var result = new Array(city_name_elem_1 , city_name_elem_2 ) ;
	return result ;
  }
  
  
  function attribute_city_values(city_object)
  {  
	  
	  // $('#debug').append('  ----   attribute_city_values' + city_object + ', id=' + city_object.id + ' / ');
	  
	  if(typeof(city_object) == 'undefined' || city_object === false )
	  {
	  $('#city_birth_id').val('') ;
	  } else {   
	  var city_birth_id = city_object.id ;
	  // alert(city_birth_id);
	  $('#city_birth_id').val(city_birth_id) ;
	  // alert('val' + $('#city_birth_id').val());
	  
	  } 
	  
	  getAstro() ;

  }
  
  
//  $('#city_birth_id').change(function () {alert('change ::!!!!! ');    } );

  

// ----------- ASTRO CALCUL -------



$('#unknow_hour').click( 
						 function(){
							  
							  $('#hour_birth , #min_birth').val('');
							  }
						 );


astro_show(); // génére le div & elements icon  si demandés par classInscription

$("#form_inscription select[id$='birth']").change( 
												  function() 
												  { 
												     getAstro() ; 
													// alert( $(this).attr('id') ) ; 
													var elem = $(this).attr('id') ;
													if( elem == 'hour_birth' || elem == 'min_birth' )
													{
														$('#unknow_hour').removeAttr("checked") ;
													}
												 }
												  
												 
												  
												  );  // trigge astro au changement de param birth infos


function astro_show() // Affiche d'icon astro, si asked dans la class  FormInscription => recup le html de base 
{

		// si le input a été affiché par la class  FormInscription et que l'on a bien demandé les input astro  dans  FormInscription , sinon stop
		if ( $("#astro").length ==  0 || $("#astro_icon_line").length == 0 )  { return false ; } 
		
		var page =  '_html_stuff' ;
		info_html = new Object ;
	    info_html.ask_for =  'icon_astro' ; 
		
		$.post(   page ,
			      info_html ,
					function(astro_html)  
					{ 		 
					 $("#astro_icon_line").html(astro_html);
					 getAstro() ;
					} 
					  , "html"
				);
		
		
}



function getAstro() //  check les valeur astro selon infos naissance => call Ajax ; // set les input hidden
{	
		
	// si le input astro a été affiché par la class  FormInscription
	if ( $("#astro").length ==  0 )  { return false ; } // doit pas arriver , triggé normalement par astro_show
	
	info_birth = new Object ;
	
	var day_birth = $('#day_birth').val();
	var month_birth = $('#month_birth').val();
	var year_birth = $('#year_birth').val();
	
	var hour_birth = $('#hour_birth').val();
	var min_birth = $('#min_birth').val();
	
	var city_birth_id = $('#city_birth_id').val();
		
	if( day_birth != '' && month_birth != ''  && year_birth != '' ) 
	{	
	info_birth.birth_date =  year_birth + '-' + month_birth + '-'  + day_birth  ;	
	} else {
	// clean tout astro si champs manquants
	$("input[id$='_astro']").val(''); // clean hidden
	$.each( $('#icon_sign img') , function(key, value) // clean img
								   {
									   var img = value ;
									   var source = $(img).attr("src");
                                       pos =  source.lastIndexOf('/')+1 ;
                                       path =  source.substr(0,pos) ;
                                       new_img = path + 'transparent.gif' ;
									   
									   $(img).attr("src" , new_img);   
								   });

	return false ; // end clean
	}
		
		
	if( hour_birth != '' && min_birth != ''  ) 
	{
		info_birth.birth_time =  hour_birth + ':' + min_birth   ;
	}
	
	
	if( city_birth_id != '' ) 
	{
		info_birth.city_birth_id =  city_birth_id  ;
	}
		
		
		  if(typeof(info_birth.birth_date) != 'undefined')
		 { 
			 var page =  '_get_astro' ;
			 
			$.post(    page ,     
							   info_birth  ,  	  
									function(astro_response)  
									{ 		 
									      $.each( astro_response, function(key, value) // set les input hidden 
											    { 
												     // var astro_field =  '#' + key +'_astro';
												     // $(astro_field).val(value) ;
											    						
																		if(value !== false)  
																		{
																		var astro_field =  '#' + key +'_astro';												
																		$(astro_field).val(value) ;
																		}
																			
															});	 
										  
											 astro_icon() ;
									 } 
						   , "json"
					  );
		 }		
}








function astro_icon()
{
	 
 
	 if ( $("#astro_icon_line").length == 0 )  {return false ; } // si affichage des icons a été demandé
	 		
	icon_collection = $("#astro_icon_line #sign")   ;  // toutes les icon sign  a checker 
	
	$(icon_collection).each(function(){
	 
	astro_type =  $(this).attr('alt'); 
	pos =  astro_type.lastIndexOf('_') ;
	astro_type =  astro_type.substr(0,pos) ;
	 
	
	
	// cherche l'image a afficher
	
	icon_value = '';
	if(astro_type=='zodiac') 
	{ 
	    icon_value =  $('#zodiac_id_astro').val() ;    
		txt_value =   $('#zodiac_sign_astro').val() ;    
		extension = 	   '.jpg' ; 
	 
	  $("#debug_astro").append('icon_value->' + icon_value + '/');
	 
	 }
		
	// if(astro_type=='element') { icon_value =  $('#element_astro').val() }
	
	if(astro_type=='decan') 
	{
		icon_value =  $('#decan_astro').val() ;  
		txt_value =  $('#decan_astro').val() + ' Décan' ;  
	    extension = 	   '.gif' ; 
	 }
	
	 if(astro_type=='ascendant') 
	 { 
		 icon_value =  $('#ascendant_id_astro').val() ;   
	 	 txt_value =  $('#ascendant_sign_astro').val() ;  
		 extension = 	   '.jpg' ; 
	 }
	
	if(astro_type=='chinese') 
	{ 
	icon_value =  $('#chinese_id_sign_astro').val() ;  
	txt_value =  $('#chinese_sign_astro').val() ;  
	extension = 	   '.gif' ; 
	}

  
  //  si pas de result ajax , pas assez d'infos pour calculer un sign, ascendant etc..
  if(typeof(icon_value) =='undefined' || icon_value =='' )  
	{ 
	 icon_value = 'transparent' ;
	 txt_value =  ''; 
	 extension = 	   '.gif' ; 
	} 
	
	
	icon_value  +=  extension  ;

   
   // si nouvelle image a afficher,  remplacement image et text, sinon nothing 
   
   actual_img = $("#sign[alt='" + astro_type + "_thumb'] #icon_sign img").attr('src') ;
   pos =  actual_img.lastIndexOf('/')+1 ;
   path =  actual_img.substr(0,pos) ;
   actual_img = actual_img.substr(pos) ; 
   
   if(  icon_value != actual_img  )  
	{

		function changeIcon(what_element) 
		{
            what_element.css("opacity",0).attr('src' , path + icon_value).animate({ opacity: 1 },1000);
		} ;
		

		var element = $("#sign[alt='" + astro_type + "_thumb'] #icon_sign img") ;
		changeIcon(element) ;
		
		var zodiac_sign = 	  $('#zodiac_sign_astro').val() ;
		txt_value =  ucfirst( txt_value ) ;		
		element_txt =   "#sign[alt='" + astro_type +"_thumb'] #text_sign"; 		
		$(element_txt).css("opacity",0).text(txt_value).animate({ opacity: 1 },1000) ; 
	}  
   

	 });

	
	
	
}




}); // End Document Ready

