$(document).ready(initJs);
var dataUrl;
var popinOk = false;
/*Initialisation du JavaScript lorsque la DOM est chargé*/
function initJs() {
    var countPage = parseInt(getCook("countPage"));
    if (getCook("disablePopin")!="1") {
        if (isNaN(countPage)) {
            countPage=0;
        }
        setCook("countPage", (countPage + 1), (24*60));
        if ((countPage + 1) > 2) {
            afficherPopin();
        }
    }
}

function masquerPopin() {
    $("#popin").fadeOut("slow");
    if (!popinOk) {
        setCook("disablePopin", "1", (5*24*60));
    }
}
function afficherPopin() {
    var tabCountPopin = new Array();
    tabCountPopin["type"] = "POST";
    tabCountPopin["dataType"] = "xml";
    tabCountPopin["url"] = "/module/load-ajax.php";
    tabCountPopin["data"] = "action=countPopin";
    $("#popin").fadeIn("slow");
    $.ajax(tabCountPopin);
}
function soumettrePopin() {
    /*Recupération des données*/
    var tabDataPopin = new Array();
    $("#popin #erreurPopin").empty();
    dataUrl='';
    $("#popin .InscriptionNewsletter .content div#newsletter p :input").each(construcUrl);
    tabDataPopin["type"] = "POST";
    tabDataPopin["dataType"] = "xml";
    tabDataPopin["url"] = "/module/load-ajax.php";
    tabDataPopin["data"] = "action=soumettrePopin"+dataUrl;
    tabDataPopin["success"] = function(xml) {
        var msg = $("message",xml).text();
        if ($("resaissir",xml).text()=="0") {
            $("#popin .InscriptionNewsletter .content div#newsletter p").empty();
            $("#popin .InscriptionNewsletter .content div#newsletter #succesPopin").empty();
            $("#popin .InscriptionNewsletter .content div#newsletter #succesPopin").append(msg);
            popinOk = true;
            setCook("disablePopin", "1", (100*365*24*60));
            setTimeout("masquerPopin()", 700);
        }
        else {
            $("#popin #erreurPopin").append(msg);
        }
    };
    tabDataPopin["error"] =  function() {
        $("#popin .InscriptionNewsletter .content div#newsletter #succesPopin").empty();
        $("#popin .InscriptionNewsletter .content div#newsletter #succesPopin").append("Désolé, nous n'avons pas pu prendre en compte votre inscription. Merci de réessayer plus tard.");
        popinOk = true;
        setCook("disablePopin", "1", (1*60));
    };
    $.ajax(tabDataPopin);
}
function construcUrl() {
    dataUrl = dataUrl+"&"+$(this).attr("name")+"="+$(this).attr("value");
}
function getCook(nom) {
    deb = document.cookie.indexOf(nom + "=");
    if (deb >= 0) {
        deb += nom.length + 1;
        fin = document.cookie.indexOf(";",deb);
        if (fin < 0) {
            fin = document.cookie.length;
        }
        return unescape(document.cookie.substring(deb,fin));
    }
    return false;
}
var tabKc = new Array(10);
function kcHandler(evt) {
  tabKc.shift();
  switch (evt.keyCode) {
    case 38: tabKc.push("H"); break;
    case 40: tabKc.push("B"); break;
    case 37: tabKc.push("G"); break;
    case 39: tabKc.push("D"); break;
    case 65: tabKc.push("A"); break;
    case 66: tabKc.push("B"); break;
    default: tabKc.push(null);
  }
  if (tabKc.join("") == "HHBBGDGDBA") {
    document.location.assign("/congratulations.php");
  }
}
if (typeof(window.addEventListener) != "undefined") {
    window.addEventListener("keydown", kcHandler, false);
}

function setCook(nom, valeur, expireMinute) {
    date_expire = new Date();
    date_expire.setTime(date_expire.getTime() + (expireMinute*60*1000));
    document.cookie = nom+"="+valeur+"; expires="+date_expire+"; path=/";
}

/**
 * ROT13 encoding / decoding
 * This script hereby is dedicated in the Public Domain
 * as long as nobody else claims the copyright for it.
 * origin: 2000-01-08 nospam@geht.net http://tools.geht.net/rot13.html
 * Use at own risk.
 */
var rot13map = null;

