﻿/**************************************************************************************/
/*  AMO - Expertime                                                                   */
/*                                                                                    */
/*							     Authentification		                              */
/*                                                                                    */
/*                                                                      June 2008     */
/**************************************************************************************/


var WSUrl = '/WebServices/wsplanet.asmx';
var SOAPHeaderLogin = 'User';
var SOAPHeaderPwd = 'Pass';

var result = -10;

var pass;
var mail;
var remember;

/********************************************/
//	FillUserLoginScript
//	Fill data for login form
/********************************************/
function FillUserLoginScript(email, password, rememberpwd) {
    //alert('FillUserLoginScript(email='+email+', password='+password+', rememberpwd='+rememberpwd+')');
    $("#popinEmail").val(email);
    $("#popinMotDePasse").val(password);
    $("#retenir").attr("checked", rememberpwd);
}



/********************************************/
//	CheckLoginSubmit
//	Verify form and launch login process
/********************************************/
function CheckLoginSubmit() {
    try {
        if (CheckForm()) {
            if (AjaxInitialize()) {
                Login();
            }
        }
        else {
            return false;
        }
    }
    catch (ex) {
        alert('CheckLoginSubmit()\r\nErreur : ' + ex);
    }
    return false;
}

/********************************************/
//	Login 
//	Call WebService Authentification method
/********************************************/
function Login() {
    try {
        // Create the SOAP Envelope
        strEnvelope = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
        strEnvelope += '   <soap:Header>';
        strEnvelope += '    <CredentialHeader xmlns="http://planetvertbaudet.services.org/">';
        strEnvelope += '      <UserName>' + SOAPHeaderLogin + '</UserName>';
        strEnvelope += '      <Password>' + SOAPHeaderPwd + '</Password>';
        strEnvelope += '    </CredentialHeader>';
        strEnvelope += '  </soap:Header>';
        strEnvelope += '  <soap:Body>';
        strEnvelope += '    <AuthenticateUserAndSave xmlns="http://planetvertbaudet.services.org/">';
        strEnvelope += '      <userName>' + mail + '</userName>';
        strEnvelope += '      <passWord>' + pass + '</passWord>';
        strEnvelope += '      <remember>' + remember + '</remember>';
        strEnvelope += '    </AuthenticateUserAndSave>';
        strEnvelope += '  </soap:Body>';
        strEnvelope += '</soap:Envelope>';

        // Set up the post
        objHttp.onreadystatechange = GetLoginResult;
        objHttp.open("post", WSUrl);
        objHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        objHttp.setRequestHeader("SOAPAction", "http://planetvertbaudet.services.org/AuthenticateUserAndSave");
        objHttp.send(strEnvelope);
    }
    catch (ex) {
        alert('Login(' + mail + ', ' + pass + ', ' + remember + ')\r\nErreur : ' + ex);
    }
}

/********************************************/
//	GetLoginResult 
//	Fires when WS return results
/********************************************/
function GetLoginResult() {
    try {
        if (objHttp.readyState == 4) {
            ParseXMLResult();
        }
    }
    catch (ex) {
        alert('GetLoginResult()\r\nErreur : ' + ex);
    }
}

/********************************************/
//	ParseXMLResult 
//	Parse WS XML result for login returns
/********************************************/
function ParseXMLResult() {
    result = 0;
    try {
        var xmlResult = objHttp.responseText;
        var startPos = xmlResult.indexOf('</AuthenticateUserAndSaveResult>') - 2;
        var stopPos = xmlResult.indexOf('</AuthenticateUserAndSaveResult>');
        if (startPos > 0 && stopPos > startPos) {
            var tempResult = xmlResult.substring(startPos, stopPos);
            if (tempResult.match('>')) {
                tempResult = xmlResult.substring(startPos + 1, stopPos);
            }
            result = parseInt(tempResult);
        }

        Redirect();
    }
    catch (ex) {
        alert('ParseXMLResult()\r\nErreur : ' + ex); //+ '\r\n' + objHttp.responseText);
    }
}


/********************************************/
//	Redirect 
//	If login success call HttpHandler process
/********************************************/
function Redirect() {

    // test login
    //alert("redirect");
    
    
    try {
        RegisterLoginOmnitureTag();
    }
    catch (ex) {
        alert('Probleme Tag Omniture)\r\nErreur : ' + ex);
    }

    try {
        if (result == 1) {
            // var url = escape(window.location.href);
            // window.location = '/Account/Authentification.ashx?l=' + mail + '&p=' + pass + '&r=' + remember + '&returnUrl=' + url;
            var url = window.location.href;
            if ($("[id$='hiddenLoginRedirect']").attr('value') != '') {
                url = $("[id$='hiddenLoginRedirect']").attr('value');
 
            }
            window.location = url;
        }
        else {
            if (result == -1 || result == 0) {
                alert("Votre nom d'utilisateur ou votre mot de passe est incorrect.\r\nMerci de réessayer.\r\nVérifiez que la touche 'Majuscules' de votre clavier n'est pas verrouillée.");

            }
            else if (result == 2) {
                alert("Votre compte n'est pas activé. Vous allez etre redirigé vers la page d'activation.");
                window.location.replace("/Account/ConfirmationInscription.aspx?email=" + mail);
            }
            else if (result == 5) {
                alert("Vous ne pouvez plus vous connectez sur le site.");
            }
            else {
                alert("Une erreur s'est produite (Code : " + result.toString() + ")");
            }
        }
    }
    catch (ex) {
      alert('Redirect (Result = ' + result + ')\r\nErreur : ' + ex);
    }
}

function RegisterLoginOmnitureTag() {
    var s = s_gi(OmnitureReportSuite);
    s.linkTrackVars = 'events';
    s.linkTrackEvents = 'event11';
    s.events = 'event11';
    s.tl(this, 'o', 'Login');
}


/**************************************************************************************/
/*                                                                                    */
/*                                                                                    */
/*							     Form Check Tools		                              */
/*                                                                                    */
/*                                                                                    */
/**************************************************************************************/


function CheckForm() {
    var error = CheckField($("#popinMotDePasse"));
    error |= CheckField($("#popinEmail"));

    if (error) {
        $('#errorSummary').show();
        return false;
    }
    else {
        $('#errorSummary').hide();
        pass = $("#popinMotDePasse").val();
        mail = $("#popinEmail").val();
        remember = $("#retenir").attr('checked');
        return true;
    }
    return false;
}


function CheckField(field) {
    // is empty ?
    if ($(field).val() == '') {
        setError($(field));
    }
    // is valid ? (for emails)
    else if ($(field).attr('class').indexOf('mandatoryEmailLogin') != -1) {
        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

        if (!(emailPattern.test($(field).val()))) {
            setError($(field));
        }
        else {
            eraseError($(field));
        }
    }
    else {
        eraseError($(field));
    }
}


