
// Global variables
var translatedErrors = new Array(),
    translatedMessages = new Array(),
    startAnimalBreed = true;

$(document).ready(function()
{
	// DISPLAY THE LANGUAGE MENU IN THE HEADER OF THE HOMEPAGE
    $("#langues>a").mouseover(function(){
        $("#langues-fleche").attr('src',$("#fleche-down").attr('value'));
        $("#menuLangue").slideDown();
    });
    $("#langues>a").focus(function(){
        $("#langues-fleche").attr('src',$("#fleche-down").attr('value'));
        $("#menuLangue").slideDown();
    });
    $("#langues>a").click(function(){
        $("#langues-fleche").attr('src',$("#fleche-right").attr('value'));
        $("#menuLangue").slideToggle();
        this.blur();
        return false;
    });
    $("#langues").mouseleave(function(){
        $("#langues-fleche").attr('src',$("#fleche-right").attr('value'));
        $("#menuLangue").slideUp();
    });

    var reg = new RegExp( "[_]+" );

    // When clicking a link in the main menu
    $('#header #menu a').unbind( 'click' );
    $('#header #menu a').click(function(){
        var classMenu = $(this).attr('id').split( reg )[1];
        if($('#sousMenu .sousMenu:visible').length) { // Si sous menu déjà ouvert
            if(classMenu == $('#sousMenu .sousMenu:visible').attr('id').split( reg )[1]) { // Si clic sur sous menu ouvert
                $('#sousMenu #sousMenu_'+classMenu).slideUp();
                gestionFleche('kill');
            } else {
                $('#sousMenu .sousMenu:visible').slideUp();
                $('#sousMenu #sousMenu_'+classMenu).slideDown();
                gestionFleche(false, classMenu);
            }
        } else { // Si sous menu non ouvert
            $('#sousMenu #sousMenu_'+classMenu).slideDown();
            gestionFleche(true, classMenu);
        }
        return false;
    });

    // When clicking a link in the breadcrumbs
    $('#container .ariane a.scroll').unbind( 'click' );
    $('#container .ariane a.scroll').click(function(){
        var classMenu = $(this).attr('class');
        classMenu = classMenu.replace('scroll','');
        classMenu = classMenu.replace(' ','');
        if($('#sousMenu .sousMenu:visible').length) { // Si sous menu déjà ouvert
            if(classMenu.split( reg )[1] == $('#sousMenu .sousMenu:visible').attr('id').split( reg )[1]) { // Si clic sur sous menu ouvert
                $('#sousMenu #sousMenu_'+classMenu.split( reg )[1]).slideUp();
                gestionFleche_v2('kill');
            } else {
                $('#sousMenu .sousMenu:visible').slideUp();
                $('#sousMenu #sousMenu_'+classMenu.split( reg )[1]).slideDown();
                gestionFleche_v2(false, classMenu.split( reg )[1]);
            }
        } else { // Si sous menu non ouvert
            $('#sousMenu #sousMenu_'+classMenu.split( reg )[1]).slideDown();
            gestionFleche_v2(true, classMenu.split( reg )[1]);
        }
        return false;
    } );

    // Hack for the :focus selector not working on IE7
    $( 'input' ).bind( 'focus', function() { $( this ).addClass( 'inputwfocus' ); } )
                .bind( 'blur',  function() { $( this ).removeClass( 'inputwfocus' ); } );

    ////////////////////////////////////////////// Validator //////////////////////////////////////////////

    // Add a new validation method for inputs with CSS class 'date'
    $.validator.addMethod(
        'date', function( value, element )
        {
            return getDateFromDatePickerString( value ) != false;
        }
    );

    // Add a new validation method for inputs with CSS class 'date_max_today'
    $.validator.addMethod(
        'date_max_today', function( value, element )
        {
        	var dpDate = getDateFromDatePickerString( value ),
                todayDate = new Date();

            return dpDate != false && dpDate <= todayDate;
        }
    );

    // Add a new validation method for inputs with CSS class 'phone_number'
    $.validator.addMethod(
        'phone_number', function( value, element )
        {
            // A phone number should only contain numbers, the plus sign or spaces
            var pattern = /^\+?[0-9 ]+$/;
            return ( pattern.test( value ) | (value == '') );
        }
    );

    // Add a new validation method for inputs with CSS class 'breed_or_size'
    $.validator.addMethod(
        'breed_or_size', function( value, element )
        {
        	$( element ).attr( 'name' ).match( /_([0-9]+)$/ );
        	var index = RegExp.$1;
            return $( 'select[name="dog_breed_' + index + '"]' ).val() != ''
            	|| $( 'select[name="animal_size_' + index + '"]' ).val() != '';
        }
    );

    // Add a new validation method for inputs with CSS class 'date_of_birth_or_age'
    $.validator.addMethod(
        'date_of_birth_or_age', function( value, element )
        {
        	$( element ).attr( 'name' ).match( /_([0-9]+)$/ );
        	var index = RegExp.$1;
            return $( 'input[name="birthday_' + index + '"]' ).val() != ''
            	|| $( 'input[name="age_' + index + '"]' ).val() != '';
        }
    );

    // Add a new validation method for inputs with CSS class 'password_with_confirm'
    $.validator.addMethod(
        'password_with_confirm', function( value, element )
        {
            var isCurrentConfirm = $( element ).attr( 'name' ).lastIndexOf ( '_confirm' ) != -1,
                password = isCurrentConfirm ? $( 'input[name="' + $( element ).attr( 'name' ).replace( '_confirm', '' ) + '"]' ) : $( element ),
                passwordConfirm = isCurrentConfirm ? $( element ) : $( 'input[name="' + $( element ).attr( 'name' ) + '_confirm"]' ),
                valid = $( password ).val() == $( passwordConfirm ).val();

            if( valid )
            {
                $( password, passwordConfirm ).next( 'label' ).hide();
            }

            return valid;
        }
    );

    // Add a new validation method for inputs with CSS class 'minlength_3'
    $.validator.addMethod(
        'minlength_3', function( value, element )
        {
            return value == '' ||  value.length >= 3;
        }
    );

    // Validator messages
    $.extend( $.validator.messages,
    {
        'date': translatedErrors['Invalid date format'],
        'date_max_today': translatedErrors['Please choose a date before today.'],
        'phone_number': translatedErrors['Please enter a valid phone number.'],
        'breed_or_size': translatedErrors['Please choose a breed OR a size.'],
    	'date_of_birth_or_age': translatedErrors['Please specify the birthdate OR the age.'],
    	'password_with_confirm': translatedErrors['The passwords do not match.'],
    	'minlength_3': translatedErrors['The password must be at least 3 characters long.']
    } );

    $(".clearOnFocus").focus(function () {
        $(this).attr('value', "");
    });

    var valeurInput = $.ez.search;

    $("#recherche").attr('value',valeurInput);

    $("#recherche").focus(function () {
        $("#menuLangue").hide();
        if (this.value == valeurInput) this.value = '';
    });

    $("#langues>a").mouseover(function(){
        $("#menuLangue").show();
    });
    $("#langues>a").focus(function(){
        $("#menuLangue").show();
    });
    $("#langues>a").click(function(){
        $("#menuLangue").toggle();
        this.blur();
        return false;
    });
    $("#langues").mouseleave(function(){
        $("#menuLangue").hide();
    });

    // Gestion du blocOnglet fiche race Felins
    function ficheFelin() {
        var heightbloc = $('#infoFelin ul li .blocContenu').height();
        var heightTitre = $('#infoFelin ul li h5').height();

        $('#infoFelin ul').css('height', heightbloc + heightTitre + 30);

        $('#infoFelin ul li h5').click( function() {
            $('#infoFelin ul li.actif').removeClass('actif');
            $(this).parent().addClass('actif');

            $(this).parent().parent().css('height', parseInt($(this).parent().find('.blocContenu').height()) + 30 + heightTitre);
        });

    }
    ficheFelin();

    $("#envoiAmi").click(function(){
        $("#overlayLightbox").show();
        $("#envoiAmiLightbox").show();
        this.blur();
        return false;
    });

    $("#envoiAmi img").mouseover(function(){
        $(this).attr('src', $.ez.ezimageroot + 'picto-envoyer-ami-on.png');
    });
    $("#envoiAmi img").mouseout(function(){
        $(this).attr('src', $.ez.ezimageroot + 'picto-envoyer-ami.png');
    });

    $("#diminuerTxt img").mouseover(function(){
        $(this).attr('src', $.ez.ezimageroot + 'picto-taille-texte-moins-on.png');
    });
    $("#diminuerTxt img").mouseout(function(){
        $(this).attr('src', $.ez.ezimageroot + 'picto-taille-texte-moins.png');
    });

    $("#augmenterTxt img").mouseover(function(){
        $(this).attr('src', $.ez.ezimageroot + 'picto-taille-texte-plus-on.png');
    });
    $("#augmenterTxt img").mouseout(function(){
        $(this).attr('src', $.ez.ezimageroot + 'picto-taille-texte-plus.png');
    });

    $("#imprimer img").mouseover(function(){
        $(this).attr('src', $.ez.ezimageroot + 'picto-imprimer-on.png');
    });
    $("#imprimer img").mouseout(function(){
        $(this).attr('src', $.ez.ezimageroot + 'picto-imprimer.png');
    });


    $("#imprimer").click(function(){
        window.print();
        this.blur();
        return false;
    });
    $(".lightBox .fermer a").click(function(){
        $("#overlayLightbox").hide();
        $(this).parent().parent().hide();
        $("#videotheque .playerFlash > div").empty();
        if($("#videotheque .playerFlash iframe").length) {
			$("#videotheque .playerFlash iframe").remove();
			$("#videotheque .playerFlash br").remove();
			$("#videotheque .playerFlash a").remove();
			$("#videotheque .playerFlash i").remove();
		}
        this.blur();
        return false;
    });
    $("#aside .imgFlash a.btVideoLightbox").click(function(){
      $("#titreVideo").text($(this).attr("title"));
        $("#descVideoAjax p").html($("#descVideo").html());

        chargeFlashVideo(this.href);


        $("#overlayLightbox").show();
        $("#videothequeLightbox").show();
        this.blur();
        return false;
    });

    $("#content a.video").click(function(){
      $("#titreVideo").text($(this).attr("title"));
        $("#descVideoAjax p").html($("#descVideo").html());

        chargeFlashVideo(this.href);


        $("#overlayLightbox").show();
        $("#videothequeLightbox").show();
        this.blur();
        return false;
    });

    $("#sliderPhoto a").click(function(){
      $("#photoContent").attr("src",this.href);
        $("#titrePhoto").text($(this).attr("title"));
        $("#descPhotoAjax p").html($("#descPhoto").html());

        $("#overlayLightbox").show();
        $("#photothequeLightbox").show();
        this.blur();
        return false;
    });

    $("#content a.photo").click(function(){
      $("#photoContent").attr("src",this.href);
        $("#titrePhoto").text($(this).attr("title"));

        var idphoto = $(this).attr("id");
        // requete ajax pour recup la description longue de la video
        $url = $.ez.ezurl + "/layout/set/photo_desc?object_id="+idphoto;
        $url.replace('//', '/');
        $.get($url, function(data){
            $("#descPhotoAjax p").html(data);
        });

        $("#overlayLightbox").show();
        $("#photothequeLightbox").show();
        this.blur();
        return false;
    });

    // Gestions des carrousels :

    $(".blocSlider").each(function(){

        var current = $(this);
        var menuMargin = 0;

        if ( current.parent().parent().attr("class") == 'lightBox' )
        {
            var marge = 76;
            var largeurSlider = 590;
        }
        else
        {
            var marge = current.find(".slider a").outerWidth(true);
            var largeurSlider = current.find(".masqueSlider").width();
        }

        var longueurSlide = ( current.find(".slider a").length * marge ) - largeurSlider - marge;

        current.children(".sliderPrec").click(function(){
            if ( menuMargin > 0 )
            {
                current.find(".masqueSlider .slider").animate({"left": "+="+marge+"px"}, "slow", "swing");
                menuMargin = menuMargin - marge;
            }
            this.blur();
            return false;
        });

        current.children(".sliderSuiv").click(function(){
          if ( menuMargin <= longueurSlide )
          {
            current.find(".masqueSlider .slider").animate({"left": "-="+marge+"px"}, "slow", "swing");
            menuMargin = menuMargin + marge;
          }
          this.blur();
          return false;
        });
    });

    // Gestion des descriptifs photos et vidéo

    $("#sliderPhoto a").bind("mouseover", function(){
        // ou chargement des textes en ajax
        var divContent = $("#descPhoto");
        var divContentReplace = $(this).find('.descPhoto').html();
        divContent.html(divContentReplace);
    });

    $("#sliderVideo a").click(function(){
        // ou chargement des textes et images en ajax
        var descVideo = $("#descVideo");
        var apercuVideo = $("#apercuVideo");
        var lienVideo = $("#aside .imgFlash a.btVideoLightbox");
        var divContentReplaceTxt = $(this).find('.descVideo').html();
        var divContentReplaceImg = $(this).find('.imageURL').text();

        var divContentReplaceHtml = $(this).attr("href");
        var divContentReplaceId = $(this).attr("class");
        var divContentReplaceTitle = $(this).attr("title");

        lienVideo.attr('href', divContentReplaceHtml);
        lienVideo.attr('id', divContentReplaceId);
        lienVideo.attr('title', divContentReplaceTitle);
        descVideo.html(divContentReplaceTxt);
        apercuVideo.attr('src', $.ez.ezroot + '/' + divContentReplaceImg);

        this.blur();
        return false;
    });


    /*
     * Gestion recherche des retailers
     */

    $('.annuaireSearch').click(function(){
    	var url = $(".url").attr('value')+"/(city)/"+$(".city").attr('value');
    	window.location = url;
     });

	$("#rechercheR").keypress(function (e){
    	var code = (e.keyCode ? e.keyCode : e.which);
    	if(code == 13) {
    		var url = $(".url").attr('value')+"/(city)/"+$(".city").attr('value');
    		window.location = url;
		}
    });

	/* EVOL BDEL Geoloc retailers */
	$("#retailers_city").keypress(function (e){
		if($("#retailers_city").attr('value') != ""){
			var code = (e.keyCode ? e.keyCode : e.which);
   	 		if(code == 13) {
   	 			geoloc();
   	 		}
		}
	});

	$("#retailers_distance").keypress(function (e){
		if($("#retailers_city").attr('value') != ""){
			var code = (e.keyCode ? e.keyCode : e.which);
   	 		if(code == 13) {
   	 			geoloc();
   	 		}
		}
	});

	$(".retailerBtn").click(function (){
		if($("#retailers_city").attr('value') != ""){
 			geoloc();
		}
	});

	function geoloc(){
		var url = $("#retailers_url").attr('value')+"/(city)/"+$("#retailers_city").attr('value');
		if($("#retailers_distance").attr('value') != ""){
			// Get city coordinates with GMaps
	    	geocoder = new GClientGeocoder();
	    	geocoder.getLatLng( $("#retailers_city").attr('value'), function readGLoc(response) {
	    		if (response){
	    			url += "/(distance)/"+$("#retailers_distance").attr('value')+"/(lat)/"+response.lat()+"/(lng)/"+response.lng();
	    		}
	    		window.location = url;
    		});
		}
		else {
			window.location = url;
		}
	}



    /*
     * Autocompletion for City
     */
    if ( $('#retailers_city').length )
    {
        $("#retailers_city").autocomplete({
                    source: "",delay: 1000
        });
        $('#retailers_city').keyup(function() {
          // on lance l'ajax sur la page php avec certains paramètres
          $ville = $('#retailers_city').val();
          $pays = $('#retailers_country_code').val();

          $.ez( 'cityautocompletion::getCity', { 'ville': $ville, 'pays':  $pays }, function( data ){

            var villes = data['content'].split(",");
              $( "#retailers_city" ).autocomplete( "option", "source", villes);
          });
        });
    }

/*
 * Daily Ratio  Help
 */
    var col = new Array();
    var row = new Array();
    var weight = new Array();
    var age = new Array();

    function update_slider() {
        $("#weight").slider({
            value:0,
            min: 0,
            max: (weight.length>0)? weight.length-1: 0,
            step: 1,
            slide: function(event, ui) {
                $("#amount").text(weight[ui.value]);
            }
        });
        $("#amount").text(weight[0]);

        $("#age").slider({
            value:0,
            min: 0,
            max: age.length-1,
            step: 1,
            slide: function(event, ui) {
                $("#amount_age").text(age[ui.value]);
            }
        });
        $("#amount_age").text(age[0]);
    }

    function initSlider(){
        var str_url = $("#url_product_ratio").attr("value")+"?lang="+$('#language').attr('value')+"&id="+$('#product_id').attr("value")+"&ratio=1";

        $.ajax({
            type: "GET",
            url: str_url,
            dataType: "xml",
            success: function(data) {
                if( $(data).find("product").children().size() > 0){
                    // DISPLAY DAILY RATION HELP
                    $("#product_table").css("display", "none");
                    $("#product_daily_ration").css("display", "block");

                    // PARSE INFORMATIONS
                    $(data).find("lign").each(function(index){
                        if($("#adult").size() > 0){
                            if(index < 3){
                                //GET THE INFORMATION FROM THE TPL
                                age[index] = $("#adult"+index).attr("value");
                            }
                        }else{
                            //GET THE INFORMATION FROM THE WS
                            age[index] = $(this).text();
                        }
                        row[index] = $(this).attr('num');
                    });

                    $(data).find("col").each(function(index){
                        weight[index] = $(this).text();
                        col[index] = $(this).attr('num');
                    });

                    update_slider();
                    get_cup_gramme();
                }
            }
        });
    }

    function get_cup_gramme() {

        if (!Array.prototype.indexOf){
        Array.prototype.indexOf = function(elt /*, from*/){
            var len = this.length;
            var from = Number(arguments[1]) || 0;
            from = (from < 0)
                ? Math.ceil(from)
                : Math.floor(from);
            if (from < 0)
            from += len;

            for (; from < len; from++){
            if (from in this &&
                this[from] === elt)
                return from;
            }
            return -1;
        };
        }

        var z = age.indexOf($("#amount_age").text());
        var j = weight.indexOf($("#amount").text());

        var str_url = $("#url_product_ratio").attr("value")+"?lang="+$('#language').attr('value')+"&id="+$('#product_id').attr("value")+"&ratio=1&row="+row[z]+"&col="+col[j];

        $.ajax({
            type: "GET",
            url: str_url,
            dataType: "xml",
            success: function(data) {
                $('#dog_ration_p_id').html($(data).find("ratio_g").text());
                $('p.dog_ration_p').ifixpng();

                if($(data).find("ratio_cup").text()==""){
                    $('.daily_ratio_cup_im').css("display","none");
                }else{
                    $('.daily_ratio_cup_im').css("display","inline");
                    $('.dog_ratio_cup').html($(data).find("ratio_cup").text());
                }
            }
        });

        /* Mantis 795 - comportement sur curseur anormal, il ne reste pas rouge */
        $('.slider_daily > a').mouseleave(function(){
            $(this).removeClass('ui-state-focus');
        });
    }

    if($("#product_daily_ration").size() > 0){
        initSlider();

        $('#button_ratio_calculate_id').mouseenter(function(){
            $(this).parent().find('.left_button_album').attr("class","left_button_album_hover");
            $(this).parent().find('.middle_button_album_input').attr("class","middle_button_album_input_hover");
            $(this).parent().find('.right_button_album').attr("class","right_button_album_hover");
        })
            .mouseleave(function(){
                $(this).parent().find('.left_button_album_hover').attr("class","left_button_album");
                $(this).parent().find('.middle_button_album_input_hover').attr("class","middle_button_album_input");
                $(this).parent().find('.right_button_album_hover').attr("class","right_button_album");
        })
            .click(function(){
                get_cup_gramme();
        });
    }

/*
 * Body Constitution
 */
    $('.button_body_constitution_body').mouseenter(function(){
        $(this).parent().find('.left_button_body_constitution_dog').attr("class","left_button_body_constitution_dog_hover");
        $(this).parent().find('.middle_button_body_constitution_dog').attr("class","middle_button_body_constitution_dog_hover");
        $(this).parent().find('.right_button_body_constitution_dog').attr("class","right_button_body_constitution_dog_hover");

        $(this).parent().find('.left_button_body_constitution_cat').attr("class","left_button_body_constitution_cat_hover");
        $(this).parent().find('.middle_button_body_constitution_cat').attr("class","middle_button_body_constitution_cat_hover");
        $(this).parent().find('.right_button_body_constitution_cat').attr("class","right_button_body_constitution_cat_hover");
    })
        .mouseleave(function(){
            $(this).parent().find('.left_button_body_constitution_dog_hover').attr("class","left_button_body_constitution_dog");
            $(this).parent().find('.middle_button_body_constitution_dog_hover').attr("class","middle_button_body_constitution_dog");
            $(this).parent().find('.right_button_body_constitution_dog_hover').attr("class","right_button_body_constitution_dog");

            $(this).parent().find('.left_button_body_constitution_cat_hover').attr("class","left_button_body_constitution_cat");
            $(this).parent().find('.middle_button_body_constitution_cat_hover').attr("class","middle_button_body_constitution_cat");
            $(this).parent().find('.right_button_body_constitution_cat_hover').attr("class","right_button_body_constitution_cat");
    })
        .click(function(){
            window.open($('#button_body_constitution_link').attr("value"));
    });

    $( '.back' ).click( function()
    {
        javascript: history.go( -1 )
    });

    ////////////////////////////////////////////// Register form //////////////////////////////////////////////

    // Validate information collection form
    $( '#Register' ).validate(
    {
        // Ignore all invisible elements
        ignore: ':hidden',
        // Do not remove this empty function! It automatically empties the error labels when the fields are corrected.
        success: function( label )
        {
        },
        // Specifies how we display the error messages
        errorPlacement: function( error, element )
        {
            var initialErrorMessage = error.text();
            var errorMessage =
                ( translatedErrors != null && translatedErrors[initialErrorMessage] != undefined ) ? translatedErrors[initialErrorMessage] : initialErrorMessage;
            $( element ).parent().parent().children( '.verror' ).first().html( errorMessage );
        },
        // If the form seems valid, just check that the password and the password confirmation are the same
        submitHandler: function( form )
        {
            if( $( '.password' ).val() === $( '.password_confirm' ).val() )
            {
                form.submit();
            }
            else
            {
                $( '.password' ).parent().parent().children( '.verror' ).html( translatedErrors['The passwords do not match.'] );
            }
        }
    });

    // Register form : display register fields OR information collection fields according to the type of user
    if( $( '#Register' ).length > 0 )
    {
        switchRegisterFormFields();

        // The right fields have to be displayed after the user changes his/her type
        $( '#informationcollection_profile' ).change( function()
        {
            switchRegisterFormFields();

            if( $( '#occupations_container' ).length != 0 )
        	{
	            // Retrieve the profile selected in the "profile" field
	            var selected_profile = $( '#informationcollection_profile :selected' ).attr( 'class' );

	            // Show all options of the occupations selector
	            $( '#occupations_container select option' ).show();

	            // Hide all options that do have a class attribute, and it is different than the selected profile
	            $( '#occupations_container select option[class][class!="' + selected_profile + '"]' ).hide();
        	}
        } );
    }

    ////////////////////////////////////////////// Member edit //////////////////////////////////////////////

    $( '#member_edit' ).validate(
    {
        // Do not remove this empty function! It automatically empties the error labels when the fields are corrected.
        success: function( label )
        {
        },
        // Specifies how we display the error messages
        errorPlacement: function( error, element )
        {
            var errorMessage =
                ( translatedErrors != null && translatedErrors[error[0].textContent] != undefined ) ? translatedErrors[error[0].textContent] : error[0].textContent;
            $( element ).parent().children( '.verror' ).first().html( errorMessage );
        },
        // If the form seems valid, just check that the password and the password confirmation are the same
        submitHandler: function( form )
        {
            form.submit();
        }
    });

 // When changing the value of the store locator input
    $( '#dealer_location' ).bind( 'keyup blur change', function( event )
    {
        $( '#dealer_location_form' ).attr( 'action', $( '#dealer_location_initial_link' ).val() + $( '#dealer_location' ).val() );
    } );
    $( '#dealer_location_footer' ).bind( 'keyup blur change', function( event )
    {
        $( '#dealer_location_form_footer' ).attr( 'action', $( '#dealer_location_initial_link_footer' ).val() + $( '#dealer_location_footer' ).val() );
    } );
});

