/**
 * EUVS
 * Javascript file for Community category
 */

$(document).ready(function() {
    // IMAGE REPLACEMENT
    FLIR.init( { path: '/facelift/' } );
    $('#subnav ul li').each( function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesmediumcond',
            realFontHeight: true,
            resizeBox: true
        }));
    });
    $('.wikicollection h1,.share h1,.signup h1,.myfavorites h1,.bookmarks h2 span,.bookmark .edit h2 span, .bookmark .remove h2 span, .member #links h2 span').each( function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesmedium',
            mode: 'wrap',
            resizeBox: true
        }));
    });
    $('.sharing h2 strong, .share .wrapper.share-a-bottle h2 strong, .share .wrapper.share-a-book h2 strong, .bookmarks #label-search').each( function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesbold',
            mode: 'wrap',
            resizeBox: true
        }));
    });
    $('.sharing h2, .share .wrapper.share-a-bottle h2, .share .wrapper.share-a-book h2, .bookmarks #label-search').each( function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonneslight',
            mode: 'wrap',
            resizeBox: true
        }));
    });
    $('.member .parthead h2,.member .parthead .number, .bookmarks .lastmarks h2').each( function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesbold',
            mode: 'wrap',
            resizeBox: true
        }));
    });
    $('.blocklogin h5, .share .wrapper.share-a-bottle label, .share .wrapper.share-a-book label').each( function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesmedium',
            mode: 'wrap',
            resizeBox: true
        }));
    });
    $('#footmore h6').each( function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesbook',
            realFontHeight: true,
            resizeBox: true
        }));
    });
    $('.signup p:not(.block_terms) label,.signup h2, .member.edition .form_wrapper p label, .member.edition .form_wrapper h2, .member.edition #blockavatar h2').each( function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesmedium',
            realFontHeight: true,
            resizeBox: true
        }));
    });

	$('.bookmarks #add-bookmark h3 span.add,.bookmarks #get-marker h3 span.get ').each(function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesblackcond',
            realFontHeight: true,
            resizeBox: true
        }));
	});
	$('.bookmarks #add-bookmark h3,.bookmarks #get-marker h3').each(function() {
        FLIR.replace(this, new FLIRStyle({
            cFont: 'vonnesmedium',
            realFontHeight: true,
            resizeBox: true
        }));
	});

    // Login block
    var login_field_value = $(".blocklogin input.login").val();
    $(".blocklogin input.login").focus(function(){if ($(this).val() == login_field_value) $(this).val('').addClass('active');});
    $(".blocklogin input.login").blur(function(){if ($(this).val() == '') $(this).val(login_field_value).removeClass('active');});
    
    var password_field_value = $(".blocklogin input.password").val();
    $(".blocklogin input.password").focus(function(){if ($(this).val() == password_field_value) $(this).val('').addClass('active');});
    $(".blocklogin input.password").blur(function(){if ($(this).val() == '') $(this).val(password_field_value).removeClass('active');});
     
    var openid_field_value = $(".blocklogin input.openid").val();
    $(".blocklogin input.openid").focus(function(){if ($(this).val() == openid_field_value) $(this).val('').addClass('active');});
    $(".blocklogin input.openid").blur(function(){if ($(this).val() == '') $(this).val(openid_field_value).removeClass('active');});
    
    // OpenID switch link
    var login_mode_switch = function(){
        $(".blocklogin .modeopenid").toggle();
        $(".blocklogin .modeplainlogin").toggle();
    }
    $(".blocklogin .switcher a.switch").click(login_mode_switch);
    if (document.location.hash == '#openid') login_mode_switch();
    
	// Général
	$('.community .params label').show();
	
    // Member profile
    $(".member .parthead .toggle a").click(function(){
		var part = $(this).closest('.profilepart').attr('id');
		if(!$("#"+part+" .content").length) return true;
		$("#"+part+" .content").toggle();
        var src = $("#"+part+" .toggle a img").attr("src").replace("hide","temp").replace("show","hide").replace("temp","show");
        $("#"+part+" .toggle a img").attr("src",src);
		return false;
    });
    
    // Signup
    if ($('#signup_form input').length > 1) {
		var checkingLogin = false;
        var initial_value = [];
        $('.block_date_birth input').each(function() {
            initial_value[this.id] = $(this).val();
            $(".block_date_birth input").focus(function(){if ($(this).val() == initial_value[this.id]) $(this).val('').addClass('active');});
            $(".block_date_birth input").blur(function(){if ($(this).val() == '') $(this).removeClass('active').val(initial_value[this.id]);});
        });
        
        var checkField = function(f) {
            var check = checker(f);
			if($(f).is("[type=checkbox]")) return;
            if (check) $('#req_'+f.attr('name')).addClass('valid');
            else $('#req_'+f.attr('name')).removeClass('valid');
        }
        
        var checker = function(f) {
            
            var check = false;
            
            // Fonctions de check
            var checkReq = function(v) {return (v != '');}
            var checkMail = function(v) {
                var pattern = new RegExp(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i);  
				return pattern.test(v);
            }
            /////////////////// C'EST ICI
            var checkLogin = function(v) {
				if(checkingLogin) return;
				checkingLogin = true;
                $.get('/en/community/signup', {ajax: true, testlogin: v}, function(data) {
					checkingLogin = false;
					if(data == false) $('#req_login').addClass('valid');
					else $('#req_login').removeClass('valid');
				}, 'json');
				return false;
                //$.ajax({url: '/en/community/signup', data: "ajax=true&testlogin="+v}, success: function(data) {var test = (data == 'false') ? true : false; return test;}});
            }
            /////////////////// ---------
            var checkPass = function(v, v2){return (v == v2);}
            var checkLength = function(v,min,max) {return (v.length >= min && v.length <= max);}
            var checkInterval = function(v,min,max) {return (Math.floor(v) == v && v >= min && v <= max);}
            
            switch (f.attr('name')) {
                case 'email':
                check = (checkReq(f.val()) && checkMail(f.val()));
                return check; break;
                
                case 'date_birth_year':
                var d = new Date();
                check = (checkReq($('input#date_birth_day').val())
                && checkReq($('input#date_birth_month').val())
                && checkReq(f.val())
                && checkInterval($('input#date_birth_day').val(),1,31)
                && checkInterval($('input#date_birth_month').val(),1,12)
                && checkInterval(f.val(),1900,d.getFullYear()));
                return check; break;
                
                case 'login':
                check = (checkReq(f.val()) && checkLength(f.val(),4,20) && checkLogin(f.val()));
                return check; break;
                
                case 'password':
                check = (checkLength(f.val(),6,20) && checkReq(f.val()));
                return check; break;
                
                case 'confirm_password':
                check = (checkLength(f.val(),6,20) && checkReq(f.val()) && checkPass($('input#password').val(),f.val()));
                return check; break;
                
                case 'firstname':
                case 'lastname':
                case 'address':
                case 'city':
                case 'zipcode':
                case 'country':
                check = (checkLength(f.val(),2,255) && checkReq(f.val()));
                return check; break;

				case 'terms':
				break;
            }
			return false;
        }

		function checkEvent() {
        	if ($(this).attr('name') == 'date_birth_day' || $(this).attr('name') == 'date_birth_month') checkField($('#date_birth_year'));
            else {
            	checkField($(this));
                if ($(this).attr('name') == 'password') 
                	checkField($('#confirm_password'));
        	}
		}
		
		$('input#terms').click(function() {
			if($(this).is(":checked")) {
				$('#req_terms').addClass('valid');
			}
			else $('#req_terms').removeClass('valid');
		});
        
        $('#signup_form input').each(function(i){
            $(this).keyup(checkEvent);
            $(this).blur(checkEvent);
        });

        $('#signup_form select').each(function(i){
            $(this).change(function(){
                checkField($(this));
            });
        });
		
		$('#text_terms').hide();
		$('.block_terms label a').click(function(){
			$('#text_terms').toggle();
			return false;
		});
    }

	/* FAVORIS */

	/* Changement de page */
	function initFavoritesPagineLinks() {
		$('.favorites #pagine a').each(function() {
			var text = $(this).text();
			$(this).attr('href','javascript:void(0)');
			if(text.match(/^(\d*)$/)) $(this).attr('rel',text);
			$(this).click(function() {
				var page = $(this).attr('rel');
				var mem_id = $('.wikicol.favorites').attr('id').substring(7);
				if($(this).hasClass('prev')) page = parseInt($('.wikicol.favorites .bottles-container').attr('id').substring('5')) - 1;
				else if($(this).hasClass('next')) page = parseInt($('.bottles-container').attr('id').substring('5')) + 1;
				var displayOption = $('.wikicol.favorites a.display-option.current').attr('rel');
				var sorting = $('.wikicol.favorites select.sorting').val();
				var collection = $('.wikicol.favorites select.collection').val();
				$('.wikicol.favorites .bottles-container').load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/favorites',
					{ view : displayOption, sorting : sorting, collection : collection, page : page, mem_id : mem_id },
					function() {
						initFavoritesPagineLinks();
						if($('.wikicol.favorites').hasClass('removable')) initRemove();
						$('.wikicol.favorites .bottles-container').attr('id','page-' + page);
					}
				);
			});
		});
	}

	/* Suppression */
	function initRemove() {
		if(!$('.wikicol.favorites').hasClass('removable')) { return; }
		$('.wikicol.favorites a.remove').attr('href','javascript:void(0)');
		$('.wikicol.favorites a.remove').hide();
		$('.community .wikicol.favorites ul.items li').mouseover(function() {
			$(this).children('.remove-wrapper').children('a').show();
			$(this).children('a.remove').show();
		});

		$('.community .wikicol.favorites ul.items li').mouseout(function() {
			$(this).children('.remove-wrapper').children('a').hide();
			$(this).children('a.remove').hide();
		});

		$('.wikicol.favorites a.remove').click(function() {
			var lang = $('body').hasClass('en') ? 'en' : 'fr';
			var objectId = $(this).attr("rel");
			var indiceDepart = objectId.lastIndexOf('/')+1;
			var indiceArrivee = objectId.length;
			objectId = objectId.substring(indiceDepart, indiceArrivee);

			var bottle_type = $("#obj" + objectId).attr('rel');

			$.getJSON('/' + lang + "/collection/ajax/?method=removeFromFavorite&objectId="+escape(objectId)+"&typeFav=" + bottle_type,
				function(data){ if(data.success) $("#obj" + objectId).fadeOut(500, function() {
					$(this).remove();
				})
			});
		});
	}
	
	initFavoritesPagineLinks();
	if($('.wikicol.favorites').hasClass('removable')) initRemove();
	
	/* Filtres de collection */
	$('.wikicol.favorites select.collection').change(function() {
		var displayOption = $('a.display-option.current').attr('rel');
		var sorting = $('.wikicol.favorites select.sorting').val();
		var collection = $(this).val();
		var mem_id = $('.wikicol.favorites').attr('id').substring(7);
		$('.wikicol.favorites .bottles-container').load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/favorites',
			{ view : displayOption, sorting : sorting, collection : collection, mem_id : mem_id },
			function() {
				initFavoritesPagineLinks();
				if($('.wikicol.favorites').hasClass('removable')) initRemove();
				}
		);
	});

	/* Affichage : liste ou miniatures ? */
	$('.wikicol.favorites a.display-option').attr('href','javascript:void(0)').click(function() {
		var displayOption = $(this).attr('rel');
		var sorting = $('.wikicol.favorites select.sorting').val();
		var collection = $('.wikicol.favorites select.collection').val();
		var currentLink = $(this);
		var previousLink = (displayOption == 'thumbnails') ? $('.wikicol.favorites a.display-option[rel="list"]') : $('.wikicol.favorites a.display-option[rel="thumbnails"]');

		if(($('.wikicol.favorites .bottles-container ul').hasClass('list-details') && displayOption == "list")
		 || $('.wikicol.favorites .bottles-container ul').hasClass('thumbnails') && displayOption == "thumbnails") return;

		var page = $('.wikicol.favorites .bottles-container').attr('id').substring('5');
		var mem_id = $('.wikicol.favorites').attr('id').substring(7);

		$('.wikicol.favorites .bottles-container').load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/favorites',
			{ view : displayOption, sorting : sorting, collection : collection, mem_id : mem_id },
			function() {
				if(previousLink.length) previousLink.removeClass('current');
				if(currentLink.length)  currentLink.addClass('current');
				initFavoritesPagineLinks();
			    if($('.wikicol.favorites').hasClass('removable')) initRemove();
			}
		);
	});
	
	/* Options de tri */
	$('.wikicol.favorites select.sorting').change(function() {
		var sorting = $(this).val();
		var displayOption = $('.wikicol.favorites a.display-option.current').attr('rel');
		var collection = $('.wikicol.favorites select.collection').val();
		var mem_id = $('.wikicol.favorites').attr('id').substring(7);
		$('.wikicol.favorites .bottles-container').load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/favorites',
			{ view : displayOption, sorting : sorting, collection : collection, page : 1, mem_id : mem_id  },
			function() { initFavoritesPagineLinks(); if($('.wikicol.favorites').hasClass('removable')) initRemove(); }
		);
	});

	/* WIKI COLLECTION */
	if($('.wikicol.collection').length) {

		var isIE6 = ($.browser.msie && $.browser.version == '6.0');

		function closePopover() {
			$('#popover-container').animate({opacity:0},'normal', function() { $(this).remove(); });
		}

		function popoverRepos() {
			$('#popover-container').css({
				top : ($(window).height() / 2 ) - ($('#popover-container').height() / 2),
				left : ($(window).width() / 2 ) - ($('#popover-container').width() / 2)
			});
		}
		
		function initPopover() {
			$('a.popover-link').click(function() {

				var link = $(this);
				var lang = $('body').hasClass('en') ? 'en' : 'fr';
				var bottle_id = link.attr('rel').substring(7);
				var url = '/' + lang + '/community/wiki-bottle-info';
				var popover = $(document.createElement('div')).css({
					position : isIE6 ? 'absolute' : 'fixed',
					'z-index' : 10000
				}).attr('id','popover-container');

				popover.load(url, { bottle_id : bottle_id }, function() {
					popoverRepos();
					$(this).find('a.close').click(function(){ closePopover(); });
					$(this).find('li.more-infos a').click(function(){ 
						$.get('/' + lang + '/community/wiki-bottle-details', { bottle_id : bottle_id }, function(data) {
						});
					});

					var picLink = $(this).find('li.show-pics a');
					$.getJSON('/' + lang + '/community/wiki-bottle-pics', { bottle_id : bottle_id }, function(data) {
						picLink.click(closePopover);
						if(data.pics.length) picLink.lightbox({
						  //  fitToScreen: true,
						    jsonData: data.pics,
					       	loopImages: true,
					        imageClickClose: false,
					        disableNavbarLinks: true,
							prevLinkTitle : '/css/img/prevlabel.gif',
							nextLinkTitle : '/css/img/nextlabel.gif',
							fileBottomNavCloseImage : '/css/img/closelabel.gif',
							fileLoadingImage : '/css/img/loader.gif'
					    });
					});
					$('#popover p.legend').each( function() {
				        FLIR.replace(this, new FLIRStyle({
				            cFont: 'vonnesbold',
				            mode: 'wrap',
				            resizeBox: true
				        }));
				    });
				});
				$('body').append(popover).fadeIn(500);
				$(window).resize(popoverRepos);
			});
		}

		initPopover();

		/* Filtres de collection */
		$('.wikicol.collection select.collection').change(function() {
			var displayOption = $('.wikicol.collection a.display-option.current').attr('rel');
			var sorting = $('.wikicol.collection select.sorting').val();
			var collection = $(this).val();
			var mem_id = $('.wikicol.collection').attr('id').substring(7);
			$('.wikicol.collection .bottles-container').load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/wiki-bottles',
				{ view : displayOption, sorting : sorting, collection : collection, mem_id : mem_id},
				function() {
					//initWikiColPagineLinks();
					initPopover();
				}
			);
		});

		/* Affichage : liste ou miniatures ? */
		$('.wikicol.collection a.display-option').attr('href','javascript:void(0)').click(function() {
			var displayOption = $(this).attr('rel');
			var sorting = $('.wikicol.collection select.sorting').val();
			var collection = $('.wikicol.collection select.collection').val();
			var currentLink = $(this);
			var previousLink = (displayOption == 'thumbnails') ? $('.wikicol.collection a.display-option[rel="list"]') : $('.wikicol.collection a.display-option[rel="thumbnails"]');

			if(($('.wikicol.collection .bottles-container ul').hasClass('list-details') && displayOption == "list")
			 || $('.wikicol.collection .bottles-container ul').hasClass('thumbnails') && displayOption == "thumbnails") return;

			var page = $('.wikicol.collection .bottles-container').attr('id').substring('5');
			var mem_id = $('.wikicol.collection').attr('id').substring(7);

			$('.wikicol.collection .bottles-container').load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/wiki-bottles',
				{ view : displayOption, sorting : sorting, collection : collection, mem_id : mem_id},
				function() {
					if(previousLink.length) previousLink.removeClass('current');
					if(currentLink.length)  currentLink.addClass('current');
					//initWikiColPagineLinks();
					initPopover();
				}
			);
		});

		/* Options de tri */
		$('.wikicol.collection select.sorting').change(function() {
			var sorting = $(this).val();
			var displayOption = $('.wikicol.collection a.display-option.current').attr('rel');
			var collection = $('.wikicol.collection select.collection').val();
			var mem_id = $('.wikicol.collection').attr('id').substring(7);
			$('.wikicol.collection .bottles-container').load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/wiki-bottles',
				{ view : displayOption, sorting : sorting, collection : collection, page : 1, mem_id : mem_id },
				function() {
					//initWikiColPagineLinks();
					initPopover();
				 }
			);
		});
	}

	/* Bookmarks */
	function initBookmarksPagineLinks() {
		$('.community.member #links #pagine a').each(function() {
			var text = $(this).text();
			$(this).attr('href','#links');
			if(text.match(/^(\d*)$/)) $(this).attr('rel',text);
			$(this).click(function() {
				var page = $(this).attr('rel');
				var mem_id = $('.community.member #links .content').attr('id').substring(7);
				if($(this).hasClass('prev')) page = parseInt($('.community.member #links .bookmarks-list').attr('id').substring('5')) - 1;
				else if($(this).hasClass('next')) page = parseInt($('.community.member #links .bookmarks-list').attr('id').substring('5')) + 1;
				$('.community.member #links .content').load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/bookmarks',
					{ page : page, mem_id : mem_id },
						function() {
						initBookmarksPagineLinks();
					}
				);
			});
		});
	}

	initBookmarksPagineLinks();

	/* Share */
	if($('.wrapper.share-a-bottle').length || $('.wrapper.share-a-book').length) {
		if($("input[type=file]").length) $("input[type=file]").filestyle({ 
			image: $('body').hasClass('fr') ? '/css/img/community/bg-choose-file-fr.png' : '/css/img/community/bg-choose-file-en.png',
			imageheight : 27,
			imagewidth : 123,
			width : 153
		});
	}

	$('.wrapper.share-a-bottle a#addpic').click(function() {
		var nb = $('.wrapper.share-a-bottle .upload input[type=file]').length;
		var inputFile = $(document.createElement('input')).attr({'name':'photo' + nb,'type':'file'}).insertBefore(this);
		inputFile.filestyle({
			image: $('body').hasClass('fr') ? '/css/img/community/bg-choose-file-fr.png' : '/css/img/community/bg-choose-file-en.png',
			imageheight : 27,
			imagewidth : 123,
			width : 153
		});
	});
	
    var prod_year_value = $(".share-a-bottle input[name=year]").val();
    $(".share-a-bottle input[name=year]").focus(function(){ if ($(this).val() == prod_year_value) $(this).val(''); });
    $(".share-a-bottle input[name=year]").blur(function() { if ($(this).val() == '') $(this).val(prod_year_value); });

    var label_value = $(".share-a-bottle textarea[name=description]").val();
    $(".share-a-bottle textarea[name=description]").focus(function(){ if ($(this).val() == label_value) $(this).val(''); });
    $(".share-a-bottle textarea[name=description]").blur(function() { if ($(this).val() == '') $(this).val(label_value); });

	$('select[name=wine_type]').parent('span').hide();
	$('select[name=bottle_type]').change(function(){
		if($(this).val() == "wine_bottle") {
			$('select[name=wine_type]').parent('span').show();
			$('select[name=spirit_type]').parent('span').hide();
			$('select[name=country_code]').parent('span').hide();
		}
		if($(this).val() == "spirits_bottle") {
			$('select[name=spirit_type]').parent('span').show();
			$('select[name=wine_type]').parent('span').hide();
			$('select[name=country_code]').parent('span').show();
		}
	});
	$('select[name=spirit_type]').change(function(){
		$('select[name=bottle_type]').val('spirits_bottle');
	});
	$('select[name=wine_type]').change(function(){
		$('select[name=bottle_type]').val('wine_bottle');
	});

	// Share a book
	var title_value = $(".share-a-book input[name=title]").val();
    $(".share-a-book input[name=title]").focus(function(){ if ($(this).val() == title_value) $(this).val(''); });
    $(".share-a-book input[name=title]").blur(function() { if ($(this).val() == '') $(this).val(title_value); });

	var author_value = $(".share-a-book input[name=author]").val();
    $(".share-a-book input[name=author]").focus(function(){ if ($(this).val() == author_value) $(this).val(''); });
    $(".share-a-book input[name=author]").blur(function() { if ($(this).val() == '') $(this).val(author_value); });

	var editor_value = $(".share-a-book input[name=editor]").val();
    $(".share-a-book input[name=editor]").focus(function(){ if ($(this).val() == editor_value) $(this).val(''); });
    $(".share-a-book input[name=editor]").blur(function() { if ($(this).val() == '') $(this).val(editor_value); });

	var pub_year_value = $(".share-a-book input[name=publication_year]").val();
    $(".share-a-book input[name=publication_year]").focus(function(){ if ($(this).val() == pub_year_value) $(this).val(''); });
    $(".share-a-book input[name=publication_year]").blur(function() { if ($(this).val() == '') $(this).val(pub_year_value); });

	// Message de confirmation
	if($("#thanks-overlay").length) {
		$("#thanks-overlay").overlay({speed:'slow', close: 'a.back img'});
		$("#thanks-overlay").overlay().load();
	}

	/* Edition de profil */
	var motto_val;

	function submitChanges(motto) {	$.post('/en/community/edit-profile', {motto : motto}); }

	$('blockquote.motto.editable').click(function(){
		var blockquote = $(this);
		motto_val = $(this).text().substring(0,$(this).text().length-1).substring(1);

		if(!$('#motto-input').length) {
			var editInput = $(
				document.createElement('input')
			).attr({
				'id' : 'motto-input',
				'class' : 'motto',
				'value' : motto_val
			}).insertAfter(this).focus();
			$(this).hide();
			editInput.blur(function(){
				editInput.hide();
				blockquote.text('“' + editInput.val() + '”');
				blockquote.show();
				submitChanges($(this).val());
			});
		}
		else {
			$('#motto-input').val(motto_val);
			$('#motto-input').show();
			blockquote.hide();
		}
	});

	function preview(img, selection) {
	    var scaleX = 179 / (selection.width || 1);
	    var scaleY = 179 / (selection.height || 1);

		var xpos = Math.round(scaleX * selection.x1);
		var ypos = Math.round(scaleY * selection.y1);
		var width = Math.round(scaleX * $('#uploaded_avatar').width());
		var height = Math.round(scaleY * $('#uploaded_avatar').height());
		
	    $('#uploaded_avatar + div > img').css({
	        height: height + 'px',
	        width: width + 'px',
	        marginTop: '-' + ypos + 'px',
	        marginLeft: '-' + xpos + 'px'
	    });
		$('#validate_avatar_form input[name=xpos]').val(selection.x1);
		$('#validate_avatar_form input[name=ypos]').val(selection.y1);
		$('#validate_avatar_form input[name=width]').val(width);
		$('#validate_avatar_form input[name=height]').val(height);
	}

	function editAvatar() {
		if($('#avatar_form').length) return;
		$('#blockavatar #validate_avatar_form').remove();
		$('#blockavatar').append($(document.createElement('div')).load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/form-avatar',
				function() { $('#blockavatar').slideDown() }
			)
		);
	}

	if($('#validate_avatar_form').length) {
		$(document.createElement('div')).append($(document.createElement('img')).attr('src' , $('#uploaded_avatar').attr('src')).css('position', 'relative')).attr('class', 'avatarPreview').insertAfter($('#uploaded_avatar'));

		$('#uploaded_avatar').imgAreaSelect({
			aspectRatio: '1:1',
			onSelectChange: preview
		});

		var submitting = false;

		$('#validate_avatar_form').submit(function() {
			if(submitting) return; else submitting = true;

			var avatar = $('#uploaded_avatar').attr('src').split('/');
			avatar = avatar[avatar.length-1];

			$.post('/en/community/edit-profile',
				{
					avatar : avatar,
					xpos : $('#validate_avatar_form input[name=xpos]').val(),
					ypos : $('#validate_avatar_form input[name=ypos]').val(),
					width : $('#validate_avatar_form input[name=width]').val(),
					height : $('#validate_avatar_form input[name=height]').val()
				},
				function(data){
					$('.headblock img.photo').attr('src', data.file).fadeOut(0).fadeIn(200).click(editAvatar).css('cursor','pointer');
					$('#blockavatar').slideUp();
					$('.imgareaselect-outer, .imgareaselect-selection, .imgareaselect-border1, .imgareaselect-border2').hide();
					submitting = false;
				},
				'json'
			);
			return false;
		});
	}
	
	// Slide des avatars
	function initPrevMemberLink() {
		$('a.previous-members').click(function(){
			var mem_id = $(this).attr('rel').substring(7);
			var prev = $(this).parent().parent();
			prev.load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/prev-member', { mem_id : mem_id }, initPrevMemberLink);
		});
	};

	function initNextMemberLink() {
		$('a.next-members').click(function(){
			var mem_id = $(this).attr('rel').substring(7);
			var next = $(this).parent().parent();
			next.load('/' + ($('body').hasClass('en') ? 'en' : 'fr') + '/community/next-member', { mem_id : mem_id }, initNextMemberLink);
		});
	};

	initPrevMemberLink(); initNextMemberLink();

});
