var newsLetterIncentiveVerif;
var newsLetterVerif;
var verifIdentity;
jQuery(document).ready(function($) {
	
		// Chargement des iframe like facebook en post
		$.post('/www/front-ws/facebook-like-loading', null, function(data){
			$('#facebookCadoLikeButton').html(data.buttonContent);
			$('#facebookCadoLikeBox').html(data.boxContent);
		}, 'json');
		
		// Pub
		var $ads;
	    $('div[id^="adsref-"]').each(function() { 			// pour chaque bloc d'annonce #adsref-[ads_id]
	        $ads = $('#ads-' + this.id.substr(7)).empty(); 	// supprimer de #ads-[ads_id] tout éventuel contenu
	        $('ins:first', this).appendTo($ads); 			// déplacer l'annonce dans #ads-[ads_id]
	    });
		
		function scroll_tweet(li){
	        var post = li.children("div.post"),
	        pWidth = post.width();
	        if (pWidth > parseInt(balloon.css('width'))){
	            var leftEnd = li.find('div.end');
	            if(leftEnd.length === 0){
	                leftEnd = $('<div class="end left" />').appendTo(li);
	            } 
	            var offsX = parseInt(leftEnd.width());
	            post.animate({left: offsX - pWidth - 55}, 23000, 'linear', function(){post.css('left', offsX);});
	        }
	    }
		
		// Carousel
		if($('#giftsCarousel, #flashGamesCarousel').length){
			$('#giftsCarousel, #flashGamesCarousel').jcarousel({
				auto: 10,
				wrap: 'circular',
				itemLoadCallback: function(){
					$('#giftsCarousel, #flashGamesCarousel', '.carousel').css('visibility', 'visible');
				}
			});
		}
		
		// Rating
		var gameListType = '';
		var gameId = '';
		$('.show_stars').mouseenter(function(){
			gameListType = $(this).parent().attr('id').split('-')[0];
			gameId = $(this).parent().attr('id').split('-')[1];			
			if($('.note-thank').is(':hidden') && $.cookie('deja-vote-' + gameListType + '-' + gameId) == null) $('.rate-game', '#' + gameListType + '-' + gameId).show();
		}).mouseleave(function(){
			$('.rate-game', '#' + gameListType + '-' + gameId).hide();
		});
		
		$('.note_game_action').mouseenter(function(){
			var $note = $(this).attr('title');
			$('.rate-game').find('li').each(function(){
				var $el = $(this).find('a');
				if($el.attr('title') > $note) $el.addClass('no-star');
				else if($el.hasClass('no-star')) $el.removeClass('no-star');
			});
		});
		
		// Scroll adsense
		var contentHeight = $('#content').height();		
		var pubHeight = ($('#sidebarAdSense').length) ? $('#sidebarAdSense').height() : $('#sidebarMenu').height();
		var maxTop = (contentHeight - pubHeight) + 10;
		
		$(window).scroll(function(){
			if($(this).scrollTop() < maxTop){				
				var top = $(this).scrollTop();				
				if(top < 0 || pubHeight > top) top = 0;
				if(top > 0) top = top - 200;
				$('#sidebarAdSense, #sidebarMenu').attr('style', 'margin-top: ' + top + 'px;');
			}
		});
		
		$('.note_game_action').click(function(){
			var $note = $(this).attr('title');
			$.post('/www/front-ws/note-game-' + gameListType, 'id=' + gameId + '&note=' + $note, function(data){
				if(data.response == 'true') { 
					$('.rate-game', '#' + gameListType + '-' + gameId).hide();
					$('.note-thank', '#' + gameListType + '-' + gameId).show();
					if($('.nb-votes', '#' + gameListType + '-' + gameId).length) $('.nb-votes', '#' + gameListType + '-' + gameId).html(data.new_nb_votes);
					$(document).oneTime(3000, function() {
						$('.note-thank').hide();
					});
					// On dépose un cookie pour que la personne ne vote plus pour ce jeu
					$.cookie('deja-vote-' + gameListType + '-' + gameId, 1, {
						expires: 3650,
						path: '/'
					});
										
					var element = $('.show_stars', '#' + gameListType + '-' + gameId);
					var classes = element.attr('class').split(/\s+/);
					var pattern = /^rating-stars-/;
					for(var i = 0; i < classes.length; i++){
					  var className = classes[i];
					  if(className.match(pattern)){
					    element.removeClass(className);
					  }
					}
					element.addClass('rating-stars-' + data.new_rate_css)
				}
			}, 'json');
		});
		
		//Creation du cookie déjà joué
		$('[name="unplayed"]').click(function(){
			$id = $(this).val();
			$.cookie('deja-joue-' + $id, 0, {
				expires: 3650,
				path: '/'
			});
			$('.' + $id).removeClass('played');
			$('.col-right', '.' + $id).show();
			$('.first', '.' + $id).hide();
			$('.last', '.' + $id).show();	
			$('[name="played"]').attr('checked', '');
		});

		$('[name="played"]').click(function(){
			$id = $(this).val();
			$.cookie('deja-joue-' + $id, 1, {
				expires: 3650,
				path: '/'
			});
			$('.' + $id).addClass('played');
			$('.col-right', '.' + $id).hide();
			$('.first', '.' + $id).show();
			$('.last', '.' + $id).hide();
			$('[name="unplayed"]').attr('checked', 'checked');
		});
		
		//Sauvegarder le jeu
		$('#saveGame').click(function(){
			gameName = $(this).attr('title');
			if(window.external && typeof(window.sidebar) == 'undefined') window.external.AddFavorite(window.location.href,gameName);
		    else if(window.sidebar.addPanel) window.sidebar.addPanel(gameName,window.location.href,"");
		});
		
		//Nombre element page
		$('[name="nbEl1"],[name="nbEl2"]').change(function(){
			$val = $(this).val();
			$.cookie('nbPage', $val, {
				expires: 3650,
				path: '/'
			});
			if($.browser.msie) window.location.reload();
			else location.href = window.location.href;
		});
	
		
		function scroll_tweet(li){
	        var post = li.children("div.post"),
	        pWidth = post.width();
	        if (pWidth > parseInt(balloon.css('width'))){
	            var leftEnd = li.find('div.end');
	            if(leftEnd.length === 0){
	                leftEnd = $('<div class="end left" />').appendTo(li);
	            } 
	            var offsX = parseInt(leftEnd.width());
	            post.animate({left: offsX - pWidth - 55}, 23000, 'linear', function(){post.css('left', offsX);});
	        }
	    }
	
	    function swap_tweets(current_tweet){
	        var next_tweet = (current_tweet + 1) % 5;
	        var li = $("li#tweet" + next_tweet);
	
	        $("#tweet" + current_tweet).fadeOut(300);
	        setTimeout(function(){
	            li.fadeIn(400);
	         }, 400);
	
	        setTimeout(function(){scroll_tweet(li);}, 3800);                
	
	        display_tweet = next_tweet;
	        setTimeout(function(){swap_tweets(display_tweet);}, 11300);
	    }
	        
	    var balloon = $("#twitterpost div.balloon");
	    display_tweet = 0;
	    if($("div.balloon ul li#tweet1").html() !== null){
	        setTimeout(function(){swap_tweets(display_tweet);}, 12000);
	        var firstli = $("li#tweet0");
	        setTimeout(function(){scroll_tweet(firstli);}, 7500);
	    }
	
		
		var mailVerif = function(email){
			return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/).test(email);
		}
				
		if(incentivePopup) $('#overlayIncentive').show();
				
		$('#incentiveClose').click(function(){
			document.cookie = 'incentivePopup=true;path="/"';
			$.cookie("incentivePopup", "true", {path: '/'});
			$('#overlayIncentive').hide();
		});
			
		$('.okbuttonIncentive').click(function(){
			newsLetterIncentiveVerif('newsletterIncentiveEmail', '/inscription/' + $('[name="newsletterIncentiveEmail"]').val());
		});
		
		newsLetterIncentiveVerif = function(input, redirect){
			if(!mailVerif($('[name="' + input + '"]').val())) jAlert('Veuillez saisir un email correct', 'Désolé, une erreur est survenue');
			else {
				$.cookie("incentivePopup", "true", {
					expires: 3650,
					path: '/'
				});
				location.href = redirect;
			}
		};
		
		$('.okbutton').click(function(){
			newsLetterVerif('newsletterEmail', '/inscription/' + $('[name="newsletterEmail"]').val());
		});
			
		$('.okbuttonLanding').click(function(){
			newsLetterVerif('landingEmail', '/inscription/' + $('[name="landingEmail"]').val() + '/' + partner);
		});
		
		newsLetterVerif = function(input, redirect){
			if(!mailVerif($('[name="' + input + '"]').val())) jAlert('Veuillez saisir un email correct', 'Désolé, une erreur est survenue');
			else location.href = redirect;
		};
		
		$('[name="search-terms"]').submit(function(){ return false; });
		
		$('#buttonsearch').click(function(){
			if($('#searchinput').val() == '' || $('#searchinput').val() == 'Ex.: un lot, un annonceur') {
				jAlert('Veuillez saisir un terme à rechercher', 'Désolé, une erreur est survenue');
				return false;
			} else {
				$.post('/www/front-ws/top-search', 'query=' + encodeURIComponent($('#searchinput').val()), function(data){
					location.href = '/recherche/' + data.response;
				}, 'json');
			}
		});
	
		/* ------------------------------------------------------------------------
			Class: Boite d'identification
		------------------------------------------------------------------------- */
				
		// Appel webservice login
		$('#formAuthSubmit').unbind().click(function(){ 
			verifIdentity('redirect', 'login', 'pwd'); 
		});
		
		// Appel webservice login
		$('#formForumAuthSubmit').unbind().click(function(){
			verifIdentity('redirectForum', 'loginForum', 'pwdForum'); 
		});
		
		verifIdentity = function(redirect, login, pwd){
			var redirect = $('[name="' + redirect + '"]').val();
			var login 	 = $('[name="' + login + '"]').val();
			var pwd 	 = $('[name="' + pwd + '"]').val();
			var remember = $('[name="rememberMe"]:checked').val();
			if(remember == undefined) remember = 0;
			
			if(login == '') jAlert('Veuillez saisir votre nom d\'utilisateur', 'Erreur lors de la connexion');
			else if(pwd == '') jAlert('Veuillez saisir votre mot de passe', 'Erreur lors de la connexion');
			else {
				$.post('/www/front-ws/login', 'login=' + login + '&pwd=' + pwd + '&remember=' + remember, function(data){
					if(data.response == 'true') location.href = redirect;
					else jAlert('Echec lors de l\'authentification.<br />Veuillez vérifier votre nom d\'utilisateur ou mot de passe.', 'Désolé, une erreur est survenue');
				}, 'json');
			}
		};
		
		// Appel webservice logout
		$('#logoutAuthBtn').unbind().click(function(){
			var logOutredirect = $('[name="logOutredirect"]').val();		
			$.post('/www/front-ws/logout', null, function(data){
				if(data.response == 'true') location.href = logOutredirect;
			}, 'json');
		});
		
		if ($('#action_billboard').length) {
			setTimeout(function() {
				var el = function() {
					$(document).unbind('mousemove', el).unbind('keydown', el).unbind('scroll', el);
					$('#action_billboard .button').css('display', 'block').hide().fadeIn();
				};
				$(document).bind('mousemove keydown scroll', el);
			}, 500);
			if ($.browser.msie && parseInt($.browser.version) <= 6) {
				$('#action_billboard .button').mouseover(function() {
					$(this).addClass('hover');
				}).mouseout(function() {
					$(this).removeClass('hover');
				});
			}
		}
	
		if ($.browser.msie && parseInt($.browser.version) <= 6) {
			$('.drawing').each(function() {
				var bg = $(this).css('background-image');
				if (bg.indexOf('.png') != -1)
					$(this).css('background-image', 'none').get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + bg.split('url("')[1].split('")')[0] + "', sizingMethod='scale')";
			});
		}
	
		var sform = $('#searchform'),
					ss = sform.children('input'),
					sb = sform.children('button'),
					defSearchVal = ss.attr('title');
					ss.attr('title', '');
					if (ss.val() == '') ss.val(defSearchVal);
					else if (ss.val() != defSearchVal) {
						ss.addClass('active');
						sb.addClass('visible');
					}
					ss.focus(function() {
						if (ss.val() == defSearchVal) ss.val('').addClass('active');
					}).blur(function() {
						if (ss.val() == '') ss.val(defSearchVal).removeClass('active');
					}).keydown(function(e) {
						if (e.which == 27) ss.val('');
					}).keyup(function() {
						if (ss.val() != '') sb.addClass('visible');
						else sb.removeClass('visible');
					});
					if (ss.length) {
						$(ss[0].form).submit(function() {
							if (ss.val() == defSearchVal) ss.val('');
						});
					}
					var abutton = $('#accountbutton'),
					submenu = abutton.next('div.loginmenu').get(0) || abutton.next('div.submenu').get(0);
					if (submenu) {
						submenu = $(submenu);
						var clickOutside,
						hideMenu = function() {
							abutton.removeClass('selected').unbind('click').click(showMenu);
							submenu.hide();
							$(document).unbind('click', clickOutside);
							return false;
						},
						showMenu = function() {
							abutton.addClass('selected').unbind('click').click(hideMenu);
							submenu.show();
							submenu.find('input[name="user_name"]').focus();
							$(document).click(clickOutside);
							return false;
						};
						clickOutside = function(e) {
							var elems = $(e.target).parents().andSelf();
							if ($.inArray(submenu[0], elems) == -1 && $.inArray(abutton[0], elems) == -1)
								hideMenu();
						};
						hideMenu();
					}
});