//DISPLAY THE SUBMENU AFTER THE MENU OF THE HOMEPAGE
function gestionFleche( init, left )
{
    var flecheMenu = $('#sousMenu #flecheMenu');

    var width = 0;
    var posLeft = 235;

    for (var i = 1; i <= left ; i++) {
        width = $( '#topMenu_' + i ).innerWidth();
        if( i == left )
            width = width/2;

        posLeft += width;
    }

    if(init == 'kill') {
        flecheMenu.fadeOut();
    } else if (init) {
        flecheMenu.css('left', Math.floor(posLeft) + 'px' );
        flecheMenu.fadeIn();
    } else {
        flecheMenu.animate( {left:Math.floor(posLeft)+ 'px'}, {duration:500} )
    }
}

function showMoreInfo(prefix,index){
    $.colorbox({width:"800px", initialWidth:"100px", maxHeight:"100%", initialHeight:"100px", inline:true, href:"#"+prefix+index, open:true});
    $("#cboxOverlay").css('opacity','0.7');
}
/* XXX */
function submitForm()
{
	var actionUrl = $('input[name=urlAction]').val();
	var params = 'YourName=' + $('input[name=YourName]').val() + '&' +
				 'YourFirstName=' + $('input[name=YourFirstName]').val() + '&' +
				 'YourEmail=' + $('input[name=YourEmail]').val() + '&' +
				 'ReceiversName=' + $('input[name=ReceiversName]').val() + '&' +
				 'ReceiversFirstName=' + $('input[name=ReceiversFirstName]').val() + '&' +
				 'ReceiversEmail=' + $('input[name=ReceiversEmail]').val() + '&' +
				 'SendButton=' + $('input[name=SendButton]').val() + '&' +
				 'NodeID=' + $('input[name=NodeID]').val();
	$.ajax({
	   type: "POST",
	   url: actionUrl,
	   data: params,
	   success: function( retour ){
	     $("#envoiAmiLightbox").empty().append( retour );

	   }
	 });
	this.blur();
	return false;
}

