window.onload = onLoadPage;
var isPageLoaded = false;
var isServerUp = false; //track it with a cookie that will be available 20 minutes
testServerStatus('http://analytics.theinsurers.co.uk/form.gif?d=motorbike-insurance.asdafinance.com');

//if the time of loading the image is greater then this then won't load the scripts
var timeforLoadingTheImage = 10000 //5 seconds
var dateTimenow = new Date();
var startTimeOfImageLoad = dateTimenow.getTime();



function testServerStatus(URL) {
    //test if server is up and wait for results
    if (readCookie(isServerUp) != "true") {
        var testerImage = new Image();
        testerImage.src = URL;
        
        testerImage.onload = isActive;
        testerImage.onerror = isDead;
    }
    else {
        //the server is up
        dhtmlLoadScript('Scripts/Pagetracker.js')
    }


}
function onLoadPage() {
    isPageLoaded = true;
    if (readCookie(isServerUp)) {
        dhtmlLoadScript('Scripts/formfill.js');
    }
}

function isActive() {
    var currentDateTimeOfImageLoad = dateTimenow.getTime();
    if ((currentDateTimeOfImageLoad - startTimeOfImageLoad) >= timeforLoadingTheImage) return;
    dhtmlLoadScript('Scripts/Pagetracker.js')
    createCookie(isServerUp, true, 20);
    if (isPageLoaded) {
        dhtmlLoadScript('Scripts/formfill.js');
    }
}


function isDead() {
    //do nothing
    eraseCookie(isServerUp);
}
function dhtmlLoadScript(url) {
    var e = document.createElement("script");
    e.src = url;
    e.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
}

//create a cookie for X minutes to hold the status of the server
function createCookie(name, value, minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime() + (minutes * 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);
}

