$(document).ready(function() {  

    $( '.oubliMdp' ).click( function() {
    
        $.ajax({     
            type        : 'POST',
            url         : 'ajax/oubli_mdp.ajax.php',
            contentType : 'application/x-www-form-urlencoded;charset=ISO-8859-15',
            beforeSend  : function() {
                
                    $( '.oubliMdpSection' ).hide( 'fast' ).remove();
                    
                },
            success     : function( datas ) {
                
                    $( '#section' ).before( datas );
                    $( '.oubliMdpSection' ).show( 'blind' );
                    
                    $( '#renvoi' ).submit( function() {
                        
                        $.ajax({     
                            type        : 'POST',
                            url         : 'ajax/send_mdp.ajax.php',
                            contentType : 'application/x-www-form-urlencoded;charset=ISO-8859-15',
                            data        : ({ 
                                mail           : $( 'input[name=oubli_email]' ).val(),
                            }),  
                            success     : function( datas ) {

                                    $( '.redAlert' ).html( datas );
                                    
                                }
                                
                        });
                        
                        return false;    
                    
                    });
                    
                }
                
        });    
        
        
        
    });  

    resize_header();
    
    $(window).resize(function() {
        resize_header();
    });
    
    $.backstretch("http://www.kibodio.com/css/img/background.jpg");
    
    $(window).bind('load', function () {
        $('#logo_kibodio, #logo_3dnn').cross();
    });
    
    $('#blocLogo ul').hover( function() {
        $( this ).css( 'height' , 'auto' ); 
    }, function() {
        $( this ).css( 'height' , '24px' ); 
    });
    
    $( '#identify' ).bind( 'submit' , function() {

        $.ajax({     
            type        : 'POST',
            url         : 'ajax/identification.ajax.php',
            data        : ({ 
                    login           : $( 'input[name=identify_login]' ).val(),
                    password        : $( 'input[name=identify_password]' ).val(),
                }),  
            dataType    : 'json',
            contentType : 'application/x-www-form-urlencoded;charset=ISO-8859-15',
            beforeSend  : function() {
                
                    $( '#identify' ).css( 'opacity' , '0.4' );
                    
                },
            success     : function( datas ) {
                
                    $( '#identify' ).css( 'opacity' , '1.0' ); 

                    $.each( datas , function( key , val ) {
                        
                        if ( key == 'empty' ) {

                            location.reload();       
                            
                        } else {
                        
                            alert( val );   
                            
                        }
                        
                    });  

                }
                
        });
        
        return false;
        
    });
    
    $( '.logout' ).click( function() {
    
         $.ajax({     
            type        : 'POST',
            url         : 'ajax/logout.ajax.php',
            dataType    : 'json',
            contentType : 'application/x-www-form-urlencoded;charset=ISO-8859-15',
            beforeSend  : function() {
                
                    $( '.logout' ).css( 'opacity' , '0.4' );
                    
                },
            success     : function( datas ) {
                
                    $( '.logout' ).css( 'opacity' , '1.0' ); 
                    location.reload(); 

                }
                
        });    
    });
    
    if ( $( '#fb-root' ).length !== 0 ) {
        window.fbAsyncInit = function() {
            FB.init({ appId : '$fb_user' , status : true , cookie : true , xfbml : true });
            FB.Event.subscribe( 'auth.login' , function( response ) {     

                if (response.authResponse) {

                    var reponse = response.authResponse; 
                    $.ajax({
                        type        : 'POST',
                        url         : 'ajax/fb_connect.ajax.php',
                        data        : ({
                                uid             : reponse.userID ,
                                access_token    : reponse.accessToken
                            }), 
                       contentType  : 'application/x-www-form-urlencoded;charset=ISO-8859-15',
                       success      : function( datas ) {

                           if (datas != '') {

                               window.location.href = datas;
                               
                           }
     
                       }
                    });
                }
            });

        };
        (function() {
            var e = document.createElement('script');
            e.type = 'text/javascript';
            e.src = document.location.protocol + '//connect.facebook.net/fr_FR/all.js#appId=225312357494782&xfbml=1';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }());
    }
    
});

function disqus_config() {

    this.callbacks.onNewComment = [function(comment) {

        send_historic_action( 'comment' , comment.text );

    }];
    
}

function send_historic_action( type , content ) {
    
    $.ajax({     
        type        : 'POST' ,
        url         : 'ajax/save_action.ajax.php' ,
        data        : ({ 
                type        :   type ,
                content     :   content
            }),  
        contentType : 'application/x-www-form-urlencoded;charset=ISO-8859-15'      
    });           
    
}

function resize_header() {
    
    var margin      = Math.max ( ( $('body').width() - 1600 ) / 2 , -295 );
    var max_width   = Math.max ( Math.min( $(window).width() - margin , 1600 ) , 1275 );
    
    $('#blocLogo').css({'margin-left' : margin + 'px', 'width' : max_width + 'px' }); 
    
}

/*
* Vérification qu'une chaine correspond au format d'une adresse mail
*
* @param string emailAddress Chainte ŕ vérifier
* @return boolean La chainte est-elle ou non un mail
*/
function is_mail( mail ){
    
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    
    return re.test( mail );

}

/*
 * jQuery Backstretch
 * Version 1.2.2
 * http://srobbin.com/jquery-plugins/jquery-backstretch/
 *
 * Add a dynamically-resized background image to the page
 *
 * Copyright (c) 2011 Scott Robbin (srobbin.com)
 * Dual licensed under the MIT and GPL licenses.
*/