function closeForm()
{
    $("#overlayLightbox").hide();
    $("#envoiAmiLightbox").hide();
    $(this).parent().parent().hide();
    return false;
}

// Returns the index of the pet related to the given DOM element
function getPetIndex( element )
{
    return $( element ).attr( 'name' ).substr( $( element ).attr( 'name' ).lastIndexOf( '_' ) + 1 );
}

// Update the register form so it can become a information collection form as well, and vice versa
var reg_form_type = 0;
function switchRegisterFormFields()
{
    // Tricky part first : copy all values from the pro fields to the non-pro fields when switching, and vice versa
    $( '#Register :input:visible:not(:radio)' ).each( function()
    {
        var parentDiv = $( this ).parent();

        if( parentDiv.hasClass( 'pro_field' ) )
        {
            var siblingDiv = $( parentDiv ).parent().children( '.non_pro_field' ).first();
            siblingDiv.children( ':input' ).first().val( $( this ).val() );
        }
        else if( parentDiv.hasClass( 'non_pro_field' ) )
        {
            var siblingDiv = $( parentDiv ).parent().children( '.pro_field' ).first();
            siblingDiv.children( ':input' ).first().val( $( this ).val() );
        }
    } );

    // Then the radio buttons
    if( $( '#Register :radio:checked:visible' ).length != 0 )
    {
        var radio = $( '#Register :radio:checked:visible' ),
            radioParent = $( radio ).parent(),
            childrenRadios = $( radioParent ).children( ':radio' ),
            selectedRadioIndex = 0;

        // Retrieve the index of the selected radio input
        for( selectedRadioIndex = 0; selectedRadioIndex < childrenRadios.length; selectedRadioIndex++ )
        {
            if( $( childrenRadios[selectedRadioIndex] ).attr( 'checked' ) )
                break;
        }

        var siblingDiv = $( radioParent ).parent().children( radioParent.hasClass( 'pro_field' ) ? '.non_pro_field' : '.pro_field' ).first(),
            radios = $( siblingDiv ).children( ':radio' );

        $( radios[selectedRadioIndex] ).attr( 'checked', 'checked' );
    }

    // Which form elements do we display?
    reg_form_type = ( $( '#informationcollection_profile' ).val() == 0 ) ? 0 : 1;
    var pro_display = [ 'none', 'block' ],
        non_pro_display = [ 'block', 'none' ];

    // Pro fields
    $( '.pro_field' ).css( 'display', pro_display[reg_form_type] );

    // Non-pro fields
    $( '.non_pro_field' ).css( 'display', non_pro_display[reg_form_type] );

    // Pro lines
    $( '.pro_line' ).css( 'display', pro_display[reg_form_type] );

    // Non pro lines
    $( '.non_pro_line' ).css( 'display', non_pro_display[reg_form_type] );

    // Form name
    $( '#Register' ).attr( 'name', regFormNames[reg_form_type] );

    // Form action
    $( '#Register' ).attr( 'action', regFormActions[reg_form_type] );

    // Form submit button id
    $( '#Register :submit' ).attr( 'id', regFormSubmits[reg_form_type] );

    // Form submit button name
    $( '#Register :submit' ).attr( 'name', regFormSubmits[reg_form_type] );
}

