jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function popUpConnexion() {

    var form = $.ajax({
        url: "/moduleConnexionMembres/formConnexion.php",
        async: false
    }).responseText;

    $(form).dialog({
        bgiframe: true,
        resizable: false,
        height:'auto',
        width:400,
        modal: true,
        minHeight:0,
        buttons: {
            'Annuler': function() {
                $(".dialogConnexion").dialog('destroy');
                clearValForm('#formConnexion');
            },
            'Ok': function() {
                var valeurForm = $('#formConnexion').serialize();
                $.post("/moduleConnexionMembres/connexion.php",
                {
                    'valeur':valeurForm
                },
                function(data){
                    
                    if(data==1){
                        $('<div class="dialogDestroy" title="Article signalé">\n\
                                <p>Vous êtes maintenant connecté sur Mobcustom</p></div>').dialog({
                            bgiframe: true,
                            resizable: false,
                            height:'auto',
                            width:400,
                            modal: true,
                            minHeight:0
                        });

                        loadZoneConnexion();
                        setTimeout("popUpTimerClose('.dialogDestroy')",2000);
                        setTimeout("popUpTimerClose('.dialogConnexion')",2000);
                        setTimeout("clearValForm('#formConnexion')",2000);
                    }

                    if(data==2) {
                        $('<div class="dialogDestroy" title="Vérifiez vos identifiants">\n\
                                <p>Vous avez spécifié un nom d\'utilisateur ou un mot de passe incorrect, veuillez recommencer</p></div>').dialog({
                            bgiframe: true,
                            resizable: false,
                            height:'auto',
                            width:400,
                            modal: true,
                            minHeight:0,
                            buttons: {
                                'OK': function() {
                                    $(".dialogDestroy").dialog('destroy');
                                    $(".dialogConnexion").dialog('destroy');
                                    clearValForm('#formConnexion');
                                    popUpConnexion(); // on re ouvre automatiquement le formulaire
                                }
                            }
                        });
                    }

                    if(data==0) {
                        $('<div class="dialogDestroy" title="Erreur serveur">\n\
                                <p>Veuillez nous excuser, une erreur serveur est survenue, recommencez plus tard</p></div>').dialog({
                            bgiframe: true,
                            resizable: false,
                            height:'auto',
                            width:300,
                            modal: true,
                            minHeight:0
                        });

                        setTimeout("popUpTimerClose('.dialogDestroy')",2000);
                        setTimeout("popUpTimerClose('.dialogConnexion')",2000);
                        setTimeout("clearValForm('#formConnexion')",2000);
                    }

                    if(data==3) {
                        $('<div class="dialogDestroy" title="Attention">\n\
                                <p>Trop de tentatives de connexion ont été enregistrées, veuillez essayer plus tard</p><br/><br/>\n\
                                <p>Pour plus de renseignements, <a href=http://www.mobcustom.com/contact>contactez-nous</a></p></div>').dialog({
                            bgiframe: true,
                            resizable: false,
                            height:'auto',
                            width:400,
                            modal: true,
                            minHeight:0,
                            buttons: {
                                'OK': function() {
                                    $(".dialogDestroy").dialog('destroy');
                                    $(".dialogConnexion").dialog('destroy');
                                    clearValForm('#formConnexion');
                                }
                            }
                        });
                    }

                    if(data==6) {
                        $('<div class="dialogDestroy" title="Attention">\n\
                                <p>Votre adresse IP n\'a pas pu être récupérée</p><br/><br/>\n\
                                <p>Pour plus de renseignements, <a href=http://www.mobcustom.com/contact>contactez-nous</a></p></div>').dialog({
                            bgiframe: true,
                            resizable: false,
                            height:'auto',
                            width:400,
                            modal: true,
                            minHeight:0,
                            buttons: {
                                'OK': function() {
                                    $(".dialogDestroy").dialog('destroy');
                                    $(".dialogConnexion").dialog('destroy');
                                    clearValForm('#formConnexion');
                                }
                            }
                        });
                    }

                    if(data==7) {
                        $('<div class="dialogDestroy" title="Attention">\n\
                                <p>Vous avez effectué trop de tentatives de connexion, veuillez essayer dans 24h</p><br/><br/>\n\
                                <p>Pour plus de renseignements, <a href=http://www.mobcustom.com/contact>contactez-nous</a></p></div>').dialog({
                            bgiframe: true,
                            resizable: false,
                            height:'auto',
                            width:400,
                            modal: true,
                            minHeight:0,
                            buttons: {
                                'OK': function() {
                                    $(".dialogDestroy").dialog('destroy');
                                    $(".dialogConnexion").dialog('destroy');
                                    clearValForm('#formConnexion');
                                }
                            }
                        });
                    }
                    
                    //on ecrase les propriétés du overlay
                    $(".ui-widget-overlay").css("opacity","0.5");
                    $(".ui-widget-overlay").css("background","none");
                    $(".ui-widget-overlay").css("background-color","#000");

                    //au clic sur la croix en haut a droite
                    $(".ui-dialog-titlebar-close").click(   function ()
                    {
                        $(".dialogConnexion").dialog('destroy');
                        clearValForm('#formConnexion');
                    }
                    );
                }
                );
            }
        }
    });

    //au clic sur la croix en haut a droite
    $(".ui-dialog-titlebar-close").click(   function ()
    {
        $(".dialogConnexion").dialog('destroy');
        clearValForm('#formConnexion');
    }
    );

    //on ecrase les propriétés du overlay
    $(".ui-widget-overlay").css("opacity","0.5");
    $(".ui-widget-overlay").css("background","none");
    $(".ui-widget-overlay").css("background-color","#000");
}