(function($) {

    $.backstretch = function(src, options, callback) {
        var defaultSettings = {
            centeredX: true,         // Should we center the image on the X axis?
            centeredY: true,         // Should we center the image on the Y axis?
            speed: 0                 // fadeIn speed for background after image loads (e.g. "fast" or 500)
        },
        container = $("#backstretch"),
        settings = container.data("settings") || defaultSettings, // If this has been called once before, use the old settings as the default
        existingSettings = container.data('settings'),
        rootElement = ("onorientationchange" in window) ? $(document) : $(window), // hack to acccount for iOS position:fixed shortcomings
        imgRatio, bgImg, bgWidth, bgHeight, bgOffset, bgCSS;
                
        // Extend the settings with those the user has provided
        if(options && typeof options == "object") $.extend(settings, options);
    
        // Initialize
        $(document).ready(_init);
  
        // For chaining
        return this;
    
        function _init() {
            // Prepend image, wrapped in a DIV, with some positioning and zIndex voodoo
            if(src) {
                var img;
                
                // If this is the first time that backstretch is being called
                if(container.length == 0) {
                    container = $("<div />").attr("id", "backstretch")
                                            .css({left: 0, top: 0, position: "fixed", overflow: "hidden", zIndex: -999999, margin: 0, padding: 0, height: (0.6875 * $(window).width() + 'px'), width: "100%"});
                } else {
                    // Prepare to delete any old images
                    container.find("img").addClass("deleteable");
                }
                
                img = $("<img />").css({position: "absolute", display: "none", "margin-top": "120px", padding: 0, border: "none", zIndex: -999999})
                                  .bind("load", function(e) {                                          
                                      var self = $(this),
                                          imgWidth, imgHeight;
                                          
                                      self.css({width: "auto", height: "auto"});
                                      imgWidth = this.width || $(e.target).width();
                                      imgHeight = this.height || $(e.target).height();
                                      imgRatio = imgWidth / imgHeight;

                                      _adjustBG(function() {
                                          self.fadeIn(settings.speed, function(){
                                              // Remove the old images, if necessary.
                                              container.find('.deleteable').remove();
                                              // Callback
                                              if(typeof callback == "function") callback();
                                          });
                                      });
                                      
                                  })
                                  .appendTo(container);
                 
                // Append the container to the body, if it's not already there
                if($("body #backstretch").length == 0) {
                    $("body").append(container);
                }
                
                // Attach the settings
                container.data("settings", settings);
                    
                img.attr("src", src); // Hack for IE img onload event
                // Adjust the background size when the window is resized or orientation has changed (iOS)
                $(window).resize(_adjustBG);
            }
        }
            
        function _adjustBG(fn) {
            try {
                bgCSS = {left: 0, top: 0}
                bgWidth = rootElement.width();
                bgHeight = bgWidth / imgRatio;
                
                // Make adjustments based on image ratio
                // Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
                if(bgHeight >= rootElement.height()) {
                    bgOffset = (bgHeight - rootElement.height()) /2;
                    if(settings.centeredY) $.extend(bgCSS, {top: "-" + bgOffset + "px"});
                } else {
                    bgHeight = rootElement.height();
                    bgWidth = bgHeight * imgRatio;
                    bgOffset = (bgWidth - rootElement.width()) / 2;
                    if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
                }

                $("#backstretch, #backstretch img:last").width( bgWidth ).height( bgHeight )
                                                        .filter("img").css(bgCSS);
            } catch(err) {
                // IE7 seems to trigger _adjustBG before the image is loaded.
                // This try/catch block is a hack to let it fail gracefully.
            }
      
            // Executed the passed in function, if necessary
            if (typeof fn == "function") fn();
        }
    };
  
})(jQuery);

(function ($) {
    $.fn.cross = function (options) {
        return this.each(function (i) { 
            // cache the copy of jQuery(this) - the start image
            var $$ = $(this);
            
            // get the target from the backgroundImage + regexp
            var target = $$.css('backgroundImage').replace(/^url|[\(\)'"]/g, '');

            // nice long chain: wrap img element in span
            $$.wrap('<span style="position: relative;"></span>')
                // change selector to parent - i.e. newly created span
                .parent()
                // prepend a new image inside the span
                .prepend('<img>')
                // change the selector to the newly created image
                .find(':first-child')
                // set the image to the target
                .attr('src', target);

            // the CSS styling of the start image needs to be handled
            // differently for different browsers
            if ($.browser.msie || $.browser.mozilla) {
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : '',
                    'top' : this.offsetTop
                });
            } else if ($.browser.opera && $.browser.version < 9.5) {
                // Browser sniffing is bad - however opera < 9.5 has a render bug 
                // so this is required to get around it we can't apply the 'top' : 0 
                // separately because Mozilla strips the style set originally somehow...                    
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : '',
                    'top' : "0"
                });
            } else { // Safari
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : ''
                });
            }

            // similar effect as single image technique, except using .animate 
            // which will handle the fading up from the right opacity for us
            $$.hover(function () {
                $$.stop().animate({
                    opacity: 0
                }, 500);
            }, function () {
                $$.stop().animate({
                    opacity: 1
                }, 500);
            });
        });
    };
    
})(jQuery);