// Initializes a tmp upload for the pet with the given index
function initTmpUpload( petIndex )
{
	new AjaxUpload( 'buttonUpload_' + petIndex,
    {
        action: $.ez.ezurl + '/uploadTemp/upload',
        name: 'fileToUpload',
        hoverClass: '',
        onSubmit: function( file, extension )
        {
        },
        onComplete: function( file, response )
        {
            $( '#thumb_' + petIndex ).attr( 'src', $.ez.ezroot_upload + response );
            $( '#thumb_' + petIndex ).show();
            $( '#image_path_' + petIndex ).attr( 'value', response );
        }
    });
}

// Returns a JS Date object from a date picker string.
function getDateFromDatePickerString( datePickerString )
{
    var datePieces = datePickerString.split( '/' ),
        dateFormatWithoutSeparators = $.datepicker.regional[$.ez.lang].dateFormat.split( '/' ).join( '' ),
        dayIndex = dateFormatWithoutSeparators.indexOf( 'dd' ) / 2,
        monthIndex = dateFormatWithoutSeparators.indexOf( 'mm' ) / 2,
        yearIndex = dateFormatWithoutSeparators.indexOf( 'yy' ) / 2;

    var day = parseInt( datePieces[dayIndex], 10 ),
        month = parseInt( datePieces[monthIndex] - 1, 10 ),
        year = parseInt( datePieces[yearIndex], 10 );

   if( isNaN( day ) || isNaN( month ) || isNaN( year ) )
        return false;

    if( day < 1 || day > 31 || month < 0 || month > 11 )
        return false;
    return new Date( year, month, day );
}

