$(document).ready( function() {

    /************************************
    *                            INIT CSS
    *************************************/
    $("#userland #lostPasswordButton").show();
    $("#userland #lostPasswordForm").css('border', 'none');
    $("#userland div:first").addClass('javascript');


    /************************************
    *                         INIT LABELS
    *************************************/
    $("#loginForm").find("label").inFieldLabels();
    $("#lostPasswordForm").find("label").inFieldLabels();
    $("#formulaireInscription").find("label[class='labelBlock']").inFieldLabels();


    /************************************
    *                       HIDE ELEMENTS
    *************************************/
    $("#loginForm").hide();
    $("#lostPasswordForm").hide();


    /************************************
    *                   EFFECTS LISTENERS
    *************************************/
    var timer;
    $("#userland").hover(
        function() {
            //alert('clear');
            clearTimeout(timer);
        },
        function(){
            timer = setTimeout( function()
                        {
                            $("#loginForm").slideUp('normal');
                            $("#lostPasswordForm").slideUp('normal');
                        }, 1500);
        }
    );

    initLogin();
    initLostPassword();

    $("#connectButton").mouseover(
        function() {
                // displaying effects
            $("#lostPasswordForm").slideUp('normal', function(){
            $("#loginForm").slideDown('normal');
            });
        }
    );

    $("#accountAccessButton").mouseover(function() {
        $("#accountOptionsBox").slideDown('normal');
    });

    /************************************
    *                     CLICK LISTENERS
    *************************************/
    $("#lostPasswordButton").click(function() {

        // displaying effects
        $("#loginForm").slideUp('normal', function(){
                $("#lostPasswordForm").slideDown('normal');
            });
          return false;
    });


    /************************************
    *                          VERIF FORM
    *************************************/
    // gestion des champs dupliqués (vérification à la frappe)
    $("input.inputText").each(function(){
        if($(this).attr("name").match(/email/)) {
            $(this).keyup(function() {
                checkFieldsMatch('email');
            });
            $(this).blur(function() {
                checkFieldsMatch('email');
            });
        }
    });

    $("input.inputPass").each(function(){
        $(this).keyup(function() {
          checkFieldsMatch('pass');
        });
    });

    /************************************
    *                     INIT AJAX LINKS
    *************************************/
    $('#userland #serviceLinks a#createAccountButton').click(function()
        {
            $.address.value($(this).attr('href'));
            return false;
    });


    //////////////////////////////////////////////////////
    //////////////////////////////////////////////////////
    //////////////////////////////////////////////////////
        $('#logout').click(function(e){
            $('#userland').load('ajax_id.php?logout');
            reLoad()
            return false;
        });
    //////////////////////////////////////////////////////
    //////////////////////////////////////////////////////
    //////////////////////////////////////////////////////

    $('#userland #espaceMembre ul li a[target!="_blank"]').click(function(){
        $.address.value($(this).attr('href'));
        return false;
    });
});


/************************************
*                          INIT LOGIN
*************************************/
function initLogin() {


    // handle login, build a hash with concatenated username + ':' + pass
    $("#loginForm").submit(function() {

        //alert("received ajax call to login");
        var login   = $(this).find("input[name=login]").val();
        var pass    = $(this).find("input[name=password]").val();
        var lsticky = $(this).find("input[type=sticky]").checked; //????
        var lang    = $(this).find("input[name=lang]").val();
        var urlfin  = $(this).attr("action");

        if(login=='' || pass=='') {
            //alert("login or password is missing, please try again");
            return false;
        }

        var lhash   = $.md5(login+':'+pass);
        //alert("sending hash : "+lhash);
        // reset password field
        $(this).find("input[name=password]").val('');
        ajaxLogin({
            'hash'   : lhash,
            'sticky' : typeof(lsticky)=='undefined'?false:true,
            'lang'   : lang,
            'action' : urlfin
        });

        return false;
    });

}


