function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie (name) {
    createCookie (name, "", -1);
}

function checkUserAge (theCookie, ifYes, noRedirect) {
    theCookie = readCookie (theCookie);
    if ((theCookie != null) && (theCookie != "null") && (theCookie != "")) {
        if (theCookie == "no") {
            // USER IS TOO YOUNG
            window.location = "tooyoung.php";
        } else if (theCookie == "yes") {
            // USER IS OLD ENOUGH
            if (ifYes != "") {
                // SEND THEM TO THE SPECIFIED PAGE (FROM AGE SELECT PAGE)
                window.location = ifYes;
            } else {
                // THEY JUST STAY ON THE PAGE AND NOTHING HAPPENS
            }
        }
    } else {
        // NO COOKIE, SEND THEM THERE (IF THEY AREN'T THERE ALREADY)
        if (!noRedirect) {
            window.location = "index.php";
        }
    }
}

function verifyAge (theCookie) {
    var now = new Date ();
    var today = new Date (now.getYear (), now.getMonth (), now.getDate ());

    var yearNow = now.getFullYear ();
    var monthNow = now.getMonth () + 1;
    var dateNow = now.getDate ();

    yearDob = document.getElementById ('year').value;
    monthDob = document.getElementById ('month').value;
    dateDob = document.getElementById ('day').value;

    if (
        ((yearDob !== "NULL") && (monthDob !== "NULL") && (dateDob !== "NULL")) &&
        ((yearDob != 0) && (monthDob != 0) && (dateDob != 0))
        ) {
        yearAge = yearNow - yearDob;

        if (monthNow >= monthDob) {
            var monthAge = monthNow - monthDob;
        } else {
            yearAge--;
            var monthAge = 12 + monthNow -monthDob;
        }

        if (dateNow >= dateDob){
            var dateAge = dateNow - dateDob;
        } else {
            monthAge--;
            var dateAge = 31 + dateNow - dateDob;
            if (monthAge < 0) {
                monthAge = 11;
                yearAge--;
            }
        }

        if (yearAge >= 18) {
            createCookie (theCookie, "yes", 7);
        } else {
            createCookie (theCookie, "no", 7);
        }
        window.location = "index.php";
    } else {
        window.alert ("Please enter your date of birth");
    }
}

