﻿function GetXmlHttpObject() {
    var xmlHttp=null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

//parameters: QueryString-ParameterString
function requestPage(url, parameters, containerId, followupFunction) {
    lastRequestedUrl = url;
    if (lastRequestedUrl.indexOf("?") > -1)
        lastRequestedUrl = lastRequestedUrl.substr(0, lastRequestedUrl.indexOf("?"));
   
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/html');
         }
     } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
           try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
        }
     }
     if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
     }
     http_request.onreadystatechange = function() {
        responsePage(containerId, followupFunction);
     }
     http_request.open('GET', url + parameters, true);
     http_request.send(null);
}
    
function responsePage(containerId, followupFunction)
{
    responseContainer = document.getElementById(containerId);
    if (responseContainer != null) {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
            var text = http_request.responseText;
            text = text.substr(text.indexOf("<div style=\"margin:"));
            text = text.substr(0, text.indexOf("</form"));
                responseContainer.innerHTML = text;
                if (followupFunction)
                    followupFunction();
            }
        }
    }
}

//quiz-vars
var _currentUrl = "";
var _currentCulture = "de-ch";
var _quizIsValid = false;
var _firstId, _secondId, _thirdId;
var a1 = false;
var a2 = false;
var a3 = false;
//result-vars
var emailTB, streetTB, townTB, nameTB
var _errorMsg = "";
var _resultIsValid;
var _emailErrorMsg = "";
var emailRegEx = "[a-zA-Z0-9\._-]*@[a-zA-Z0-9\._-]*\.[a-zA-Z]{2,4}";
var _isMobile = false;

function initGrillQuiz(grillQuizUrl, currentCulture, subscriptionErrorMessage, subscriptionEmailErrorMessage, firstQuestionId, isMobile)
{
    _currentUrl = grillQuizUrl;
    _currentCulture = currentCulture;
    if (!_currentUrl.endsWith('/'))
        _currentUrl += "/";
    if (_currentUrl.indexOf("/GrillQuiz_files") == -1)
        _currentUrl += "GrillQuiz_files/"
    _currentUrl += "quizresult.aspx";
    _errorMsg = subscriptionErrorMessage;
    while (_errorMsg.indexOf("--quote--") > -1)
        _errorMsg = _errorMsg.replace("--quote--", "'");
    _emailErrorMsg = subscriptionEmailErrorMessage;
    while (_emailErrorMsg.indexOf("--quote--") > -1)
        _emailErrorMsg = _emailErrorMsg.replace("--quote--", "'");
    _firstId = firstQuestionId;
    _secondId = firstQuestionId.replace("First", "Second");
    _thirdId = firstQuestionId.replace("First", "Third");
    _isMobile = isMobile;
}

function markAnswer(sender, question, answer) {

    var xmlHttp = GetXmlHttpObject();
    var url = _currentUrl + "?q=" + question + "&a=" + answer + "&r=" + Math.random().toString();
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    
    //first set all answers to unselected
    var baseId = sender.id.substring(0, sender.id.length - 1);
    document.getElementById(baseId + "A").className = "unselected";
    document.getElementById(baseId + "B").className = "unselected";
    document.getElementById(baseId + "C").className = "unselected";
    
    //then set the right to no css class
    document.getElementById(sender.id).className = "";
    
    if (question == "1")
        a1 = true;
    if (question == "2")
        a2 = true;
    if (question == "3")
        a3 = true;
}

//btn evaluate on mainpage
function evaluateQuiz()
{
    validateQuiz();
    if (_quizIsValid)
    {
        //container
        var div = document.createElement("div");
        div.className = "quizResultHolder";
        div.id = "GrillQuizResultHolder";

        document.forms[0].appendChild(div);
        requestPage(_currentUrl, "?evaluate=true&culture=" + _currentCulture + "&r=" + Math.random().toString(), "GrillQuizResultHolder", evaluateQuizFollowup);
    }
}

//needed to add the btn close after the content (requestPage)
function evaluateQuizFollowup()
{
    var div = document.getElementById("GrillQuizResultHolder");

    //close-Btn
    var btnClose = document.createElement("div");
    btnClose.innerHTML = "[x]";
    btnClose.style.position = "absolute";
    btnClose.style.right = "4px";
    btnClose.style.top = "2px";
    btnClose.style.fontSize = "larger";
    btnClose.style.fontWeight = "bold";
    btnClose.style.cursor = "pointer";
    btnClose.onclick = function(){
        closeQuizWindow();
    }
    div.appendChild(btnClose);
}