$('#getVariable').ready(function(){
  if($('#getVariable').length > 0)
  {
    load();
  }
});

//Fonction lancer a chaque fois qu'un block est affiché
function runFctBlock(){
    if(typeof(animalBreed)!="undefined" && startAnimalBreed){
        animalBreed();
        startAnimalBreed = false;
    }
}

function removeFromFavourites( current_user_object_id, _node_id, _class_identifier, purge )
{
    $.ez(   'favorites::removeFavorite',
            {
                user_id: current_user_object_id,
                node_id: _node_id,
                class_identifier: _class_identifier
            },
            function()
            {
                var divFav = $( 'div.fav_' + _node_id );
                $( divFav ).next( 'div.separator' ).remove();
                $( divFav ).remove();
                $( '#all_favourites div.favourite' ).removeClass( 'row_light' );
                $( '#all_favourites div.favourite' ).removeClass( 'row_dark' );
                $( '#all_favourites div.favourite:odd' ).addClass( 'row_dark' );
                $( '#all_favourites div.favourite:even' ).addClass( 'row_light' );
            }
    );
}

function purgeFromFavourites( _node_id )
{
    $.ez(   'favorites::removeFavorite',
            {
                node_id: _node_id,
                purge: true
            }
    );
}

function hideFavourites()
{
    $('.favourite_category').hide();
}

function showFavourites()
{
    $('.favourite_category').show();
}

function showFavouritesCategory(favourite_number, id)
{
	$('#no_favourite').hide();
	hideFavourites();
	$('#'+id+'_favourites').show();
	if (id == 'all')
	{
		if (favourite_number==0)
		{
			$('#no_favourite').show();
		}
	}
	else if ( $('#'+id+'_favourites > *').length == 0 )
	{
		$('#no_favourite').show();
	}
}

