﻿
var testid;
var downloadSpeed;
var uploadSpeed;
var uid;
var newsletter;
var superfast;
var debugMode;
var displayMode;
var providerID;
var userRegistered;
var postcode;

function escapeHTML(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
};

function generateGuid() {
    var guid = '';

    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;

        if ((i == 8) || (i == 12) || (i == 16) || (i == 20)) guid += "-";
    }

    return guid;
}

function remoteJson(listener, callback) {
    if (listener) {
        var script = document.createElement("script"); // new script element.
        script.setAttribute("type", "text/javascript");
        script.setAttribute("id", "remotejson" + generateGuid());

        if (listener.indexOf("?") > 0) {
            script.setAttribute("src", listener + "&nocache=" + generateGuid() + "&callback=" + callback);
        }
        else {
            script.setAttribute("src", listener + "?nocache=" + generateGuid() + "&callback=" + callback);
        }

        document.getElementsByTagName("head")[0].appendChild(script);
    }
}

function listen(evnt, elem, func) {
    if (elem.addEventListener) {  // W3C DOM
        elem.addEventListener(evnt, func, false);
    }
    else { // IE DOM
        var r = elem.attachEvent("on" + evnt, func);
        return r;
    }
    //else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}



function InitAJAX() {
    var objxml = null;
    var ProgID = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.3.0", "Microsoft.XMLHTTP"];

    try {
        objxml = new XMLHttpRequest();
    }
    catch (e) {
        for (var i = 0; i < ProgID.length; i++) {
            try {
                objxml = new ActiveXObject(ProgID[i]);
            }
            catch (e) {
                continue;
            }
        }
    }

    return objxml;
}


function display(where, what) {
    document.getElementById(where).innerHTML = what[0];
    /*if (document.getElementById('bc_table'))
    {
    document.getElementById('google_ads').style.marginTop = (document.getElementById('broadband_table').clientHeight + 100) + 'px';
    }*/
}

function getNextSibbling(e) {

    do e = e.nextSibling;
    while (e && e.nodeType != 1);
    return e;
}




function getSelectedValue(item) {
    if (document.getElementById(item)) {
        return document.getElementById(item).options[document.getElementById(item).selectedIndex].value;
    }
    else {
        return;
    }

}

function setComboValue(comboid, item) {
    //return document.getElementById(item).options[document.getElementById(item).selectedIndex].value;
    var i = 0;
    for (var i = 0; i < document.getElementById(comboid).options.length; i++) {
        if (document.getElementById(comboid).options[i].value == item) {
            document.getElementById(comboid).selectedIndex = i;
            return;
        }
    }
}




function SetCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays == null || nDays == 0) nDays = 1;
    expire.setTime(today.getTime() + 3600000 * 24 * nDays);
    document.cookie = cookieName + "=" + escape(cookieValue)
                 + ";expires=" + expire.toGMTString();
}

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 getElementsByClassName(classname, node) {
    if (!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for (var i = 0, j = els.length; i < j; i++)
        if (re.test(els[i].className)) a.push(els[i]);
    return a;
}

function hideNonUK() {
    WhenDomReady(function() { hideNonUKCore(); });

}

function hideNonUKCore() {
    //alert('b');
    if (document.getElementById("ukonly1")) {
        document.getElementById("ukonly1").style.display = 'none';
    }
    if (document.getElementById("ukonly2")) {
        document.getElementById("ukonly2").style.display = 'none';
    }
    if (document.getElementById("ukonly3")) {
        document.getElementById("ukonly3").style.display = 'none';
    }
    if (document.getElementById("ukonly4")) {
        document.getElementById("ukonly4").style.display = 'none';
    }
}

function trackEvent(name) {
    remoteJson('/comparison/ajax.aspx?mode=trackevent&event=' + name);
}


//TODO:Inaccurate!!!
function printMb(kbps) {
    return Math.round(kbps / 1024 * 100) / 100 + 'Mb';
}

function onEnterGoWithPostcode(e, elemID, url) {
    if (e.keyCode == 13) {
        goWithPostcode(elemID, url)
    }

}


function goWithPostcode(elemID, url) {

    document.location.href = url + document.getElementById(elemID).value;
}

function openPopup(url) {
    var myPopup = window.open(url, "", "");
    if (!myPopup) {
        document.location.href = url;
    }
}

function goToRedirWithRef(url) {
    openPopup(url + '&ref=' + document.location.href);
}

function highlightRow(elem, on) {
    if (on) {
        elem.className = 'bc_tr_highlighted';
    }
    else {
        elem.className = 'bc_tr';
    }
}

/*----------------------------------------------------------------------------------------------
/*--------------------------Homepage -------------------------------
/*----------------------------------------------------------------------------------------------*/
function openNewWindow(theURL, winName, features) {
    window.open(theURL, winName, features);
}


function styleValidationMessage(elem, on) {
    if (on) {
        document.getElementById(elem).style.borderColor = 'red';
        document.getElementById(elem).style.borderWidth = '2px';
        document.getElementById(elem).style.borderStyle = 'solid';
        document.getElementById(elem).style.marginBottom = '1px';
        document.getElementById(elem).style.height = '25px';
    }
    else {
        document.getElementById(elem).style.borderColor = '';
        document.getElementById(elem).style.borderWidth = '';
        document.getElementById(elem).style.borderStyle = '';
        document.getElementById(elem).style.marginBottom = '';
        document.getElementById(elem).style.height = '';
    }
}

//var speedtestStats = new Object();
function speedCheckerStarted() {
    // setTimeout("trackEvent('speedCheckerStarted')",100);
    //speedtestStats['start'] = new Date();

}

function speedCheckerDownloadProgress(payloadID, maximumDownloadSpeed, predictedDownloads) {
    //speedtestStats['downloadspeed'] = maximumDownloadSpeed;
}

function speedCheckerCompleted(result) {
    if (document.getElementById('resultMenuTop').style.display == 'none') {
        document.getElementById('survey').style.display = 'none';
        document.getElementById('resultMenuTop').style.display = 'block';

    }
    //trackEvent('speedCheckerCompleted');
    
    //clicky.goal('192'); //re-add if we ever need to track clicky goals for number of speed tests completed

    downloadSpeed = result.split(',')[0];
    uploadSpeed = result.split(',')[1];

    //speedtestStats['end'] = new Date();
    //speedtestStats['downloadspeed'] = downloadSpeed;
    //isp may break the structure, we need to isolate it and get last part for testid
    testid = result.substring(result.lastIndexOf(',') + 1)
    isp = 'notused'; //result.split(',')[2];
    //testid =  result.split(',')[3];
    displayMode = "resultMenu";
    callResultMenu();
    /*if (techsupport)
    {
    document.getElementById('toprightimage').innerHTML = '<a href="/technical_support.aspx"><img src="/images/technical_support.gif" /></a>';
    }*/
    //displayPagePeel();


}


function setVisited() {
    //document.getElementById('resultMenuTop').style.display = 'none';
    //document.getElementById('survey').style.display = 'block';
    superSetVar('/cp=speedtestnet');
    trackEvent('speedtestnet');
}



function surveyVote() {
    var sel = null;
    for (i = 0; i < document.getElementsByName('surveyRadios').length; i++) {
        if (document.getElementsByName('surveyRadios')[i].checked) {
            sel = document.getElementsByName('surveyRadios')[i].value;
        }
    }
    if (!sel && document.getElementById('txtSurveyOther').value == '') {
        alert('Please select one of the options');
        return;
    }
    if (sel) {
        trackEvent(sel);
    }
    else {

        remoteJson("/comparison/ajax.aspx?mode=surveysuggest&suggestion=" + document.getElementById('txtSurveyOther').value, null);
    }
    document.getElementById('survey_questions').style.display = 'none';
    document.getElementById('survey_thankyou').style.display = 'block';
}

function displayPagePeel() {
    if (document.getElementById('PagePeelSmall')) {
        document.getElementById('PagePeelSmall').style.display = 'block';
    }
}

function unloaded() {


    if (speedtestStats['start']) {
        var length;

        if (speedtestStats['end']) {
            length = speedtestStats['end'] - speedtestStats['start'];
        }
        else {
            length = 0;
        }

        if (!speedtestStats['downloadspeed']) {
            speedtestStats['downloadspeed'] = 0;
        }
        http = InitAJAX();
        //alert(http);
        http.onreadystatechange = function() { };
        http.open("GET", "/comparison/ajax.aspx?mode=saveSpeedTestStats&length=" + length + "&dl=" + speedtestStats['downloadspeed'], false);
        http.send();

    }

}
//listen('unload', window, unloaded);

/*----------------------------------------------------------------------------------------------
/*--------------------------Navigation -------------------------------
/*----------------------------------------------------------------------------------------------*/
function callResultMenu(providerID, packageID, postcode) {
    uid = readCookie('uid');
    infos = '';
    if (providerID) {
        infos += '&providerid=' + providerID;
    }

    if (uid) {
        infos += '&uid=' + uid;
    }


    if (isp) {
        infos += '&isp=' + isp;
    }


    if (typeof (window['testid']) != "undefined") {
        if (testid) {
            remoteJson("/comparison/ajax.aspx?mode=resultMenu&dl=" + downloadSpeed + '&id=' + testid + infos, 'resultMenuLoaded()');
        }
    }

}

function resultMenuLoaded() {
    if (displayMode == "resultMenu") {

        showActionMenuButtons();
    }
}

function showActionMenuButtons() {
    displayMode = "resultMenu";
    remoteJson("/comparison/ajax.aspx?mode=actionMenuButtons", null);
}

function changeISP() {
    var diffISP = getSelectedValue("cboDifferentISPs");
    callResultMenu(diffISP);
    if (displayMode == "whatIsMaxSpeed") {
        callWhatIsMaxSpeed();
    }
}


function displayLoading() {

    document.getElementById('broadband_table').innerHTML = '<div style="width:100%;font-size:17px;text-align:center;font-weight:bold;margin:50px;"><div style="float:left;width:100px;"><div id="flash_loading" ></div></div><div style="float:left;margin-top:29px;">... Please wait .. Getting maximum speed estimate for your line ...</div><br style="clear:both;" /></div>';
    swfobject.embedSWF("http://www.broadbandspeedchecker.co.uk/images/cubes.swf", "flash_loading", "75", "75", "6.0.0", "http://www.broadbandpackages.org/images/expressInstall.swf");

}

/*----------------------------------------------------------------------------------------------
/*--------------------------What is my max speed -------------------------------
/*----------------------------------------------------------------------------------------------*/
var areaMode;
function callWhatIsMaxSpeed(areamode) {
    areaMode = areamode;
    displayMode = "whatIsMaxSpeed";
    //trackEvent('callWhatIsMaxSpeed' + areamode);
    uid = readCookie('uid');
    infos = '';
    /* if (providerID)
    {
    infos += '&providerid=' + providerID;
    }*/
    if (uid) {
        infos += '&uid=' + uid;
    }

    if (areaMode) {
        infos += '&areamode=1';
    }

    if (testid) {
        remoteJson('/comparison/ajax.aspx?mode=whatIsMaxSpeed&id=' + testid + infos, 'whatIsMaxSpeedLoaded()');
    }
}

function whatIsMaxSpeedLoaded() {

    packageID = getSelectedValue("cboPackages");

    //var postcode;
    // var providerID;
    if (document.getElementById('txtPostcode')) {
        postcode = document.getElementById('txtPostcode').value;
    }

    uid = readCookie('uid');

    infos = '';
    //providerID = document.getElementById('providerID').value;

    if (providerID) {
        infos += '&providerid=' + providerID;
    }

    if (packageID) {
        infos += '&packageid=' + packageID;
    }

    if (uid) {
        infos += '&uid=' + uid;
    }

    if (postcode) {
        infos += '&postcode=' + postcode;
    }



    if ((packageID > 0 || providerID == "999") && providerID > 0 && postcode != '') {
        if (areaMode) {
            callBroadbandSpeedInMyArea(testid, infos);
        }
        else {
            remoteJson('/comparison/ajax.aspx?mode=broadbandSpeedList&dl=' + downloadSpeed + '&id=' + testid + infos, null);
        }
    }


}


function howFastCanIGetClicked() {

    //validation
    var message = '';


    if (getSelectedValue("cboPackages") == "-1" && providerID != 999) {

        styleValidationMessage('packageInput', true);
        message += ' - your broadband package \n';
    }
    else {
        packageID = getSelectedValue("cboPackages");
        styleValidationMessage('packageInput', false);

    }

    if (document.getElementById('txtPostcode').value == "") {
        styleValidationMessage('postcodeInput', true);
        message += ' - your postcode \n';
    }
    else {
        postcode = document.getElementById('txtPostcode').value;
        styleValidationMessage('postcodeInput', false);
    }


    if (message != '') {
        message = 'Please enter: \n' + message;
        alert(message);
    }
    else {
        displayLoading();
        whatIsMaxSpeedLoaded(providerID, packageID, postcode);
    }
}


function showAdsl2Only() {
    adsl2 = 1;
    sort('yearlyCost')
}

/*----------------------------------------------------------------------------------------------
/*--------------------------Previous results-------------------------------
/*----------------------------------------------------------------------------------------------*/


function callSeePreviousResults() {
    //alert(pageTracker);
    //setTimeout("pageTracker._trackPageview('/Homepage/callSeePreviousResults')",1000);
    //document.getElementById('pageTrackerLink').click();
    //this.pageTracker = _gat._getTracker(key);
    //trackEvent('callSeePreviousResults');
    displayMode = 'previousResults';
    if (userRegistered) {
        remoteJson('/comparison/ajax.aspx?mode=previousResults', null);
    }
    else {
        showRegisterForm();
    }
}

function showRegisterForm() {
    remoteJson('/comparison/ajax.aspx?mode=registerForm', null);
}




function checkemail(email) {
    var str = email
    var filter = /^.+@.+\..{2,3}$/

    if (filter.test(str)) {
        return true
    }
    else {
        return false
    }

}

function register() {
    message = '';
    info = '';
    if (document.getElementById('txtEmail').value == "" || !checkemail(document.getElementById('txtEmail').value)) {
        styleValidationMessage('emailInput', true);
        message += ' - your email \n';
    }
    else {
        email = document.getElementById('txtEmail').value;
        styleValidationMessage('emailInput', false);
    }

    if (document.getElementById('txtPassword').value == "") {
        styleValidationMessage('passwordInput', true);
        message += ' - your password \n';
    }
    else {
        password = document.getElementById('txtPassword').value;
        styleValidationMessage('passwordInput', false);
    }

    if (document.getElementById('txtPasswordConfirm').value != document.getElementById('txtPassword').value) {
        styleValidationMessage('passwordConfirmInput', true);
        message += ' - your password confirm does not match \n';
    }
    else {
        styleValidationMessage('passwordConfirmInput', false);
    }

    if (document.getElementById('chkNewsletter').checked) {
        newsletter = 1;
    }
    else {
        newsletter = 0;
    }

    if (message != '') {
        message = 'Please correct: \n' + message;
        alert(message);
    }
    else {
        document.getElementById('register_button').src = '/images/please_wait.gif';

        remoteJson('/comparison/ajax.aspx?mode=register&email=' + email + '&password=' + password + '&newsletter=' + newsletter, 'registerLoaded()');
    }
}

function registerLoaded(success) {
    if (!success) {
        alert('This email already exists in the database. Please login to retrieve your results.');
    }
    else {
        alert('Your account has been registered');
        userRegistered = 1;
        callSeePreviousResults();
        remoteJson("/comparison/ajax.aspx?mode=actionMenuButtons", null);
    }
    document.getElementById('register_button').src = '/images/register_button.gif';
}

function showLoginForm() {
    remoteJson('/comparison/ajax.aspx?mode=loginForm', null);
}

function login() {
    message = '';
    info = '';
    if (document.getElementById('txtEmail').value == "" || !checkemail(document.getElementById('txtEmail').value)) {
        styleValidationMessage('emailInput', true);
        message += ' - your email \n';
    }
    else {
        email = document.getElementById('txtEmail').value;
        styleValidationMessage('emailInput', false);
    }

    if (document.getElementById('txtPassword').value == "") {
        styleValidationMessage('passwordInput', true);
        message += ' - your password \n';
    }
    else {
        password = document.getElementById('txtPassword').value;
        styleValidationMessage('passwordInput', false);
    }


    if (message != '') {
        message = 'Please correct: \n' + message;
        alert(message);
    }
    else {
        document.getElementById('login_button').src = '/images/please_wait.gif';

        remoteJson('/comparison/ajax.aspx?mode=login&email=' + email + '&password=' + password, null);
    }
}

function loginLoaded(success) {
    if (!success) {
        alert('Email and password do not match. Please use Forgotten password link if you do not remember your password.');
    }
    else {
        userRegistered = 1;
        callSeePreviousResults();
        remoteJson("/comparison/ajax.aspx?mode=actionMenuButtons", null);
    }
    document.getElementById('login_button').src = '/images/login_button.gif';

}

/*
function facebookAuthenticated()
{
userRegistered = 1;
callSeePreviousResults();
remoteJson("/comparison/ajax.aspx?mode=actionMenuButtons",null);
remoteJson("/comparison/ajax.aspx?mode=registerFacebook",null);
}*/


/*----------------------------------------------------------------------------------------------
/*-------------------------- Share results -------------------------------
/*----------------------------------------------------------------------------------------------*/

function callShareResult() {
    //trackEvent('callShareResult');
    var fi = document.createElement("iframe");
    fi.style.width = '800px';
    fi.style.height = '400px';
    fi.frameBorder = 0;
    fi.scrolling = 'no';
    fi.src = '/share_result.aspx?id=' + testid;
    document.getElementById('broadband_table').innerHTML = '';
    document.getElementById('broadband_table').appendChild(fi);

}


/*----------------------------------------------------------------------------------------------
/*-------------------------- BroadbandSpeedList -------------------------------
/*----------------------------------------------------------------------------------------------*/
function highlightHomepage(e) {
    var on;
    var rowid = e.id.replace("row_", "");
    var inforow = document.getElementById('rowinfo_' + rowid);
    if (inforow.style.display == 'none') {
        //e.className="high";
        e.className = "cursor bc_tr_highlighted";

        try {
            inforow.style.display = 'table-row';
        }
        catch (ex) {
            inforow.style.display = 'block';
        }

    }
    else {
        e.className = "cursor bc_tr";
        inforow.style.display = 'none';
    }

}


function subscribeExchange() {
    var email = document.getElementById('txtEmail').value;
    newsletter = document.getElementById('chkEmailSpeed').checked ? 1 : 0;
    if (email.search("@") < 0) {
        alert('Please enter your email');
        return;
    }

    remoteJson('/comparison/ajax.aspx?mode=subscribeExchange&uid=' + uid + '&email=' + email + '&newsletter=' + newsletter, null);
}

function subscribedToExchange() {
    if (newsletter) {
        document.getElementById('exchangeSubscribeBox').innerHTML = 'Thank you. You will be receiving tips how to improve your broadband speed. And if you change your mind, you can opt out at any time.';
    }
    else {
        document.getElementById('exchangeSubscribeBox').innerHTML = 'Thank you. You will be notified when your exchange is enabled for a better broadband.';
    }

}


function callBroadbandSpeedInMyArea(testID, infos) {
    //trackEvent('callShareResult');
    var fi = document.createElement("iframe");
    fi.style.width = '800px';
    fi.style.height = '700px';
    fi.frameBorder = 0;
    fi.scrolling = 'no';
    fi.src = '/broadband_speed_in_my_area_iframe.aspx?id=' + testID + infos;
    document.getElementById('broadband_table').innerHTML = '';
    document.getElementById('broadband_table').appendChild(fi);

}

