var isIE6 = ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined));

$(function(){
    if ($.prettyPhoto) {
        $("a[rel^='prettyPhoto']").prettyPhoto({ theme: 'facebook', default_width: 640, default_height: 360 });
    }
    
	if (!isIE6) {
		$('#menu a').live('click', function(e){
			$el = $(this);
			$url = $el.attr('href').split('#')[0];

			$('#content').load($url, function(){
				if ($('body').hasClass('smallMenu')) {
					$('body').removeClass().addClass('smallMenu');
				}
				else {
					$('body').removeClass();
				}
				$('#menu a').removeClass('current');
				$el.addClass('current');
			});
			return false;
		});
	}

    $('#selectGenre').click(function(){
        $('#selectGenreDrop').show('fast');
    });
    
    $('#selectGenreDrop').click(function(event){
        event.stopPropagation();
    });
	$('.messages').click(function(){
    	$(this).fadeOut(700);
    });
    $('#selectGenreDropFille').click(function(event){
        $('#genre')[0].value='f';
        $('#selectGenreCurrentFille').show();
        $('#selectGenreCurrentHomme').hide();
        $('#selectGenreDropFille').addClass('selected');
        $('#selectGenreDropHomme').removeClass('selected');
        $('#selectGenreDrop').hide('fast');
    });
    
    $('#selectGenreDropHomme').click(function(event){
        $('#genre')[0].value='h';
        $('#selectGenreCurrentFille').hide();
        $('#selectGenreCurrentHomme').show();
        $('#selectGenreDropFille').removeClass('selected');
        $('#selectGenreDropHomme').addClass('selected');
        $('#selectGenreDrop').hide('fast');
    });
    
	$('#menu a').hover(function(){
		$(this).children('span').fadeIn(125);
	}, function(){
		$(this).children('span').fadeOut(125);
	});


    if ($.browser.msie) {
        op = 0.8;
    } else {
        op=1;
    }

    $('.contentImgBuzz .thumb span').css('opacity','0');

    $('.thumb').hover(function(){
        $(this).children('span').stop();
        $(this).children('span').animate({ 
            opacity: op,
            top:0
        }, 750 );
    },
    function(){
        $(this).children('span').stop();
        $(this).children('span').animate({ 
            opacity: 0,
            top:-300
        }, 750 );
    });
    
    if($('#msg').length){
        setTimeout(function(){
            $('#msg').animate({opacity: 0}, 500 );
        }, 5000);
    }
    
    $('.pass span').click(function(){
        clickEl = $(this);
        $('.pass span').each(function(){
            if($(this).parent().attr('id') == clickEl.parent().attr('id')) {
                $(this).addClass('selected');
            } else {
                $(this).removeClass('selected');
            }
        });
        
        $('#modifierPass').attr('href', clickEl.parent('.pass').attr('href'));
    });
    
    $('.annulAboMiddle input[type=radio]').each(function(){
        $(this).attr('checked','');
    });
    
    $('.annulAboMiddle input[type=radio]').click(function(){
        if($(this).attr('id')=='raison-autres') {
            $('#textareaAnnulAbo').addClass('writable');
            $('#textareaAnnulAbo').attr('readonly','');
            $('#textareaAnnulAbo').focus();
        } else {
            $('#textareaAnnulAbo').removeClass('writable');
            $('#textareaAnnulAbo').attr('readonly','readonly');
        }
    });

    $('#textareaAnnulAbo').click(function(){
        $('#raison-autres').attr('checked','checked');
        $('#textareaAnnulAbo').addClass('writable');
        $('#textareaAnnulAbo').attr('readonly','');
    });
    
    $('.ico3').each(function(){
        $(this).mouseover(function() {
            $(this).children(':first').show();
        });
        $(this).mouseout(function() {
            $(this).children(':first').hide();
        });
    });
    
    $('.lienDemarrerSession').click(function() {
        popup($(this).attr('href'));
        return false;
    });
    
    $('.formInvitation').each(function(){
        $(this).submit(function(){
            var form = this;
            var url = form.action;
            var emailElement = $("input[name='email']", this);
            var isSexeH = (form.id == 'formInvitationM');
            var genre = isSexeH ? 'M' : 'F';
            if (! form.email.value) {
                emailElement.addClass('invInTxtErr').focus();
                emailElement.effect('pulsate', { times: 2 });
                return false;
            }
            $.ajax({
                url: url,
                async: isSexeH,
                dataType: 'json',
                data: {
                    email: form.email.value,
                    genre: genre,
                    bouton: 'validerEmail'
                },
                success: function(data) {
                    if (data.success) {
                        $('.error').slideUp();
                        $("input[name='email']", $('#boxInv')).val(form.email.value);
                        emailElement.removeClass('invInTxtErr');
                        if (isSexeH) {
                            $('#overlayBlack').show();
                            data.new_user ? $('#boxInv').addClass('boxInvOK') : $('#boxInv').removeClass('boxInvOK');
                            $('#boxInv').fadeIn('slow', function() {
                                $("input[name='password']", $('#boxInv')).focus();
                            });
                            $('html').animate({ scrollTop: $('html').offset().top }, 1000);
                        } else {
                            popup('/apps?mail=' + form.email.value + '&sex=f');
                        }
                    } else {
                        emailElement.addClass('invInTxtErr').focus();
                        emailElement.effect('pulsate', { times: 2 });
                        if (data.msg) {
                            $('#errEmail' + genre).html(data.msg).slideDown();
                        }
                    }
                }
            });
            return false;
        });
    });
    
    $('#formDemarrerSession').submit(function(){
        var form = this;
        var url = form.action;
        $('.error').hide();
        $("input[name='password']", $('#boxInv')).removeClass('err');
        $("input[name='code']", $('#boxInv')).removeClass('err');
        if (! form.password.value || form.password.value.length < 5) {
            $('#msgPassword').html('Mot de passe invalide. 5 caractères minimum');
            $('#errPassword').show();
            $('.error', $('#errPassword')).fadeIn();
            $("input[name='password']", $('#boxInv')).addClass('err').focus();
            return false;
        }
        if (! form.code.value) {
            $('#msgCode').html('Veuillez renseigner un code promotionnel');
            $('#errCode').show();
            $('.error', $('#errCode')).fadeIn();
            $("input[name='code']", $('#boxInv')).addClass('err').focus();
            return false;
        }
        $.ajax({
            url: url,
            async: false,
            dataType: 'json',
            data: {
                email: form.email.value,
                password: form.password.value,
                code: form.code.value,
                bouton: $('#boutonDemarrer').attr('name')
            },
            success: function(data) {
                var span = $('#resCode').children(':first');
                if (data.success) {
                    if (data.resCode) {
                        span.html(data.resCode).removeClass('errCode');
                        if (span.hasClass('valid')) {
                            span.effect('pulsate', { times: 1 });
                        } else {
                            span.addClass('valid');
                        }
                        $('#resCode').slideDown();
                        if ($('#boutonDemarrer').attr('name') == 'demarrerSession') {
                            if (self.opener) {
                                self.opener.location.reload();
                            }
                            popup('/apps?sex=h');
                        }
                    }
                } else {
                    if (data.password) {
                        $('#msgPassword').html(data.password.msg);
                        $('#errPassword').show();
                        $('.error', $('#errPassword')).fadeIn();
                        $("input[name='password']", $('#boxInv')).addClass('err').focus();
                    }
                    if (data.code) {
                        span.html(data.code.msg).removeClass('valid');
                        if (span.hasClass('errCode')) {
                            span.effect('pulsate', { times: 1 });
                        } else {
                            span.addClass('errCode');
                        }
                        $('#resCode').slideDown();
                    }
                }
            }
        });
        $('#boutonDemarrer').attr('name', 'demarrerSession');
        return false;
    });
    
    $('#codeInvitation').delay({
        delay: 500,
        event: 'keyup',
        fn: function(){
            if (this.value) {
                $('#boutonDemarrer').attr('name', 'checkCode');
                $('#formDemarrerSession').submit();
            }
        }
    });
    if ($('#formContact .messages').length || $('#formContact .error').length) {
        $('html').animate({ scrollTop: $('#titleFormContact').offset().top }, 500);
    }
    
    $('div#headerStart input.submit').click(function(e){
        $(e.target).animate({ top: '6px' }, 100)
        .animate( { top: '4px' }, 100);
    });
    
    $('#subHead').click(function(e){
        e.preventDefault();
        $(e.target).animate({ top: '2px' }, 100)
                   .animate( { top: '0' }, 100);
    });
    
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)
    
    var preloadThis=[
        '/images/demarrer-session-hover.png',
        '/images/inv-obtenir-pass-hover.png',
        '/images/inv-warning.png',
        '/images/logo-hover.png',
        '/images/input-header-pwd-focus.png',
        '/images/input-header-log-focus.png',
        '/images/btn-valider-hover.png',
        '/images/dropdown-hover.png',
        '/images/dropdown-focus.png',
        '/images/ico-selected-b.png',
        '/images/ico-homme-b.png',
        '/images/ico-fille-b.png',
        '/images/dd-option.png',
        '/images/btn-demarrer-hover.png',
        '/images/btn-demarrer-session-hover.png',
        '/images/p1m-hover.png',
        '/images/p3m-hover.png',
        '/images/p6m-hover.png',
        '/images/p1m-press.png',
        '/images/p3m-press.png',
        '/images/p6m-press.png',
        '/images/p1m-s.png',
        '/images/p3m-s.png',
        '/images/p6m-s.png',
        '/images/p1m-s-hover.png',
        '/images/p3m-s-hover.png',
        '/images/p6m-s-hover.png',
        '/images/p1m-s-press.png',
        '/images/p3m-s-press.png',
        '/images/p6m-s-press.png',
        '/images/changer-offre-hover.png',
        '/images/obtenir-pass-hover.png',
        '/images/input-rounded-focus.png',
        '/images/input-rounded-small-focus.png',
        '/images/input-rounded-focus.png',
        '/images/close-h.png',
        '/images/pass1jour-v-h.png',
        '/images/pass3mois-v-h.png',
        '/images/close-h.png',
        '/images/ie6/p1m.gif',
        '/images/ie6/p3m.gif',
        '/images/ie6/p6m.gif',
        '/images/ie6/p1m-s-press.gif',
        '/images/ie6/p3m-s-press.gif',
        '/images/ie6/p6m-s-press.gif',
        '/images/submit-contact-hover.png',
        '/images/login-mail-sent.png'
    ]; // literal array
    
//    $(preloadThis).each(function(){
//        $('body').append($('<img class="preload" />').attr('src', this));
//    });
    
});