//btn click on send (result)
function sendSubscription()
{
    validateSubscription();
    if (_resultIsValid) {
        CMSServices.Custom.GrillQuiz.SaveRegistration(nameTB.value, streetTB.value, townTB.value, emailTB.value);
        if (_isMobile)
            setTimeout(closeAndRedirect, 1000);
        else
            setTimeout(closeAndRedirect, 50);
    }
}

function closeAndRedirect() {
    closeQuizWindow();
    if (window.location.toString().indexOf("?") > -1)
        window.location = window.location.toString() + "&endQuiz=true";
    else
        window.location = window.location.toString() + "?endQuiz=true";
}

function closeQuizWindow()
{
    var div = document.getElementById("GrillQuizResultHolder");
    //purge(div);
    document.forms[0].removeChild(div);
}

function validateSubscription()
{
    _resultIsValid = true;
    
    var txts = document.getElementsByTagName("INPUT");
    for (var i = 0; i < txts.length; i++)
    {
        if (txts[i].id.indexOf("txtEmail") > -1)
            emailTB = txts[i];
        if (txts[i].id.indexOf("txtName") > -1)
            nameTB = txts[i];
        if (txts[i].id.indexOf("txtStreetNr") > -1)
            streetTB = txts[i];
        if (txts[i].id.indexOf("txtZip") > -1)
            townTB = txts[i];
                
        if ((txts[i].id.indexOf("txtName") > -1 || txts[i].id.indexOf("txtSreetNr") > -1 || 
             txts[i].id.indexOf("txtZipTown") > -1 || txts[i].id.indexOf("txtEmail") > -1) && 
             txts[i].value == "")
            _resultIsValid = false;
    }

    if (!_resultIsValid)
        document.getElementById("valSubscription").innerHTML = _errorMsg + "<br />";
    else
    {
        if(emailTB.value.search(emailRegEx) == -1){
            _resultIsValid = false;
            document.getElementById("valSubscription").innerHTML = _emailErrorMsg + "<br />";
        }
        else
            document.getElementById("valSubscription").innerHTML = "";
    }
}

function validateQuiz()
{
    var container = document.getElementById("quizContainer");
    var q1 = document.getElementById(_firstId);
    var q2 = document.getElementById(_secondId);
    var q3 = document.getElementById(_thirdId);
    var question1 = 0, question2 = 0, question3 = 0;
 
    _quizIsValid = true;   
    for (var i = 0; i < container.childNodes.length; i++)
    {
        if (container.childNodes[i].className == "unselected")
        {
            if (container.childNodes[i].id.indexOf("lnkFirst") > -1)
                question1++;
            if (container.childNodes[i].id.indexOf("lnkSecond") > -1)
                question2++;
            if (container.childNodes[i].id.indexOf("lnkThird") > -1)
                question3++;
        }
    }
    //clean error message
    //SPAN is for ie
    //span for the rest...
    q1.innerHTML = q1.innerHTML.replace("<span class=\"highlight\">&nbsp;&nbsp;!</span>", "").replace("<SPAN class=highlight>&nbsp;&nbsp;!</SPAN>", "");
    q2.innerHTML = q2.innerHTML.replace("<span class=\"highlight\">&nbsp;&nbsp;!</span>", "").replace("<SPAN class=highlight>&nbsp;&nbsp;!</SPAN>", "");
    q3.innerHTML = q3.innerHTML.replace("<span class=\"highlight\">&nbsp;&nbsp;!</span>", "").replace("<SPAN class=highlight>&nbsp;&nbsp;!</SPAN>", "");
    //set error message
    if (question1 == 3) {
        q1.innerHTML = q1.innerHTML + "<span class=\"highlight\">&nbsp;&nbsp;!</span>";
        _quizIsValid = false;
    }
    if (question2 == 3) {
        q2.innerHTML = q2.innerHTML + "<span class=\"highlight\">&nbsp;&nbsp;!</span>";
        _quizIsValid = false;
    }
    if (question3 == 3) {
        q3.innerHTML = q3.innerHTML + "<span class=\"highlight\">&nbsp;&nbsp;!</span>";
        _quizIsValid = false;
    }
}

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}
