
$(document).ready(function() {

	/****************************************************  LOADING*****************************************************/ 

	$(document).ajaxStart(function(){
		// clear out plugin default styling
		$.blockUI.defaults.css = {};
		$.blockUI({ 
				  message: '<div ><img src="images/spinner.gif" /> Please Wait...</div>' 				  }
				  
				  );
	});
	$(document).ajaxStop(function(){			
		$.unblockUI();	
	});
	
			
	$.address.change(function(event){	
		removeEditor();	
		var url = event.value;
		 if (url.length > 1 || (params['username'] != undefined && params['username'] != '')) {
			if (url.substr(0,12) =='confirmemail') {
				$('#form_area').load('forms/'+url);
            } else if (url.substr(0,11) =='media_cards' || (params['username'] != undefined && params['username'] != '')) {
				$('#form_area').load('forms/media_cards.php?username='+encodeURI(params['username']));
            } else if (url.substr(0,6) =='search') {

                var allParams = '';
                var counter = 0;
                for (var a in params) {
                    if (counter > 0) {
                        allParams += '&';
                    }
                    counter++;
                    allParams += (a + '=' + encodeURI(params[a]));
                }
                $('#form_area').load('forms/'+url+'.php?' + allParams);
            } else {
				$('#form_area').load('forms/'+url+'.php');
            }
		}
		else {
			$('#form_area').load('forms/register_approval.php');
			//$('#form_area').load('forms/register_step1.php'); // Default Display
        }
	});
	
	// Process SignUp step1
	$('#step1').live('click', function(){										   
		$('#step1_form').validate({
					rules: {
						password: {
							required:true,
							minlength:8,
							maxlength:128
						},
						confirm_password: {
							required:true,
							equalTo: "#password"
						 }
					},
								  
			submitHandler: function(form) {
				data = $(form).serialize();
				$.post('actions/user_verif.php',{data:data}, function(data){	
					if (data == false){
						window.location.replace('#register_step2', function(){
							$('input:first').focus();														
						})
					}
					else{
						// append error message
						$('#error_message').html(data);
					}
				});					
				return false;	
			}							 
		});		
	});

	// Process SignUp step2
	$('#step2').live('click', function(){										   
		$('#step2_form').validate({
			submitHandler: function(form) {
				data = $(form).serialize();
				$.post('actions/user_register.php', {data:data}, function(data){	
					if (data == true){
						window.location.replace('#email_send', function(){
							$('input:first').focus();														
						})
					}
					else{
						// append error message
						$('#error_message').html(data);
					}
				});					
				return false;	
			}							 
		});		
	});


/*Normand interface*/

	$('#normand').live('click', function(){										   
		$('#normand_form').validate({
			submitHandler: function(form) {
				data = $(form).serialize();
				$.post('actions/user_register_normand.php', {data:data}, function(data){	
					if (data == true){
						window.location.replace('#email_send_normand', function(){
							$('input:first').focus();														
						})
					}
					else{
						// append error message
						$('#error_message').html(data);
					}
				});					
				return false;	
			}							 
		});		
	});

	// Register without approval (ce processus est temporaire , c juste pour permettre au usages de d envoyer un mail a register@cliknfind.me (normand) pour les enregister a 	     nouveau avec  /*Normand interface*/  )
	
	$('#register_approval').live('click', function(){	
		$('#register_approval_form').validate({
							  
			submitHandler: function(form) {
				data = $(form).serialize();
				$.post('actions/user_verif.php', {data:data}, function(data){	
					if (data == false){
						window.location.replace('#email_register_approval');
					}
					else{
						// append error message
						$('#error_message').html(data);
					}
				});					
				return false;	
			}							 
		});		
	});

	//Process signin 
	$('#signin').live('click', function(){
		$('#signin_form').validate({
		
			submitHandler: function(form) {
				data = $(form).serialize();
				$.post('actions/user_login.php', {data:data}, function(data){
					$('#success_message').hide();
					
					if (data == '1'){
						window.location.replace('index.php?account#Resources');
						 //location.reload('index.php?account#Resources');
					}
					else if (data == '0'){
						$('#form_area').load('forms/email_send.php');
					}
					else{
						// append error message
						$('#error_message').html(data);
					}
				});
				return false;					
			}							 
		});				
	});
	
	$('#link_acces').live('click', function(){	
			href_link = $(this).attr("href");;
			window.location.replace('index.php'+href_link);
			location.reload('index.php'+href_link);	
	});

	//cancel signup
	$('#cancel').live('click', function(){
		var answer = confirm ("Are you sure? if you confirm, you lose all the information entred on step1")	;
	 	if (answer) {
			alert('ici');
			window.location.replace('index.php#register_step1');
			location.reload('index.php#register_step1');
			//location.reload('#register_step1');/					
		return false;	
		}
	});

	//Process Forgot Password  
	$('#password_reset').live('click' , function(){
		$('#forgot_password_form').validate({
				
			submitHandler: function(form) {
				email = $('#email').val();
				data = $(form).serialize();
				$.post('actions/password_reset.php', {data:data}, function(data){

					if (data == true){
						$('#form_area').load('forms/SignIn.php', function(){
							$('#success_message').html('An email with you new password has been sent');
							$('#email').val(email);
							$('#password').focus();									
						});							
					}
					else{
						// append error message
						$('#error_message').html(data);
					}
				});
				return false;					
			}							 
		});	
	});	

	$('#chgpwd').live('click', function(){	
										
		$('#chgpwd_form').validate({
					rules: {
						password: {
							required:true,
							minlength:8,
							maxlength:128
						},
						confirm_password: {
							required:true,
							equalTo: "#password"
						 }
					},
								  	
					submitHandler: function(form) {
						old_password = $('#old_password').val();		
						password1    = $('#password').val();
						user_id      = $('#user_id').val();		
						$.post('actions/password_is_valid.php', {user_id:user_id, old_password:old_password}, function(data){

							if (data == 'true'){
								$.post('actions/update_password.php', {user_id:user_id, password:password1}, function(data){
									$('#success_message').html('Your Password is updated' );																											  		
								});		
							}
							else{
								
							$('#success_message').html('Verify your Current Password' );				
							}			
						});	
				}							 
		});		
    });
		


	$('#upload_photo1').live('click' , function(){
											   
		new AjaxUpload($('#upload_photo1'),{
			action: 'actions/upload_photo.php',
				onChange : function(file , ext){
					if (! (ext && /^(jpg|jpeg|gif|png)$/i.test(ext))){
						$('#invalid_file_dialog').html('Invalid File Extension');						
						return false;
					}
				},
			onComplete: function(file, response){
				if (response == 0){
					$('#upload_err_dialog').html(response );
					$('#upload_err_dialog').html('There was a problem uploading your file');					
				}
				else{	
					location.reload('index.php#upload_photo');
					
				}
			}			
		}); 
	});
	

	$('#delete_photo').live('click', function(){
		var answer = confirm ("You are about to delete your photo ! Are you sure?")	;
	 	if (answer) {
		$.post('actions/delete_photo.php', function(data) { 

			if(data==1) {
				$('#success_message').html('Your photo is deleted');
				location.reload('index.php#upload_photo');//$('#form_area').load('forms/upload_photo.php');	
			}
		});			
		return false;	
		}
	});
	


	$('#info').live('click', function(){
			update_user('info')	;				   
	});

	$('#bio').live('click', function(){
			update_user('bio')	;				   
	});
	$('#social').live('click', function(){
			update_user('social')	;				   
	});
	
	
		//-------------------------------------- REGION/CITY FILTERS ------------------------------------
	$('#country_code').live('change', function() {
		country_code = $(this).val();
		$.post('actions/get_regions.php', {country_code:country_code}, function(data) {
			$('#region_code').html(data);
			regions_avail = true;		
		});				
	});	
	
	
	jQuery.validator.addMethod("url", function(val, elem) {
		// if no url, don't do anything
		if (val.length == 0) { return true; }
	 
		// if user has not entered http:// https:// or ftp:// assume they mean http://
		if(!/^(https?|ftp):\/\//i.test(val)) {
			val = 'http://'+val; // set both the value
			$(elem).val(val); // also update the form element
		}
		// now check if valid url
		// http://docs.jquery.com/Plugins/Validation/Methods/url
		// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
		return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(val);
	});		
	
	
})

	function update_user(id){
		var form_name = '#'+id+'_form';	
			$(form_name).validate({
								  
				submitHandler: function(form) {
					user_id = $('#user_id').val();

					data = $(form).serialize();
					$.post('actions/update_user.php', {data:data, user_id:user_id}, function(data){
						if (data == true){
							$('#form_area').load('forms/update_success.php?id='+id);
						}
						else{
							// append error message
							$('#error_message').html(data);
						}
					});					
					return false;	
				}							 	
		});	
	}

	/****************************************************  SESSION VALIDATION *****************************************************/  	
	function validate_session(user_clicked){
		$.ajax({
			global: false,
			type: "POST",
			url: 'actions/validate_session.php',
			data: ({user_clicked : user_clicked}),
			success: function(data) {
				if (data !== 'true'){
					window.location = 'index.php';	
				}
			}
		});
	}	

	/****************************************************  Remove the editor *****************************************************/  	
	function removeEditor()	{
		
		if ((document.getElementById('editor1') ) && (navigator.platform !='iPad') ){
			editor1.destroy();
			editor2.destroy();
			editor3.destroy();
		}
	}
	