(function($){
    /**
     * jQuery delayed event execution.
     */
    $.fn.delay = function(options) {
        var timer;
        var delayImpl = function(domElem, eventObj) {
            if (timer != null) {
                clearTimeout(timer);
            }
            var newFn = function() {
                options.fn.call(domElem, eventObj);
            };
            timer = setTimeout(newFn, options.delay);
        }
       
        return this.each(function() {
            var obj = $(this);
            obj.bind(options.event, function(eventObj) {
                 delayImpl(this, eventObj);  
            });
        });
    };
})(jQuery);

function popup(dest, width, height)
{
    if (typeof width == 'undefined') {
        var width = screen.width * 0.85;
    }
    if (typeof height == 'undefined') {
        var height = 725;
    }
    if (screen.width <= 1280 || screen.height <= 800) {
        // On ouvre en full si la résolution est inférieure ou égale à 1280x800
        width = screen.width;
        height = screen.height;
    }
    var top = Math.max(0, (screen.height - height) / 2 - 40);
    var left = (screen.width - width) / 2;
    var date = new Date();
    var id = date.getTime();
    var popup = window.open(dest, 'popup' + id, 'toolbar=no, location=no, directories=no, scrollbars=yes, menubar=no, resizable=yes, status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
    popup.focus();
}