/************************************
*                   INIT LOSTPASSWORD
*************************************/
function initLostPassword() {


    // fill in field
    $("#lostPasswordForm").find("input[name=lostPasswordEmail]").val($("#loginForm").find("input[name=login]").val());

    // listener submit
    $("#lostPasswordForm").submit(function() {
          var email = $(this).find("input[name=lostPasswordEmail]").val();
          var lang  = $(this).find("input[name=lang]").val();
          var urlfin  = $(this).attr("action");

          ajaxLostPassword({
            'email'  : email,
            'lang'   : lang,
            'action' : urlfin
          });

          return false;
    });

}

/************************************
*                SEND TO LOGIN SCRIPT
*************************************/
function ajaxLogin(o) {

  $.ajax({

      url      : o['lang']+'/'+$('#connectButton').html().replace(' ','').toLowerCase(),
      type     : 'POST',
      data     : o,
      dataType : 'xml',
      timeout  : 3000, // bigger timeout lets the php login script use sleep() to minimize DDOS attempts

      error: function(e) {
        // server or network error
        alert(e);
      },

      success: function(xml)
      {
            // handle errors
            $(xml).find("error").each(
                function()
                {
                    if($(this).text()!='')
                    {
                        alert($(this).text());
                        return;

                    }

                });

            $('#userland').load('ajax_id.php');

            if($(xml).find('success').text() != '')
            {
                reLoad();
            };

            return false;
            // whatever happens, don't care as it only updates session and cookie
      }
  });
}

/************************************
*         SEND TO LOSTPASSWORD SCRIPT
*************************************/
function ajaxLostPassword(o) {
  //alert("preparing ajax call");
  $.ajax({
      url      : o['lang'] + '/lost-password',
      type     : 'POST',
      data     : o,
      dataType : 'xml',
      timeout  : 3000, // bigger timeout lets the php script use sleep() to minimize DDOS attempts

      error: function(x, txt, e) {
            alert('wtf : ' +txt + "\nerr : " + e);
            $.debug.print_r(this, 'debugContent');
            return false;
            // server or network error
      },

      success: function(xml) {
            //alert("Password Sen);
            var errors = $(xml).find("error").text();
            if(errors!='') {
              alert("Errors : " + errors);
            } else {
              alert($(xml).find("success").text());
              $("#lostPasswordForm").hide(300);
            }
            return false;
            // show a message like "check your email"
      }
  });
}


/************************************
* checks if pass are not empty, checks if fieldVal1 = fieldVal2, and checks if valid email when fieldname contains 'email'
* @fieldPrefix : name of the field to check
*************************************/
function checkFieldsMatch(fieldPrefix) {
    var fieldVal1 = $('input[name='+fieldPrefix+']').val();
    var fieldVal2 = $('input[name='+fieldPrefix+'_confirm]').val();
    if(    fieldVal1!=fieldVal2
        || fieldVal2==''
        || fieldVal2=='undefined'
        || fieldVal1==''
        || fieldVal1=='undefined'
        || ( fieldPrefix.match(/email/) && (!mailTest(fieldVal1)||!mailTest(fieldVal2)))
        )
    {
        $('input[name='+fieldPrefix+']').css("borderColor", "darkred");
        $('input[name='+fieldPrefix+'_confirm]').css("borderColor", "darkred");
        return false;
    } else
    {
        $('input[name='+fieldPrefix+']').css("borderColor", "#898083");
        $('input[name='+fieldPrefix+'_confirm]').css("borderColor", "#898083");
        return true;
    }
}


function reLoad()
{
    //alert('reload');
    if($.address.value() != null && $.address.value() != '/')
    {
        //alert($.address.value().replace(new RegExp("^['\/']+", "g"), ""));
        $.ajax({
            type: 'POST',
            url: $.address.value().replace(new RegExp("^['\/']+", "g"), ""),
            dataType: 'html',
            success: function(data)
            {
                $('#contenu').html(data);
            }
        });
    }

}