function popUpTimerClose(popup) {
    $(popup).dialog('destroy');
}

function clearValForm(input) {
    $(input).remove();
}

function loadZoneConnexion() {

    $.post("/moduleConnexionMembres/testSiConnecte.php",
    
        function(data){
        
            if(data==1) {
                $("#zoneConnexionInscription").load("/moduleConnexionMembres/recupInfosMembre.php", {limit: 25}, function(){
   					redimAvatar();
 				});
            }
        }
        );
}

function popUpDeconnexion() {

    $.post("/moduleConnexionMembres/deconnexion.php",

        function(data){

            if(data==1) {
                $('<div class="dialogDestroy" title="Merci de votre visite">\n\
                        <p>Vous êtes maintenant déconnecté.<br/>A bientôt sur le réseau Custom</p><br/><br/>\n\
                    </div>').dialog({
                    bgiframe: true,
                    resizable: false,
                    height:'auto',
                    width:'auto',
                    modal: true,
                    minHeight:0
                });
                setTimeout("popUpTimerClose('.dialogDestroy')",3000);

                //recharge la zone connexion en mode deconnecté
                var zone = '<a id="inscription" href="http://www.mobcustom.com/inscription"><span class="flecheInscription">&nbsp;</span>Devenir membre</a>\n\
                            <a id="connexion" href="javascript:popUpConnexion()"><span class="flecheInscription">&nbsp;</span>Se connecter</a>';
                $("#zoneConnexionInscription").html(zone);
            }

            if(data==0) {
                $('<div class="dialogDestroy" title="Attention">\n\
                        <p>Vous n\'avez pas pu être déconnecté à cause d\'un problème serveur, merci d\'essayer plus tard</p><br/><br/>\n\
                    </div>').dialog({
                    bgiframe: true,
                    resizable: false,
                    height:'auto',
                    width:'auto',
                    modal: true,
                    minHeight:0
                });
                setTimeout("popUpTimerClose('.dialogDestroy')",3000);
            }
        }
        );

    //on ecrase les propriétés du overlay
    $(".ui-widget-overlay").css("opacity","0.5");
    $(".ui-widget-overlay").css("background","none");
    $(".ui-widget-overlay").css("background-color","#000");
}


/////////Redim images/////////
function redimAvatar() {
    $('.avatarSmallZoneConnexion').each(function() {
        var maxWidth = 60; // Max width for the image
        var maxHeight = 30;    // Max height for the image
        var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height

        // Check if the current width is larger than the max
        if(width > maxWidth){
            ratio = maxWidth / width;   // get ratio for scaling image
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }

        // Check if current height is larger than max
        if(height > maxHeight){
            ratio = maxHeight / height; // get ratio for scaling image
            $(this).css("height", maxHeight);   // Set new height
            $(this).css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }
    });
}


$(document).ready(  function() {
	if($.cookie('PHPSESSID')) {
		loadZoneConnexion();
	}
});