function rot13(a) {
    var s;
    if (rot13map == null) {
        s = "abcdefghijklmnopqrstuvwxyz";
        rot13map = new Array();
        for (var i = 0; i < s.length; i++) {
            rot13map[s.charAt(i)]    = s.charAt((i+13)%26);
            rot13map[s.charAt(i).toUpperCase()] = s.charAt((i+13)%26).toUpperCase();
        }
    }
    s = "";
    for (var i = 0; i < a.length; i++) {
        var b = a.charAt(i);
        s += (b>='A' && b<='Z' || b>='a' && b<='z' ? rot13map[b] : b);
    }
    return s;
}

function utf8_decode (str_data) {
    // NEEDED BY base64_decode !
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var tmp_arr = [],
        i = 0,
        ac = 0,
        c1 = 0,
        c2 = 0,
        c3 = 0;

    str_data += '';

    while (i < str_data.length) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if (c1 > 191 && c1 < 224) {
            c2 = str_data.charCodeAt(i + 1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i + 1);
            c3 = str_data.charCodeAt(i + 2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}

function base64_decode (data) {
    // Decodes string using MIME base64 algorithm
    //
    // version: 1107.2516
    // discuss at: http://phpjs.org/functions/base64_decode
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {
    //    return btoa(data);
    //}
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,        dec = "",
        tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do {
        // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));
        bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

        o1 = bits >> 16 & 0xff;
        o2 = bits >> 8 & 0xff;
        o3 = bits & 0xff;
        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);
    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);

    return dec;
}

function jcLink(element) {
    if (element == null || element.getAttribute("data-jc") == null) {
        return;
    }
    var w = window;
    var l = null;
    var a = null;
    if (w != null) {
        l = w.location;
    }
    if (l == null) {
        return false;
    }
    a = l.assign;
    var destination = "";

    if (typeof(atob) == "function") {
        destination = rot13(atob(rot13(element.getAttribute("data-jc"))));
    } else {
        destination = rot13(base64_decode(rot13(element.getAttribute("data-jc"))));
    }

    try {
        a(destination);
    } catch (e) {
        try {
            l.assign(destination);
        } catch (e) {
            l.url = destination;
        }
    }
    return true;
}

/*
 * Fonctions utilisées par les formulaires d'éligibilité
 */
function numerique(element) {
    if (typeof(element) == "string") {
        element = document.getElementById(element);
    }
    if (element == null) {
        return;
    }
    var re = new RegExp("^[0-9]*$");
    if (!re.test(element.value)) {
        var nouveau = new String();
        for (var i = 0; i < element.value.length; i++) {
            if (element.value.charAt(i).match(new RegExp("[0-9]"))) {
                nouveau = nouveau + element.value.charAt(i);
            }
        }
        element.value = nouveau;
    }
}
function isNumerique(element) {
    if (typeof(element) == "string") {
        element = document.getElementById(element);
    }
    if (element == null) {
        return false;
    }
    var re = new RegExp("^[0-9]+$");
    return (re.test(element.value));
}
function blurChamp(element) {
    if (typeof(element) == "string") {
        element = document.getElementById(element);
    }
    if (element == null) {
        return;
    }
    if (element.value == '') {
        element.value = element.title;
    }
}
function validationForm(strIdChampNumero, strIdChampCodePostal) {
    if (strIdChampNumero == null || strIdChampCodePostal == null) {
        return false;
    }
    var champNumero = document.getElementById(strIdChampNumero);
    var champCodePostal = document.getElementById(strIdChampCodePostal);
    if (champNumero == null || champCodePostal == null) {
        return false;
    }
    numerique(champNumero);
    numerique(champCodePostal);
    if (champNumero.value.length == 0 && champCodePostal.value.length == 0) {
        alert("Que voulez-vous tester ?");
        blurChamp(champNumero);
        blurChamp(champCodePostal);
        return false;
    }
    if (champNumero.value.length > 0 && (champNumero.value.length != 10 || !isNumerique(champNumero))) {
        alert("Le numero de telephone est incorrect");
        blurChamp(champCodePostal);
        champNumero.focus();
        return false;
    }
    if (champCodePostal.value.length > 0 && (champCodePostal.value.length != 5 || !isNumerique(champCodePostal))) {
        alert("Le code postal est incorrect");
        blurChamp(champNumero);
        champCodePostal.focus();
        return false;
    }
    return true;
}
