﻿// Library to check whether cookies are allowed or not.

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else 
	    expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');    // getting ALL cookies!
    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 areCookiesEnabled() {
    var r = false;
    var cookieName = getNChars(8);
    var cookieValue = getNChars(12);
    createCookie(cookieName, cookieValue, 1);
    if (readCookie(cookieName) != null) {
        r = true;
        eraseCookie(cookieName);
    }
    return r;
}

var lastURI = null;
var cookieErrorMessage = "Ihr Browser akzeptiert derzeit keine Cookies.\r\nBitte ändern Sie diese Browsereinstellung, um den Versicherungsvergleich nutzen zu können.";
function cookieCheck() {
    var currentURI = document.URL;
    if ((!areCookiesEnabled()) && (lastURI != currentURI)) {
        lastURI = currentURI;
        $('form').submit(function () {
            alert(cookieErrorMessage);
            return false;
        });
        sendCookieDisabledInfo()
        isAjaxFired = true;

        alert(cookieErrorMessage);
    }
}

function getNChars(n) {
	var ret = "";
	for(var a = 0; a < n; a++)
		ret = ret + String.fromCharCode(getRandomNumber(65, 90));
	return ret;
}

function getRandomNumber(min, max) {
    if (min > max) 
        return -1;
    if (min == max)
        return min;

    return min + parseInt(Math.random() * (max - min + 1));
}

function sendCookieDisabledInfo() {
    var split = document.location.href.split("?")
    var querystring = (split.lenght!=0) ? '?' + split[1] : '' ;
    $.ajax({
        url: document.location.href.substring(0, document.location.href.lastIndexOf('/')) + '/Ajax/CookieDisabledInfo'
    })

}
