//  Copyright 2008 Narragansett Technologies.  All Rights Reserved.
var advancedLogicDebug = false;
var pageLoading = false;
var aNum = 11;
var aPart = aNum / 100;
var aWhole = aNum * 100;
var aRes = aWhole + aPart;
var aLocaleRes = aRes.toLocaleString(); // 1,000.10
var groupSep = aLocaleRes.substr(1, 1);
var decSep = aLocaleRes.substr(5, 1);
if (groupSep == '0' | groupSep == '1')
    groupSep = ',';
if (decSep == '0' | decSep == '1')
    decSep = '.';
var aCustomVal = new Array()
var cErrors = new Array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
var cErrorsObj = new Array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
var cErrorsType = new Array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
var cErrorsCount = 0;
//custom functions + return values
var cErrorsFunctions = new Array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
var cErrorsFunctionsEval = new Array(true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true);
//
function reDirect(url) {	//Call client validation if it exista
    //alert(url);
    if (url.length > 0)
        document.forms[0].action += '?newurl=' + url;
    if (HTMLFields)
        copyHTMLFields(); // Copy HTML Fields to Hidden Fields
    document.forms[0].submit();
    //FIX FOR IE5
    if (navigator.appName == 'Microsoft Internet Explorer')
        if (event) event.returnValue = false;
    return false;
}
function positionToButtons() {
    try { getElement('Buttons').focus(); } catch (e) { } //try to find button table and position to there
}
//
function showImage(e, aName, Show, aObj, ofsettop, ofsetleft) {
    try {
        if (Show) {
            if (!e)
                e = window.event
            cPosition = getPosition(e);
            getElement(aName).style.top = cPosition.y + ofsettop;
            getElement(aName).style.left = cPosition.x + ofsetleft;
            getElement(aName).style.display = '';
        }
        else
            getElement(aName).style.display = 'none';
    } catch (e) { }
}
function getPosition(e) {
    e = e || window.event;
    var cursor = { x: 0, y: 0 };
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    }
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX +
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY +
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}
var one_day = 1000 * 60 * 60 * 24
var one_month = 1000 * 60 * 60 * 24 * 30
var one_year = 1000 * 60 * 60 * 24 * 30 * 12
function calcAge(yr, mon, day, unit, decimal, round) {
    today = new Date();
    var pastdate = new Date(yr, mon - 1, day);
    var countunit = unit;
    var decimals = decimal;
    var rounding = round;
    var rvalue = 0;
    finalunit = (countunit == "days") ? one_day : (countunit == "months") ? one_month : one_year;
    decimals = (decimals <= 0) ? 1 : decimals * 10;
    if (unit != "years") {
        if (rounding == "rounddown")
            rvalue = (Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals);
        else
            rvalue = (Math.ceil((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals);
    }
    else {
        yearspast = today.getFullYear() - yr - 1;
        tail = (today.getMonth() > mon - 1 || today.getMonth() == mon - 1 && today.getDate() >= day) ? 1 : 0;
        pastdate.setFullYear(today.getFullYear());
        pastdate2 = new Date(today.getFullYear() - 1, mon - 1, day);
        tail = (tail == 1) ? tail + Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals : Math.floor((today.getTime() - pastdate2.getTime()) / (finalunit) * decimals) / decimals;
        rvalue = (yearspast + tail);
    }
    return rvalue;
}
function initRadioTextBox(aName, Ans) {
    if (getElement(aName)) {
        var ix = 0;
        var found = false
        if (getElement(aName).length) {
            while (ix < getElement(aName).length) {

                answerID = 'GText_' + getElement(aName)[ix].value.substring(0, 36);
                if (getElement(aName)[ix].value != Ans) {
                    if (getElement(answerID)) {
                        getElement(answerID).value = '';
                        getElement(answerID).disabled = true;
                    }
                }
                else {
                    try {
                        if (getElement(answerID))
                            getElement(answerID).disabled = false;
                        else {
                            //trim any spare chars on the end
                            answerID = 'GText_' + getElement(aName).value.substring(0, 36);
                            if (getElement(answerID))
                                getElement(answerID).disabled = false;
                        }
                    } catch (e) { }
                }
                ix++;
            }
        }
        else {
            if (getElement(aName).value != Ans) {
                answerID = 'GText_' + getElement(aName).value.substring(0, 36);
                if (getElement(answerID)) {
                    getElement(answerID).value = '';
                    getElement(answerID).disabled = true;
                }
                else {
                    if (getElement(answerID))
                        getElement(answerID).disabled = false;
                }
            }
            else {
                answerID = 'GText_' + getElement(aName).value.substring(0, 36);
                if (getElement(answerID))
                    getElement(answerID).disabled = false;
            }
        }
    }
}
function setRadio(aName, aValue) {
    if (getElement(aName)) {
        var ix = 0;
        var found = false
        if (getElement(aName).length) {
            while (ix < getElement(aName).length && !found) {
                if (getElement(aName)[ix].value == aValue) {
                    getElement(aName)[ix].checked = true;
                    found = true;
                }
                ix++;
            }
        }
        else {
            if (getElement(aName).value == aValue)
                getElement(aName).checked = true;
        }
    }
}
function Querystring() {
    // get the query string, ignore the ? at the front.
    var querystring = location.search.substring(1, location.search.length);
    // parse out name/value pairs separated via &amp;
    var args = querystring.split('&');
    // split out each name = value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        // Fix broken unescaping
        temp = unescape(pair[0].toLowerCase()).split('+');
        name = temp.join(' ');
        temp = unescape(pair[1]).split('+');
        value = temp.join(' ');
        this[name] = value;
    }
    this.get = Querystring_get;
}
function Querystring_get(strKey, strDefault) {
    var value = this[strKey.toLowerCase()];
    if (value == null) {
        value = strDefault;
    }
    else {
        if (value.toLowerCase() == 'undefined')
            value = '';
    }
    return value;
}
//set email/first last names if passed to survey in query string
function setDefaultFields() {
    var qs = new Querystring();
    try { getElement('ext_EmailAddress').value = getElement('__EM').value } catch (e) { }
    try { getElement('ext_EMailAddress').value = qs.get('EM', ''); } catch (e) { }
    //Default any other values all should begin with ext_
    var querystring = location.search.substring(1, location.search.length);
    // parse out name/value pairs separated via &amp;
    var args = querystring.split('&');
    user1 = ''; user2 = ''; user3 = ''; user4 = ''; user5 = ''; email = ''; firstname = ''; lastname = '';mlcode = '';
    // split out each name = value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');

        if (pair.length = 2) {

            temp = unescape(pair[0]).split('+');
            name = temp.join(' ');
            temp = unescape(pair[1]).split('+');
            value = temp.join(' ');
            if (name.toLowerCase().indexOf('ml') > -1 || name.toLowerCase().indexOf('ext_') > -1 || name.toLowerCase() == 'em' || name.toLowerCase().indexOf('dropdown_') > -1) {
                try {

                    try { getElement(name).value = value; } catch (e) { };
                    if (name.toLowerCase() == 'ext_user1')
                        user1 = unescape(pair[1]);
                    if (name.toLowerCase() == 'ext_user2')
                        user2 = unescape(pair[1]);
                    if (name.toLowerCase() == 'ext_user3')
                        user3 = unescape(pair[1]);
                    if (name.toLowerCase() == 'ext_user4')
                        user4 = unescape(pair[1]);
                    if (name.toLowerCase() == 'ext_user5')
                        user5 = unescape(pair[1]);
                    if (name.toLowerCase() == 'em')
                        email = unescape(pair[1]);
                    if (name.toLowerCase() == 'ext_emailaddress')
                        email = unescape(pair[1]);
                    if (name.toLowerCase() == 'ext_firstname')
                        firstname = unescape(pair[1]);
                    if (name.toLowerCase() == 'ext_lastname')
                        lastname = unescape(pair[1]);
                    if (name.toLowerCase() == 'ml')
                        mlcode = unescape(pair[1]);
                    if (name.toLowerCase().indexOf('dropdown_') > -1)
                        setDropDown(getElement(name), unescape(pair[1]));
                }
                catch (e) { }
                try
				{ getElement('rt_' + name).innerHTML = value; }
                catch (e) { }
            }
        }
    }
    //Substitute link values
    SubLinkValues(user1, user2, user3, user4, user5, email, firstname, lastname, mlcode);
}
function setDropDown(aObj, textValue) {

    TextVal = Trim1(textValue.toLowerCase());
    for (ix = 0; ix < aObj.length; ix++) {
        dropText = Trim1(aObj[ix].text.toLowerCase());
        if (dropText == TextVal) {

            aObj[ix].selected = true;
        }
    }
}
function setDropDownByVal(aObj, textValue) {

    TextVal = Trim1(textValue.toLowerCase());
    for (ix = 0; ix < aObj.length; ix++) {
        dropText = Trim1(aObj[ix].value.toLowerCase());
        dropTexta = dropText.split(':');
        if (dropTexta.length > 1)
            dropText = dropTexta[0]
        if (TextVal.indexOf(dropText) > -1) {
            aObj[ix].selected = true;
            break;
        }
    }
}
function setDropDownRT(aObjName, textValue) {
    try {
        aObj = getElement(aObjName);
        TextVal = Trim1(textValue.toLowerCase());
        for (ix = 0; ix < aObj.length; ix++) {
            dropText = Trim1(aObj[ix].value.toLowerCase());
            if (dropText == TextVal) {
                aObj[ix].selected = true;
                if (aObj.onchange)
                    aObj.onchange();
            }
        }
    }
    catch (e) { }
}
function setInputMx(aObjName, textValue) {
    try {
        aObjc = getElement(aObjName);
        collection = false;
        //get correct element from the collection 90%
        try {
            if (aObjc.length)
                collection = true;
        }
        catch (e) { }
        //check data type
        if (collection) {
            values = textValue.split('-');
            for (iy = 0; iy < aObjc.length; iy++) {
                setValue = '';
                if (iy <= values.length)
                    setValue = values[iy];
                aObj = aObjc[iy];
                switch (aObj.tagName.toLowerCase()) {
                    case "select":
                        textValues = textValue.split(':');
                        TextVal = Trim1(textValue.toLowerCase());
                        for (ix = 0; ix < aObj.length; ix++) {
                            for (ix = 0; ix < aObj.length; ix++) {
                                dropText = Trim1(aObj[ix].text.toLowerCase());
                                if (dropText == setValue) {
                                    aObj[ix].selected = true;
                                    if (aObj.onchange)
                                        aObj.onchange();
                                }
                            }
                        }
                        break;
                    default:
                        aObj.value = textValue;
                        break;
                }
            }
        }
    }
    catch (e) { }
}
//
function setInputMxRT(aObjName, Col, textValue) {
    try {
        aObj = getElement(aObjName);
        //get correct element from the collection 90%
        try
        { aObj = aObj[Col]; }
        catch (e) { aObj = getElement(aObjName); }
        //check data type
        switch (aObj.tagName.toLowerCase()) {
            case "select":
                TextVal = Trim1(textValue.toLowerCase());
                for (ix = 0; ix < aObj.length; ix++) {
                    for (ix = 0; ix < aObj.length; ix++) {
                        dropText = Trim1(aObj[ix].text.toLowerCase());
                        if (dropText == TextVal) {
                            aObj[ix].selected = true;
                            if (aObj.onchange)
                                aObj.onchange();
                        }
                    }
                }
                break;
            default:
                aObj.value = textValue;
                break;
        }
    }
    catch (e) { }
}
//
function setCheckBoxRT(aObjName, textValue) {
    try {
        aObj = getElement(aObjName);
        TextVal = Trim1(textValue.toLowerCase());
        for (ix = 0; ix < aObj.length; ix++) {
            dropText = Trim1(aObj[ix].value.toLowerCase());
            if (dropText == TextVal)
                aObj[ix].click();
        }
    }
    catch (e) { }
}
//Sub link place holders
function SubLinkValues(user1, user2, user3, user4, user5, email, firstname, lastname, mlcode) {
    
    var Regx = /{.*}/;
    var newLink = '';
    for (ix = 0; ix < document.links.length; ix++) {
        if (Regx.test(document.links[ix])) {
            document.links[ix].href = document.links[ix].href.replace('%7b', '{').replace('%7d', '}');
            href = document.links[ix].href;
            newhref = '';
            var subVar = document.links[ix].toString().match(/{(.)*?}/g);
            for (iy = 0; iy < subVar.length; iy++) {
                switch (subVar[iy].toLowerCase()) {
                    case '{em}':
                    case '{email}':
                    case '{emailaddress}':
                    case '{ext_emailaddress}':
                    case '{personalemail}':
                        if (email.length == 0 && getElement('__EM'))
                            email = getElement('__EM').value;
                        newhref = href.replace(subVar[iy], email);
                        href = newhref;
                        break;
                    case '{ext_user1}':
                        if (user1.length == 0 && getElement('__User1'))                         
                            user1 = getElement('__User1').value;
                        newhref = href.replace(subVar[iy], user1);
                        href = newhref;
                        break;
                    case '{ext_user2}':
                        if (user2.length == 0 && getElement('__User2'))
                            user2 = getElement('__User2').value;
                        newhref = href.replace(subVar[iy], user2)
                        href = newhref;
                        break;
                    case '{ext_user3}':
                        if (user3.length == 0 && getElement('__User3'))
                            user3 = getElement('__User3').value;
                        newhref = href.replace(subVar[iy], user3)
                        href = newhref;
                        break;
                    case '{ext_user4}':
                        if (user4.length == 0 && getElement('__User4'))
                            user4 = getElement('__User4').value;
                        newhref = href.replace(subVar[iy], user4)
                        href = newhref;
                        break;
                    case '{ext_user5}':
                        if (user5.length == 0 && getElement('__User5'))
                            user5 = getElement('__User5').value;
                        newhref = href.replace(subVar[iy], user5)
                        href = newhref;
                        break;
                    case '{ext_firstname}':
                    case '{firstname}':
                        if (firstname.length == 0 && getElement('__FirstName'))
                            firstname = getElement('__FirstName').value;
                        newhref = href.replace(subVar[iy], firstname)
                        href = newhref;
                        break;
                    case '{ext_lastname}':
                    case '{lastname}':
                        if (lastname.length == 0 && getElement('__LastName'))
                            lastname = getElement('__LastName').value;
                        newhref = href.replace(subVar[iy], lastname)
                        href = newhref;
                        break;
                    case '{ml}':
                    case '{multilang}':
                        if (mlcode.length == 0 && getElement('__ML'))
                            mlcode = getElement('__ML').value;
                        newhref = href.replace(subVar[iy], mlcode);
                        href = newhref;
                        break;
                    case '{zip}':
                        if (getElement('__Zip'))
                            newhref = href.replace(subVar[iy], getElement('__Zip').value);
                        href = newhref;
                        break;
                    case '{state}':
                        if (getElement('__State'))
                            newhref = href.replace(subVar[iy], getElement('__State').value);
                        href = newhref;
                        break;
                    default:
                        break;
                }
            }
            if (newhref.length > 0)
                document.links[ix].href = newhref;
        }
    }
}

var res;
//Validate rank question
function ValRankQuestion(QuestionId, QuestionText, CtlValue, LineNo, Ctl) {
    itemCount = 0;
    rok = true;
    unRanked = '';
    CtlArray = Ctl.split('|');
    if (!checkHidden('lbl_' + QuestionId, LineNo)) {

        var CtlV = new Array(parseInt(CtlValue));
        intVal = -1;
        for (im = 0; im < CtlV.length; im++)
            CtlV[im] = im + 1;
        //
        for (im = 0; im < CtlArray.length; im++) {

            inputValue = getElement(CtlArray[im]).value;
            try {
                intVal = parseInt(inputValue);
                if (isNaN(intVal)) {
                    getElement(CtlArray[im]).value = "";
                    intVal = 0;
                }
            }
            catch (e) { intVal = 0; }
            //
            if (intVal != 0) {
                itemCount++;
                if (((intVal - 1) < CtlV.length) && intVal != -1) {
                    if (CtlV[intVal - 1] == -1)
                        CtlV[intVal - 1] = -2;
                    else
                        CtlV[intVal - 1] = -1;
                }
            }
        }

        unRankedDup = "";
        for (im = 0; im < CtlV.length; im++) {
            //-2 means duplicate entry
            if (CtlV[im] != -1 && CtlV[im] != -2) {
                unRanked = unRanked + CtlV[im] + " ";
                rok = false;
            }
            if (CtlV[im] == -2) {
                unRankedDup = unRankedDup + CtlV[im] + " ";
                rok = false;
            }
        }
    }
    else {
        for (im = 0; im < CtlArray.length; im++)
            getElement(CtlArray[im]).value = '';
    }
    if (itemCount > CtlValue)
        rok = false;
    if (!rok) {
        if (unRanked.length > 0) {
            res = res + setErrorRank(QuestionId, QuestionText, unRanked);
            setQuestionTextColor(QuestionId, SurveyErrorDec);
        }
        if (unRankedDup.length > 0) {
            res = res + setErrorRankDup(QuestionId, QuestionText, '');
            setQuestionTextColor(QuestionId, SurveyErrorDec);
        }
        if (itemCount > CtlValue) {

            res = res + setErrorExtraRank(QuestionId, QuestionText, '', CtlValue);
            setQuestionTextColor(QuestionId, SurveyErrorDec);
        }
    }
    else
        setQuestionTextColor(QuestionId, '');

    return rok;
}
//Validate rank question
function ValRankQuestionSort(QuestionId, QuestionText, CtlValue, LineNo, Ctl) {
    itemCount = 0;
    rok = true;
    unRanked = '';
    CtlArray = getElement(Ctl).value.split('|');
    if (!checkHidden('lbl_' + QuestionId, LineNo)) {
        if (CtlArray.length != CtlValue) {
            res = res + setErrorRankSort(QuestionId, QuestionText, SurveyunRankedSort);
            setQuestionTextColor(QuestionId, SurveyErrorDec);
            rok = false;
        }
    }
    return rok;
}
// compatibility for other browsers.
function getElement(elementx) {
    var elem;
    if (navigator.appName == 'Microsoft Internet Explorer')
        elem = document.all(elementx);
    else {
        if (navigator.appName == 'Opera')
            elem = document.getElementById(elementx);
        else {
            elem = document.getElementById(elementx);
            if (elem == null) // get element by index number
                elem = document.forms[0].elements[elementx];
        }
    }
    return elem;
}
// compatibility for other browsers.
function getElementDiv(elementx) {
    var elem;

    if (navigator.appName == 'Microsoft Internet Explorer')
        elem = document.all(elementx);
    else
        elem = document.layers[elementx];
    return elem;
}
//Register filter event used for questions which subscribe
function regFilterEvent(ansId, fun) {
    elName = 'Check_' + ansId
    if (window.addEventListener) {
        getElement(elName).addEventListener('click', fun, false)
    }
    else
        getElement(elName).attachEvent('onclick', fun)

}
//Check if object is hidden
function checkHidden(aSrc, LineNo) {
    notVisible = false;
    aSrc = getElement("M_" + LineNo);
    if (aSrc != null) {
        if (aSrc.className.toLowerCase() == 'hidePanel')
            notVisible = true;
        if (aSrc.style.display.toLowerCase() == 'none') {
            notVisible = true;

        }
    }
    return notVisible;
}
function toggleCmtBox(aObj, cmtBoxId, Type, GroupId, MaxIndex) {
    if (aObj.checked) {
        try { getElement(cmtBoxId).style.display = '' } catch (e) { };
    }
    else {
        try { getElement(cmtBoxId).style.display = 'none' } catch (e) { };
    }
}
function toggleCmtBoxOff(aObj, cmtBoxId, Type, GroupId, MaxIndex) {
    switch (Type) {
        case "LikertText":
          for (var ix = 0; ix <= MaxIndex; ix++) {
              try { getElement(GroupId + "_" + ix).style.display = 'none' } catch (e) { };
          }
        break;
    }
}
function toggleCmtBoxOff1(aObj, cmtBoxId, Type, GroupId, MaxIndex) {
    switch (Type) {
        case "LikertText":
            for (var ix = 0; ix <= MaxIndex; ix++) {
                try { getElement(GroupId + "_" + ix).disabled = true } catch (e) { };
            }
            break;
    }
}
function toggleCmtBox1(aObj, cmtBoxId, Type, GroupId, MaxIndex) {
    if (aObj.checked) {
        try { getElement(cmtBoxId).disabled = false } catch (e) { };
    }
    else {
        try {
            getElement(cmtBoxId).disabled  = true;
            getElement(cmtBoxId).focus();
            } catch (e) { };
    }
}
function setHiddenElements() {
    for (var ix = 1; ix < 200; ix++) {
        aObj = getElement('M_DetailsLine' + ix)
        if (aObj) {
            if (checkHidden(null, 'DetailsLine' + ix)) //if survey lind hidden init all elements on this line
                initHiddenElements(aObj);
        }
        else
            break;
    }
}
function initHiddenElements(aObj)//initialize hidden elements
{
    //do not initialize if previous button hit 
    if (pageLoading && document.referrer.length == 0)
        return;
    for (var ix = 0; ix < aObj.childNodes.length; ix++) {
        aSrc = aObj.childNodes[ix];
        switch (aSrc.tagName) {
            case "INPUT":
                switch (aSrc.type) {
                    case "checkbox":
                    case "radio":
                        aSrc.checked = false;
                        break;
                    case "text":
                        pfx = getFieldNamePfx(aSrc).toLowerCase();
                        if (pfx == 'shortfreetext_')
                            aSrc.value = '';
                        break;
                }
                break;
            case "TEXTAREA":
                break;
            case "SELECT":
                if (aSrc.length > 0)
                    aSrc[0].selected = true;
                break;
        }
        initHiddenElements(aSrc);
    }
}
function getFieldNamePfx(aObj) {
    rValue = '';
    var Regx = /.*_/;
    pfx = Regx.exec(aObj.name);
    try { if (pfx[0]) rValue = pfx[0]; } catch (e) { }
    return rValue;
}
//Check if object is hidden allocation question
function checkHiddenAnsLine(ObjId) {
    notVisible = false;
    var aSrc = getElement(ObjId);
    if (aSrc.className) {
        if (aSrc.className.toLowerCase() == 'hidePanel')
            notVisible = true;
    }
    if (aSrc.style.display.toLowerCase() == 'none')
        notVisible = true;
    return notVisible;
}
//Check if object is hidden allocation question
function checkHidden1(Obj, LineNo) {
    var aSrc = getElement(Obj);
    return checkHidden(Obj, LineNo)
}
//Check if object is hidden allocation question
function checkHidden2(aSrc, LineNo) {
    notVisible = false;
    if (aSrc != null) {
        while (aSrc != null & !notVisible) {
            try {
                if (aSrc.id.toLowerCase().indexOf('detailsline') != -1 &
				aSrc.id.toLowerCase().indexOf('col') == -1) {
                    if (aSrc.className.toLowerCase() == 'hidePanel')
                        notVisible = true;
                    if (aSrc.style.display.toLowerCase() == 'none')
                        notVisible = true;
                }
            }
            catch (e) { }
            aSrc = getParent(aSrc);
        }
    }
    return notVisible;
}
function getParent(aObj) {
    var elem = null;
    if (navigator.appName == 'Microsoft Internet Explorer')
        elem = aObj.parentElement;
    else
        elem = aObj.parentNode;

    return elem;
}
function formatInt(aVal1) {
    var aVal = aVal1.toString().replace(groupSep, '');
    var aVal = aVal.replace(decSep, '.');
    var res = "";
    if (!isNaN(aVal) && aVal.length > 0) {
        var aNum = Math.round(aVal * 100) / 100;
        var intPart = parseInt(aNum);
        var intStr = intPart.toString();
        var iy = 0;
        var aComma = "";
        for (var ix = 1; ix <= intStr.length; ix++) {
            if (iy == 3) { iy = 0; aComma = groupSep; } else { iy++; aComma = "" }
            res = intStr.substr(intStr.length - ix, 1) + aComma + res;
        }
    }
    else
        res = aVal1;
    return res;
}

function Trim(s) {
    return s.replace(/^\s*|\s*$/g, '');
}
function Trim1(s) {
    return s.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "");
}

function CheckFieldDefinition(aObj) {
    var aSrc = event.srcElement;
    if (aSrc == null)
        aSrc = aObj;

    switch (aSrc.tagName.toLowerCase()) {
        case "input":
            switch (aSrc.name.toLowerCase()) {
                case "ext_emailaddress":
                    valTF = 'false';

                    if (aSrc.length == 0)
                        valTF = 'true';
                    if (aSrc.value.indexOf('@') == -1)
                        valTF = 'true';
                    if (aSrc.value.indexOf('.') == -1)
                        valTF = 'true';
                    //
                    aSrc.required = valTF;
                    break;
                default:
                    switch (aSrc.type.toLowerCase()) {
                        case "text":
                            if (aSrc.length == 0)
                                valTF = 'true';
                            else
                                valTF = 'false';
                            aSrc.required = valTF;
                            break;
                        default:
                            break;
                    }
                    break;
            }
            break;
        case "select":
            aSrc.required = 'false'
            if (aSrc.options[aSrc.selectedIndex].value.length == 0)
                aSrc.required = 'true'
        default:
            break;
    }
}
// ============================================================================================
// Common Javascript
// ============================================================================================
function pageLoadFinishPage() {
    try {
        if (typeof surveyPageLoadedScript == 'function')
            surveyPageLoadedScript();
    } catch (e) { }
    //
    try {
        if (typeof PageLoadScript == 'function')
            PageLoadScript();
    } catch (e) { }

}
function pageLoad() {

    // Used to Restore the Status of the Page for Back Processing
    setHightWidth();
    pageLoading = true;
    var skip = true;
    for (var ix = 0; ix < document.forms[0].length; ix++) {
        switch (getElement(ix).tagName) {
            case "INPUT":
                if (getElement(ix).type == "button" || getElement(ix).type == "submit")
                    skip = true;
                else
                    skip = false;
                break;
            case "TEXTAREA":
            case "SELECT":
                skip = false;
                break;
            default:
                skip = true; break;
        }
        if (!skip) {
            if (getElement(ix).onclick) { getElement(ix).onclick() };
            if (getElement(ix).onchange) { getElement(ix).onchange() };
        }
    }
    //call custom load routine
    try {
        if (surveyPageLoadedScript())
            surveyPageLoadedScript();
    } catch (e) { if (advancedLogicDebug) alert('SurveyPageLoadedScript script failed : ' + e.message); }
    //trigger click events on selected items used for previous button
    trg_HideShow();
    //show body after hide show is initialized
    getElement('bodyDiv').className = 'clsbodydivs';
    //signify page loaded
    pageLoading = false;
}
function setHightWidth() {
    window.scrollbars = true;
    if (navigator.appName == 'Microsoft Internet Explorer') {
        if (getElement("M_Details")) {
            if (getElement("__Width")) {
                window.resizeTo(parseInt(getElement("__Width").value), parseInt(getElement("__Height").value)); //ReSize the Screen
                getElement("DetailsDiv").style.backgroundColor = getElement("M_Details").style.backgroundColor;
                getElement("DetailsDiv").style.height = getElement("M_Details").style.height;
                getElement("M_Details").style.height = "";
            }
            else {
                if (getElement("__StyleSheetName").length == 0) //if style sheet set do not set default widths
                {
                    getElement("DetailsDiv").style.height = getElement("M_Details").style.height;
                    getElement("DetailsDiv").style.width = getElement("M_Details").style.width;
                    getElement("M_Details").style.width = "100%";
                }
            }
        }
        else {
            if (getElement("__Width")) {
                window.resizeTo(parseInt(getElement("__Width").value), parseInt(getElement("__Height").value)); //ReSize the Screen
            }
        }
    }
    else {
        if (getElement("__Width"))
            window.resizeTo(parseInt(getElement("__Width").value), parseInt(getElement("__Height").value)); //ReSize the Screen
        //removed overflow
        if (navigator.appName == 'Microsoft Internet Explorer')
            getElement("detailsDiv").style = "BORDER-RIGHT:1px;BORDER-TOP:1px;BORDER-LEFT:1px;WIDTH:100%;BORDER-BOTTOM:1px;HEIGHT:90%";
    }
}
function setRadioExecClick(aName, aValue) {
    if (getElement(aName)) {
        var ix = 0;
        var found = false
        if (getElement(aName).length) {
            while (ix < getElement(aName).length && !found) {
                if (getElement(aName)[ix].value == aValue) {
                    getElement(aName)[ix].checked = true;
                    getElement(aName)[ix].onClick();
                    found = true;
                }
                ix++;
            }
        }
        else {
            if (getElement(aName).value == aValue)
                getElement(aName).checked = true;
        }
    }
}
function setRadio(aName, aValue) {
    if (getElement(aName)) {
        var ix = 0;
        var found = false
        if (getElement(aName).length) {
            while (ix < getElement(aName).length && !found) {
                if (getElement(aName)[ix].value == aValue) {
                    getElement(aName)[ix].checked = true;
                    found = true;
                }
                ix++;
            }
        }
        else {
            if (getElement(aName).value == aValue)
                getElement(aName).checked = true;
        }
    }
}
function setRadioRT(aName, aValue) {

    try {
        if (getElement(aName)) {
            var ix = 0;
            var found = false
            if (getElement(aName).length) {
                while (ix < getElement(aName).length && !found) {
                    if (getElement(aName)[ix].value == aValue) {
                        getElement(aName)[ix].click();
                        found = true;
                    }
                    ix++;
                }
            }
            else {
                if (getElement(aName).value == aValue)
                    getElement(aName).checked = true;
            }
        }
    } catch (e) { }
}
// get element for re-take of survey had try catch
function getElementRT(elementx) {
    var elem;

    if (navigator.appName == 'Microsoft Internet Explorer') {
        try { elem = document.all(elementx); } catch (e) { }
    }
    else {
        try {
            if (navigator.appName == 'Opera')
                elem = document.getElementById(elementx);
            else {
                elem = document.getElementById(elementx);
                if (elem == null) // get element by index number
                    elem = document.forms[0].elements[elementx];
            }
        }
        catch (e) { }
    }

    return elem;
}
var res;


// compatibility for other browsers.
function getElementDiv(elementx) {
    var elem;

    if (navigator.appName == 'Microsoft Internet Explorer') {
        elem = document.all(elementx);
    }
    else {

        elem = document.layers[elementx];
    }

    return elem;
}
function getFieldLabel(aSrc) {
    var fieldLabel = "";
    var firstChild = null;

    if (aSrc.title.length > 0)
        return aSrc.title; //Try to get field label from title
    else
        fieldLabel = aSrc.name; //Try to get field label
    if (!fieldLabel) {	//maybe a collection

        if (aSrc[0].title.length > 0)
            fieldLabel = aSrc[0].title;
        else
            fieldLabel = aSrc[0].name;
    }
    // Go From Left to Right and find the Label. Searches for the parent of the input box and takes the text from there
    if (aSrc.parentElement != null) {
        firstChild = aSrc.parentElement;
        if (aSrc.parentElement.parentElement != null) {
            for (var iy = 0; iy < aSrc.parentElement.parentElement.children.length; iy++) {
                if (aSrc.parentElement.parentElement.children(iy) == firstChild)
                    iy = aSrc.parentElement.parentElement.children.length; // At the Field In Error
                else
                    if (aSrc.parentElement.parentElement.children(iy).innerText != null)
                    fieldLabel = aSrc.parentElement.parentElement.children(iy).innerText;
            }
        }
    }
    return fieldLabel;
}
function setDot(Msg) {
    if (Msg.indexOf('?') == -1)
        return '.';
    else
        return '&nbsp;';
}
function setErrorMsg(aSrc, Msg) {

    var aRes = "";
    fieldLabel = getFieldLabel(aSrc);
    if (fieldLabel.indexOf('GText') > -1)
        fieldLabel = 'Click to find error';

    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"try {document.forms[0]." + aSrc.name + ".focus();} catch (e) {} return false;\">"
		+ fieldLabel + '.</a></u> &nbsp;' + Msg + '</font></span></br>';

    return aRes;
}
function setError(aSrc) {
    var aRes = "";
    fieldLabel = getFieldLabel(aSrc);
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"try {document.forms[0]." + aSrc.name + ".focus();} catch (e) {} return false;\">"
		+ fieldLabel + '.</a></u> &nbsp;' + SurveyRequired + '</font></span></br>';
    return aRes;
}
function setErrorCnf(aSrc) {
    var aRes = "";
    fieldLabel = getFieldLabel(aSrc);
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"try {document.forms[0]." + aSrc.name + ".focus();} catch (e) {} return false;\">"
		+ fieldLabel + '.</a></u> &nbsp;' + SurveyCnfRequired + '</font></span></br>';
    return aRes;
}

function formatIntA(aVal1) {
    var aVal = aVal1.value.toString().replace(groupSep, '').replace(decSep, '');
    aVal1.value = aVal;
    return aVal;
}

function checkIfFilled(aQuestion, aObj) {
    var aSrc = event.srcElement;
    var aCount = 0;
    if (aSrc == null)
        aSrc = aObj;
    if (aSrc.tagName == "INPUT") {

        switch (aSrc.type) {
            case "checkbox":
                if (!getElement(aQuestion).checkCount)
                    getElement(aQuestion).checkCount = 0;
                aCount = getElement(aQuestion).checkCount;
                if (aSrc.checked) {
                    aCount++;
                    aSrc.priorValue = 1;
                }
                else {
                    if (aSrc.priorValue)
                        aCount--;
                }
                if (aCount > 0)
                    getElement(aQuestion).required = 'false';
                else
                    if (!pageLoading)
                    getElement(aQuestion).required = 'true';
                getElement(aQuestion).checkCount = aCount;
                break;
            case "text":

                if (!getElement(aQuestion).checkCount)
                    getElement(aQuestion).checkCount = 0;
                aCount = getElement(aQuestion).checkCount;
                if (aSrc.value.length > 0) {
                    if (aSrc.value != " ") {
                        aCount++;
                        aSrc.priorV = aSrc.value;
                    }
                    else {
                        if (aSrc.priorV)
                            aCount--;
                    }
                }
                else
                    if (aSrc.priorV)
                    aCount--;
                if (aCount > 0)
                    getElement(aQuestion).required = 'false';
                else
                    if (!pageLoading)
                    getElement(aQuestion).required = 'true';
                getElement(aQuestion).checkCount = aCount;

                // Numeric Totalling
                if (aSrc.priorValue) {
                    //if allocate amount is filled in must be required

                    var aVal = 0;
                    aSrc.value = aSrc.value.replace(decSep, '');
                    aSrc.value = aSrc.value.replace(groupSep, '');

                    if (aSrc.value.length == 0)
                        aVal = 0;
                    else
                        aVal = parseInt(aSrc.value);
                    aVal = aVal - aSrc.priorValue;
                    getElement(aQuestion).allocTotal = getElement(aQuestion).allocTotal - aVal;
                    if (parseInt(aSrc.value))
                        aSrc.priorValue = parseInt(aSrc.value);
                    if (getElement(aQuestion).allocTotal == 0)
                        getElement(aQuestion).required = 'false';
                    else
                        getElement(aQuestion).required = 'true';
                }
                break;
            case "radio":

                if (!getElement(aQuestion).checkCount)
                    getElement(aQuestion).checkCount = 0;
                aCount = getElement(aQuestion).checkCount;

                if (aSrc.checked)
                    getElement(aQuestion).required = 'false';
                if (aSrc.checked)
                    aCount++;
                if (!pageLoading & !aSrc.checked)
                    aCount--;
                getElement(aQuestion).checkCount = aCount; // Count radio buttons for Combination with Text Boxes	


                break;

            default: getElement(aQuestion).required = 'true'; break;
        }
    }
    else {
        if (aSrc.tagName == "SELECT") {
            if (aSrc.selectedIndex > -1) {
                if (!pageLoading)  //used to ensure events fired during page load do not affect validation
                    getElement(aQuestion).required = 'false';
            }
        }
        if (aSrc.tagName == "TEXTAREA") {
            if (!getElement(aQuestion).checkCount)
                getElement(aQuestion).checkCount = 0;
            aCount = getElement(aQuestion).checkCount;
            if (aSrc.value.length > 0) {
                if (aSrc.value != " ") {
                    aCount++;
                    aSrc.priorV = aSrc.value;
                }
                else {
                    if (aSrc.priorV)
                        aCount--;
                }
            }
            else
                if (aSrc.priorV)
                aCount--;
            if (aCount > 0)
                getElement(aQuestion).required = 'false';
            else
                if (!pageLoading)
                getElement(aQuestion).required = 'true';
            getElement(aQuestion).checkCount = aCount;
        }
    }
}
function Trim(s) {
    return s.replace(/^\s*|\s*$/g, '');
}
function CheckFieldDefinition(aObj) {
    var aSrc = event.srcElement;
    if (aSrc == null)
        aSrc = aObj;
    switch (aSrc.tagName.toLowerCase()) {
        case "input":
            switch (aSrc.name.toLowerCase()) {
                case "ext_emailaddress":
                    valTF = 'false';

                    if (aSrc.length == 0)
                        valTF = 'true';
                    if (aSrc.value.indexOf('@') == -1)
                        valTF = 'true';
                    if (aSrc.value.indexOf('.') == -1)
                        valTF = 'true';
                    //
                    aSrc.required = valTF;
                    break;
                default:
                    switch (aSrc.type.toLowerCase()) {
                        case "text":
                            if (aSrc.length == 0)
                                valTF = 'true';
                            else
                                valTF = 'false';
                            aSrc.required = valTF;
                            break;
                        default:
                            break;

                    }
                    break;
            }
            break;
        case "select":
            aSrc.required = 'false'
            if (aSrc.options[aSrc.selectedIndex].value.length == 0)
                aSrc.required = 'true'
        default:
            break;
    }
}
// ============================================================================================
// Common Javascript
// ============================================================================================
function pageSubmit(aForm) {
    allReadySubmitted = PageButtons.disableAll();
    if (allReadySubmitted)
        return false;
    var ok = true;
    res = "";
    setHiddenElements(); // questions on hidden line must be initialized
    //Validate page
    if (!ValidatePageQ() || !val_InputBoxes()) {
        setPageErrors(res);
        PageButtons.enableAll();
        return false;
    }
    else {
        //Call custom submit script
        submitPage = true;
        try {
            if (typeof customSubmitScript == 'function') {
                customSubmitScript(aForm);
                //check for custom errors
                if (appendCustomErrorItems()) {
                    submitPage = false;
                    setPageErrors(res);
                }
            }
        }
        catch (e) { if (advancedLogicDebug) alert('CustomSubmitScript failed : ' + e.message); }
        //Submit page
        if (submitPage) {
            document.SurveyForm.submit();
            if (navigator.appName == 'Microsoft Internet Explorer')
                if (event) event.returnValue = false;
        }
        else
            PageButtons.enableAll();
        return false;
    }
}
//Set page errors for display
function setPageErrors(errors) {
    positionToButtons();
    getElement('ValidationSummary2').className = 'showPanel'
    getElement('ValidationSummary2').setAttribute('style', 'display:');
    getElement('ValidationSummary2').innerHTML = errors;
    if (SurveyPmtErrors.toLowerCase() == 'true' || SurveyPmtErrors.toLowerCase() == ' true')
        alert(SurveyPmtMsg);
    if (navigator.appName == 'Microsoft Internet Explorer')
        event.returnValue = false;
}
// radio box question
function val_RadioBoxQ(radioId, questionText, LineNo, lblId) {

    qok = false;
    questionText = rmvPipeTextPlaceHolder(questionText);
    var objx = getElement(radioId);
    var objFocus;
    if (objx.length > 1)
        objFocus = objx[0];
    else
        objFocus = objx;

    if (!checkHidden(objFocus, LineNo)) // check if question is hidden hide show
    {
        var objx = getElement(radioId);
        for (ix = 0; ix < objx.length; ix++) {
            if (objx[ix].checked)
                qok = true;
        }
        if (!qok) {
            res = res + setError1(radioId, questionText);
            setQuestionTextColor(lblId, SurveyErrorDec);
        }
        else
            setQuestionTextColor(lblId, '');
    }
    else
        qok = true;
    return qok;
}
//Input matrix drop down
function val_InpMxDrop(checkB, LineNo) {
    qok = true;
    rowId = checkB.replace('InpMx_', 'ARow')
    var objx = getElement(checkB);
    var objxFocus;
    if (objx.length > 1)
        objxFocus = objx[0];
    else
        objxFocus = objx
    if (!checkHidden(objxFocus, LineNo)) // check if question is hidden
    {
        if (!checkHiddenAnsLine(rowId)) {
            for (ix = 0; ix < objx.length; ix++) {
                if (objx[ix].selectedIndex == 0)
                    qok = false;
            }
        }
        else
            qok = true;
    }
    else
        qok = true;
    return qok;
}
//Input matrix text
function val_InpMxTxt(checkB, LineNo) {
    qok = true;
    rowId = checkB.replace('InpMx_', 'ARow')
    var objx = getElement(checkB);
    var objxFocus;
    if (objx.length > 1)
        objxFocus = objx[0];
    else
        objxFocus = objx

    if (!checkHidden(objxFocus, LineNo)) // check if question is hidden
    {
        if (!checkHiddenAnsLine(rowId)) {
            for (ix = 0; ix < getElement(checkB).length; ix++) {
                if (getElement(checkB)[ix].value.length == 0)
                    qok = false;
            }
        }
        else
            qok = true;
    }
    else
        qok = true;
    return qok;
}
//Input matrix number
function val_InpMxNum(checkB, LineNo, min, max, ValFunction) {
    qok = true;
    rowId = checkB.replace('InpMx_', 'ARow')
    var objx = getElement(checkB);
    var objxFocus;
    if (objx.length > 1)
        objxFocus = objx[0];
    else
        objxFocus = objx
    //if (ValFunction!=null)
    //    alert(ValFunction());
    if (!checkHidden(objxFocus, LineNo)) // check if question is hidden
    {
        if (!checkHiddenAnsLine(rowId)) {
            if (getElement(checkB).length) {
                for (ix = 0; ix < getElement(checkB).length; ix++) {
                    var objx = getElement(checkB)[ix];
                    if (!val_InpMxNum1(objx, min, max))
                        qok = false;
                }
            }
            else {
                qok = val_InpMxNum1(getElement(checkB), min, max);
            }
        }
        else
            qok = true;
    }
    else
        qok = true;
    return qok;
}
function val_InpMxNum1(objx, min, max) {
    qok = true;
    if (objx.value.length == 0) //initialize to 0 is field is blank
        objx.value = '0';
    if (!isNaN(objx.value) && objx.value.length > 0) {
        intPart = parseFloat(objx.value);
        if (intPart < min || intPart > max)
            qok = false;
    }
    else
        qok = false;
    return qok;
}
function chkHSIMx(aSrc, mxType) {//hide show input matrix check input
    if (!aSrc.length) //a collection may be passed. if not try to get the collection using name
        aObjects = getElement(aSrc.name);
    else
        aObjects = aSrc; //assign collection
    //check for collection if not make collection of 1
    if (!aObjects.length) {
        aObjects = new Array(1);
        aObjects[0] = getElement(aSrc.name);
    }
    //
    for (x = 0; x < aObjects.length; x++) {
        aObj = aObjects[x];
        filled = false;
        switch (mxType.toLowerCase()) {
            case 'numeric':
                if (aObj.value.length > 0) {
                    numVal = convertNum(aObj);
                    if (numVal > 0)
                        return true;
                }
                break;
            case 'text':
                if (aObj.value.length > 0)
                    return true;
                break;
            case 'dropdown':
                if (aObj[aObj.selectedIndex].text.length > 0)
                    return true;
                break;
        }
    }
    return filled;
}
function getNumber(aObjId, col) {
    total = 0;
    aObj = getElement(aObjId)
    if (aObj.length) //if a collection
    {
        if (col == -1) // if col not specified then total row
        {
            for (ix = 0; ix < aObj.length; ix++)
                total = total + convertNum(aObj[ix])
        }
        else {
            if (col <= aObj.length)
                total = total + convertNum(aObj[col - 1])
        }
    }
    else {
        total = total + convertNum(aObj);
    }
    if (isNaN(total))
        total = 0;
    return total;
}
function convertNum(aObj) {
    intPart = 0;
    if (aObj.value == '')
        aObj.value = '0';
    if (!isNaN(aObj.value))
        intPart = parseFloat(aObj.value);
    else
        aObj.value = '0';
    return intPart;
}
//likert questions
function val_RadioBox(radioId, questionText, LineNo, lblId) {
    qok = false;
    questionText = rmvPipeTextPlaceHolder(questionText);
    rowId = radioId.replace('RadioL_', 'ARow');
    var objx = getElement(radioId);
    var objFocus;
    if (objx.length > 1)
        objFocus = objx[0];
    else
        objFocus = objx;
    if (!checkHidden(objFocus, LineNo)) // check if question is hidden hide show
    {
        if (!checkHiddenAnsLine(rowId)) //make sure row is not hidden ans filtering
        {
            var objx = getElement(radioId);

            for (ix = 0; ix < objx.length; ix++) {
                if (objx[ix].checked)
                    qok = true;
            }
            if (!qok) {
                res = res + setError1(radioId, questionText);
                setQuestionTextColor(lblId, SurveyErrorDec);
            }
            else
                setQuestionTextColor(lblId, '');
        }
        else
            qok = true;
    }
    else
        qok = true;
    return qok;
}
//likert slider
function val_RadioBoxSlider(inputId, questionText, LineNo, lblId) {
    qok = false;
    questionText = rmvPipeTextPlaceHolder(questionText);
    rowId = inputId.replace('RadioL_', 'ARow');
    var objx = getElement(inputId);
    var objFocus;
    if (objx.length > 1)
        objFocus = objx[0];
    else
        objFocus = objx;
    if (!checkHidden(objFocus, LineNo)) // check if question is hidden hide show
    {
        if (!checkHiddenAnsLine(rowId)) //make sure row is not hidden ans filtering
        {
            if (getElement(inputId).value.length>0)
                qok = true;
            else
                qok = false;
            if (!qok) {
                res = res + setError1(inputId, questionText);
                setQuestionTextColor(lblId, SurveyErrorDec);
            }
            else
                setQuestionTextColor(lblId, '');
        }
        else
            qok = true;
    }
    else
        qok = true;
    return qok;
}
//max difference
var m_maxDiffDupCheck = '';
function val_MaxDiff(radioId, questionText, LineNo, ansId, Qid) {
    dupError = false;
    qok = false;
    var answerid = '';
    questionText = rmvPipeTextPlaceHolder(questionText);
    rowId = 'ARow' + ansId;
    var objx = getElement(radioId);
    var objFocus;
    if (objx.length > 1)
        objFocus = objx[0];
    else
        objFocus = objx;
    if (!checkHidden(objFocus, LineNo)) // check if question is hidden hide show
    {
        var objx = getElement(radioId);
        for (ix = 0; ix < objx.length; ix++) {
            if (objx[ix].checked) {
                qok = true;
                if (objx[ix].value.indexOf(m_maxDiffDupCheck) > -1 && m_maxDiffDupCheck != '') {
                    qok = false;
                    dupError = true;
                }
                else
                    m_maxDiffDupCheck = objx[ix].value.substring(0, objx[ix].value.length - 2);
            }
        }
        if (!qok) {
            if (dupError)
                res = res + setErrorMxDiff1(radioId, questionText);
            else
                res = res + setErrorMxDiff(radioId, questionText);
            setQuestionTextColor(Qid, SurveyErrorDec);
        }
        else {
            setQuestionTextColor(Qid, '');
        }
    }
    else
        qok = true;
    return qok;
}
// Check box exclusive awnser return false if hidden
function val_CheckBE(checkB, LineNo, questionId) {
    qok = true;
    if (!checkHidden(getElement(checkB), LineNo)) {  // check if answerline is not hidden answer filtering
        qok = getElement(checkB).checked;
    }
    else
        qok = false;

    return qok;
}
// check box
function val_CheckB(checkB, LineNo, questionId) {
    qok = true;
    if (!checkHidden(getElement(checkB), LineNo)) {  // check if answerline is not hidden answer filtering
        qok = getElement(checkB).checked;
    }

    return qok;
}
//check if checkbox has selected more that max allowed
function val_CheckBMaxSelect(maxNo, LineNo, checkArrayList) {
    totSelected = 0;
    elemList = checkArrayList.split(',');
    for (ix = 0; ix < elemList.length; ix++) {
        if (!checkHidden(getElement(elemList[ix]), LineNo)) {
            if (getElement(elemList[ix]).checked)
                totSelected++
        }
    }
    if (totSelected > maxNo)
        return false;
    else
        return true;
}
// check box
function val_CheckB1(checkB, LineNo) {
    qok = false;
    rowId = checkB.replace('Checkl_', 'ARow')
    var objx = getElement(checkB);
    var objxFocus;
    if (objx.length > 1)
        objxFocus = objx[0];
    else
        objxFocus = objx

    if (!checkHidden(objxFocus, LineNo)) // check if question is hidden
    {
        if (!checkHiddenAnsLine(rowId)) {
            for (ix = 0; ix < getElement(checkB).length; ix++) {

                if (getElement(checkB)[ix].checked)
                    qok = true;


            }
        }
        else
            qok = true;
    }
    else
        qok = true;
    return qok;
}
// input box
function val_InputBox(inputBoxId, questionText, LineNo) {
    qok = true;
    questionText = rmvPipeTextPlaceHolder(questionText);
    var objx = getElement(inputBoxId);

    if (!checkHidden2(objx, LineNo)) // check if question is hidden
    {
        if (objx.value.length == 0) {
            qok = false;
            res = res + setError1(inputBoxId, questionText);
        }
    }
    return qok;
}
// input box
function val_FreeText(inputBoxId, questionText, LineNo, lblquestionId) {
    qok = true;
    questionText = rmvPipeTextPlaceHolder(questionText);
    var objx = getElement(inputBoxId);

    if (!checkHidden(objx, LineNo)) // check if question is hidden
    {
        if (objx.value.length == 0) {
            qok = false;
            res = res + setError1(inputBoxId, questionText);
        }
    }
    if (!qok)
        setQuestionTextColor(lblquestionId, SurveyErrorDec);
    else
        setQuestionTextColor(lblquestionId, '');
    return qok;
}
// input box
function val_ShortFreeText(inputBoxId, questionText, LineNo, lblquestionId) {
    sqok = true;
    questionText = rmvPipeTextPlaceHolder(questionText);
    var objx = getElement(inputBoxId);

    if (!checkHidden(objx, LineNo)) // check if question is hidden
    {
        if (objx.value.length == 0) {
            sqok = false;
            res = res + setError1(inputBoxId, questionText);
        }
    }
    if (!sqok)
        setQuestionTextColor(lblquestionId, SurveyErrorDec);
    else
        setQuestionTextColor(lblquestionId, '');
    return sqok;
}
// numeric text
function val_NumericText(inputBoxId, questionText, LineNo, lblquestionId, maxValue, minValue, basedOnQuest) {
    //parseInt returns 0 when 09 is entered. use parse float instead
    var objy;
    ErrorMax = minValue + ' - ' + maxValue;
    questionText = rmvPipeTextPlaceHolder(questionText);
    sqok = true;
    intPart = 0;
    if (!checkHidden(objx, LineNo)) // check if question is hidden
    {
        var objx = getElement(inputBoxId);
        if (!isNaN(objx.value) && objx.value.length > 0)
            intPart = parseFloat(objx.value);
        else
            sqok = false;
        if (basedOnQuest.length > 0) //validation based on question
        {
            objy = getElement(basedOnQuest);
            ErrorMax = minValue + ' - ' + objy.value;
        }
        if (sqok) {
            if (basedOnQuest.length > 0) //validation based on question
            {
                intBasedOn = 0;
                if (!isNaN(objy.value) && objy.value.length > 0) {
                    intBasedOn = parseFloat(objy.value);
                    if (intPart > intBasedOn)
                        sqok = false;
                }
                else
                    sqok = false;
                //ErrorMax=intBasedOn;
                ErrorMax = "0" + " - " + intBasedOn;
            }
            else {
                ErrorMax = minValue + ' - ' + maxValue;
                if (maxValue != 0)  //validation based on numeric value only
                {
                    if (intPart > maxValue)
                        sqok = false;
                }
                if (minValue != 0)  //validation based on numeric value only
                {
                    if (intPart < minValue)
                        sqok = false;
                }
            }

        }
        if (!sqok) {
            if (ErrorMax == 0)
                res = res + setError1(inputBoxId, questionText);
            else
                res = res + setErrorNumericTextError(inputBoxId, questionText, ErrorMax);
            setQuestionTextColor(lblquestionId, SurveyErrorDec);
        }
        else
            setQuestionTextColor(lblquestionId, '');
    }
    return sqok;
}
function rmvPipeTextPlaceHolder(questionText) {
    var Regx = /{.*}/;
    questionText = questionText.replace(Regx, '');
    return questionText;
}
// input box
function val_DropDown(dId, questionText, LineNo, questionId) {
    qok = true;
    questionText = rmvPipeTextPlaceHolder(questionText);
    if (!checkHidden(getElement(dId), LineNo)) // check if question is hidden
    {
        var objx = getElement(dId);
        //Selected index of 0 not selected
        if (objx.selectedIndex == 0) {
            qok = false;
            res = res + setError1(dId, questionText);
        }
        if (!qok)
            setQuestionTextColor(questionId, SurveyErrorDec);
        else
            setQuestionTextColor(questionId, '');
    }

    return qok;
}
// validate allocation question
function totNum(dId, lineNo) {

    var val = 0;
    try {
        val1 = formatIntA(getElement(dId));
        val = parseInt(val1);
    }
    catch (e) {
        val = 0;
    }
    //initialize to 0 
    if (isNaN(val))
        val = 0;
    return val;
}
function formatInt1(aVal1) {
    res = aVal1;
    return res;
}
// Get element by name
function getElementUsingName(elementx) {
    var elem;
    if (navigator.appName == 'Microsoft Internet Explorer')
        elem = document.all(elementx);
    else
        elem = document.getElementByName(elementx);
    return elem;
}
// Get form elements
function getFormElements() {
    if (navigator.appName == 'Microsoft Internet Explorer')
        return document.all;
    else
        return document.forms[0]

}
/// set allocation error
function setErrorAlloc(questionid, questionText, remValue, controlTotal) {
    aRes = '';
    aRes = aRes + "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"getElement('lbl_" + questionid + "').focus();return false;\">"
				 + questionText + setDot(questionText) + '</a></u> &nbsp; ' + SurveyAllocError.replace('%1', remValue).replace('%2', controlTotal) + '</font></span></br>';

    return aRes;
}
function setErrorRank(questionid, questionText, missingValues) {
    aRes = '';
    aRes = aRes + "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"getElement('lbl_" + questionid + "').focus();return false;\">"
				 + questionText + setDot(questionText) + '</a></u> &nbsp; ' + SurveyRankQRequired.replace('{0}', missingValues) + '</font></span></br>';

    return aRes;
}
function setErrorRankSort(questionid, questionText, missingValues) {
    aRes = '';
    aRes = aRes + "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"getElement('lbl_" + questionid + "').focus();return false;\">"
				 + questionText + setDot(questionText) + '</a></u> &nbsp; ' + SurveyunRankedSort + '</font></span></br>';

    return aRes;
}
function setErrorRankDup(questionid, questionText) {
    aRes = '';
    aRes = aRes + "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"getElement('lbl_" + questionid + "').focus();return false;\">"
				 + questionText + setDot(questionText) + '</a></u> &nbsp; ' + SurveyRankQRequiredDup + '</font></span></br>';

    return aRes;
}
function setErrorExtraRank(questionid, questionText, aType, ctlValue) {
    aRes = '';
    aRes = aRes + "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"getElement('lbl_" + questionid + "').focus();return false;\">"
				 + questionText + setDot(questionText) + '</a></u> &nbsp; ' + SurveyRankQExtra + ' ' + ctlValue + '</font></span></br>';
    return aRes;
}
//
function setQuestionTextColor(questionid, tcolor) {
    sp = questionid.indexOf('_');
    ln = questionid.length;
    ex = ln - sp;
    if (sp != -1)
        lblValue = 'lbl' + questionid.substring(sp, ex + 6);
    else
        lblValue = 'lbl_' + questionid;
    //likert questions and radio questions have - in different places
    try {
        getElement(lblValue).style.borderLeft = tcolor;
    }
    catch (e) {
        lblValue = lblValue.replace('-', '_').replace('-', '_').replace('-', '_').replace('-', '_');
        //getElement(lblValue).style.color=tcolor;
        getElement(lblValue).style.borderLeft = tcolor;
    }

}
//Set error
function setError1(questionid, questionText) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + SurveyQRequired + '</font></span></br>';
    return aRes;
}
//Set error
function setErrorMxDiff(questionid, questionText) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + SurveyMaxDiff + '</font></span></br>';
    return aRes;
}
//Set error
function setErrorMxDiff1(questionid, questionText) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + SurveyMaxDiffCol + '</font></span></br>';
    return aRes;
}
//Set error for question from advanced logic
function setError1AL(questionid, questionText) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;</font></span></br>';
    return aRes;
}
//Set error
function setErrorExclusive(questionid, questionText) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + SurveyAnsExclusive + '</font></span></br>';
    return aRes;
}
//Set error
function setErrorMaxAnswer(maxAnswer, questionid, questionText) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + maxAnswer + ' ' + SurveyErrorCMS + '</font></span></br>';
    return aRes;
}
function setErrorCustom(questionid, questionText) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + '</font></span></br>';
    return aRes;
}
//Set error
function setErrorNumericTextError(questionid, questionText, MaxValue) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + SurveyQNumericTextRequired + ' ' + MaxValue + '</font></span></br>';
    return aRes;
}
function setErrorInputMxError(questionid, questionText, QuestionTotal) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + SurveyQTotal + ' ' + QuestionTotal + '</font></span></br>';
    return aRes;
}
function setErrorInputMxError1(ansid, ansText, min, max) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ ansText + '</a></u> &nbsp;' + SurveyQtotalMinMax + ' ' + min + " - " + max + '</font></span></br>';
    return aRes;
}
//Set error input
function setError2(questionid, questionText) {
    aRes = '';
    aRes = "  <SPAN class='clsErrorMsg'><font size=2 Color=" + SurveyErrorColor + "><u><a style='cursor:hand' onclick=\"\">"
			+ questionText + setDot(questionText) + '</a></u> &nbsp;' + SurveyRequired + '</font></span></br>';
    return aRes;
}
//
//Validate input boxes
//
//check input filled
function checkInpFilled(aQuestion, aObj) {
    // do not delete required.
}
//Validate input boxes
function val_InputBoxes() {
    //get input boxes
    var elm = document.getElementsByTagName('input');
    iOkInput = valEmelemts(elm);
    //get select boxes
    elm = document.getElementsByTagName('select');
    iOkSelect = valEmelemts(elm);
    if (!iOkSelect || !iOkInput)
        iOk = false;
    else
        iOk = true;
    //check for custom error validation
    for (var ix = 0; ix < cErrorsFunctions.length; ix++) {
        if (cErrorsFunctions[ix].length > 0) {
            var functionDemo = new Function(cErrorsFunctions[ix])

            functionDemo();

            if (!cErrorsFunctionsEval[ix])
                iOk = false;
        }
    }
    //check for custom errors
    if (appendCustomErrorItems())
        iOk = false;
    return iOk;
}
function valEmelemts(elements) {
    eOk = true;
    for (var ix = 0; ix < elements.length; ix++) {
        aSrc = elements[ix];
        if ((aSrc.tagName == "INPUT" || aSrc.tagName == "SELECT") & !checkHidden2(aSrc)) {
            var chg = '';
            if (!aSrc.onchange)
                chg = '';
            else
                chg = aSrc.onchange.toString();
            //if (chg.toLowerCase().indexOf('checkinpfilled')!=-1)
            //{
            switch (aSrc.type) {
                case "select-one":
                    if (chg.toLowerCase().indexOf('checkinpfilled') != -1) {
                        fok = true;
                        fdok = true;
                        if (aSrc.selectedIndex > -1) {
                            if (Trim(aSrc[aSrc.selectedIndex].value).length == 0) {
                                eOk = false;
                                res = res + setError(aSrc);
                            }
                        }
                        else {
                            eOk = false;
                            res = res + setError(aSrc);
                        }
                    }
                    break;
                case "text":
                    if (chg.toLowerCase().indexOf('checkinpfilled') != -1 || aSrc.value.length > 0) {
                        aSrc.value = Trim(aSrc.value);
                        fok = true;
                        fdok = true;
                        if (aSrc.value.length == 0)
                            fok = false;
                        else {
                            //check emailaddress
                            if (aSrc.name.toLowerCase().indexOf('email') != -1) {
                                if (!iseMail(aSrc.value))
                                    fok = false;
                                else {
                                    //check for compare field
                                    cmpFieldName = aSrc.name.replace('ext_', 'cnf_');
                                    if (getElement(cmpFieldName) != null) {
                                        if (Trim(getElement(cmpFieldName).value).toLowerCase() != Trim(aSrc.value).toLowerCase()) {
                                            fok = false;
                                            res = res + setErrorCnf(aSrc);
                                            aSrc = getElement(cmpFieldName);
                                        }
                                    }
                                }
                            }
                            //check zip
                            if (aSrc.name.toLowerCase().indexOf('zipcode') != -1) {
                                if (!isZip(aSrc.value))
                                    fok = false;
                            }
                            //check phone
                            if (aSrc.name.toLowerCase().indexOf('_phone') != -1) {
                                if (!isPhone(aSrc.value))
                                    fok = false;
                            }
                        }
                        if (!fok) {
                            res = res + setError(aSrc);
                            eOk = false;
                        }
                    }
                    break;
                case "checkbox":
                case "radio":
                    if (chg.toLowerCase().indexOf('checkinpfilled') != -1) {
                        fok = true;
                        fdok = true;
                        radOk = false;
                        aSrc = getElement(aSrc.name);
                        if (aSrc.length) {
                            for (ixy = 0; ixy < aSrc.length; ixy++) {
                                if (aSrc[ixy].checked)
                                    radOk = true;
                            }
                        }
                        else {
                            if (aSrc.checked)
                                radOk = true;
                        }
                        if (!radOk) {
                            eOk = false;
                            res = res + setError(aSrc);
                        }
                    }
                    break;
                default:
                    break;
            }
            //}
        }
    }
    return eOk;
}
function appendCustomErrorItems() {
    errorsFound = false;
    for (ix = 0; ix < cErrors.length; ix++) {
        if (cErrors[ix].length > 0) {
            if (cErrorsType[ix].length == 0) //input box else question
                res = res + setErrorMsg(getElement(cErrorsObj[ix]), cErrors[ix]);
            else {
                res = res + setError1AL(getElement(cErrorsObj[ix]), cErrors[ix]);
                setQuestionTextColor(cErrorsObj[ix], SurveyErrorDec);
            }
            cErrors[ix] = '';
            cErrorsObj[ix] = '';
            cErrorsCount = 0;
            errorsFound = true;

        }
    }
    return errorsFound
}
// Is email address
function iseMail(email) {
    var Regx = /^[\w\.\-]+\@[\w\.\-]+\.[\w.]{2,}$/;
    return (Regx.test(email));
}
// Custom regular expression validation
function isCustomValidation(aObj, regExpression, msg) {
    var Regx = new RegExp(regExpression);
    if (!Regx.test(aObj.value)) {
        aObj.value = '';
        if (aObj.id.length > 0)
            foundm = checkItem(aObj.id);
        else
            foundm = checkItem(aObj.name);
        if (!foundm) {
            cErrorsCount = cErrorsCount + 1;
            cErrors[cErrorsCount] = msg;
            if (aObj.id.length > 0)
                cErrorsObj[cErrorsCount] = aObj.id;
            else
                cErrorsObj[cErrorsCount] = aObj.name;
        }
    }
    else {
        if (aObj.id.length > 0)
            removeErrorItem(aObj.id);
        else
            removeErrorItem(aObj.name);
    }
}
function isEmailAddress(aObj, msg) {
    failed = false;
    if (iseMail(aObj.value))
        failed = true;
    if (!failed) {
        aObj.value = '';
        if (cErrorsCount < cErrors.length) {
            if (aObj.id.length > 0)
                foundm = checkItem(aObj.id);
            else
                foundm = checkItem(aObj.name);
            if (!foundm) {
                cErrorsCount = cErrorsCount + 1;
                cErrors[cErrorsCount] = msg;
                if (aObj.id.length > 0)
                    cErrorsObj[cErrorsCount] = aObj.id;
                else
                    cErrorsObj[cErrorsCount] = aObj.name;
            }
        }
    }
    else {
        if (aObj.id.length > 0)
            removeErrorItem(aObj.id);
        else
            removeErrorItem(aObj.name);
    }
}
function isCustomNum(aObj, min, max, msg) {
    failed = false;
    var Regx = /\D/;
    if (!Regx.test(aObj.value)) {
        integ = parseInt(aObj.value)
        if (integ < min || integ > max) {
            failed = true;
            aObj.value = '';
        }
    }
    else {
        failed = true;
        aObj.value = '';
    }
    if (failed) {
        if (cErrorsCount < cErrors.length) {
            if (aObj.id.length > 0)
                foundm = checkItem(aObj.id);
            else
                foundm = checkItem(aObj.name);
            if (!foundm) {
                cErrorsCount = cErrorsCount + 1;
                cErrors[cErrorsCount] = msg;
                if (aObj.id.length > 0)
                    cErrorsObj[cErrorsCount] = aObj.id;
                else
                    cErrorsObj[cErrorsCount] = aObj.name;
            }
        }

    }
    else {
        if (aObj.id.length > 0)
            removeErrorItem(aObj.id);
        else
            removeErrorItem(aObj.name);
    }

}

function isCustomCompare(aObjName, aObjName1, msg) {
    aObj = getElement(aObjName);
    aObj1 = getElement(aObjName1);
    failed = false;
    if (aObj.value.toLowerCase() != aObj1.value.toLowerCase())
        failed = true;
    if (failed) {
        aObj1.value = '';
        if (cErrorsCount < cErrors.length) {
            if (aObj.id.length > 0)
                foundm = checkItem(aObj.id);
            else
                foundm = checkItem(aObj.name);
            if (!foundm) {
                cErrorsCount = cErrorsCount + 1;
                cErrors[cErrorsCount] = msg;
                if (aObj.id.length > 0)
                    cErrorsObj[cErrorsCount] = aObj.id;
                else
                    cErrorsObj[cErrorsCount] = aObj.name;
            }
        }
    }
    else {
        if (aObj.id.length > 0)
            removeErrorItem(aObj.id);
        else
            removeErrorItem(aObj.name);
    }
}
function checkItem(aid) {
    foundm = false;
    //remove error item from list
    for (ix = 0; ix < cErrors.length; ix++) {
        if (cErrorsObj[ix].length > 0) {
            if (cErrorsObj[ix] == aid)
                foundm = true;
        }
    }
    return foundm;
}
function removeErrorItem(id) {
    //remove error item from list
    for (ix = 0; ix < cErrors.length; ix++) {
        if (cErrorsObj[ix].length > 0) {
            if (cErrorsObj[ix] == id) {
                cErrors[ix] = '';
                cErrorsObj[ix] = '';
            }
        }
    }
}
function isZip(zip) {
    // Combined UK and US validator
    var Regx = /^\d{5}(\-\d{4})?$|^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$/;
    var RegxCanada = /^[a-zA-Z]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/;
    if (!Regx.test(zip) && !RegxCanada.test(zip))
         return (false);
     else
         return (true);
}
function isPhone(phone) {
    // us Phone var Regx = /^\(?\d{3}\)?.?\d{3}.?\d{4}$/;
    var Regx = /.*/;
    return (Regx.test(phone));
}
//--Piped text  function
function getPipeValue(searchValue) {
    for (ixm = 0; ixm < pipeText.length; ixm++) {
        if (pipeText[ixm].toLowerCase().indexOf(searchValue.toLowerCase()) != -1) {
            pair = pipeText[ixm].split(':')
            if (pair.length > 1)
                return pair[1];
        }
    }
    return '';
}
function getPipedExpression(aObj) {
    replaceV = '';
    if (aObj.innerText) {
        var Regx = /{.*}/;
        if (Regx.test(aObj.innerText)) {
            sp = aObj.innerText.indexOf('{');
            ep = aObj.innerText.indexOf('}');
            replaceV = aObj.innerText.substring(sp, ep + 1);
        }
    }
    return replaceV;
}
function setPipedTextOnPageLoad() {

    loadPipedText();
    for (ixp1 = 0; ixp1 < pipeText.length; ixp1++) {
        if (pipeText[ixp1].length > 0) {
            setPipedText(pipeText[ixp1].split(':')[0])
        }
    }
}
function setPipedText(PlaceHolder) {
    loadPipedText();
    for (ixy = 0; ixy < pipedQuestionText.length; ixy++) {
        if (pipedQuestionText[ixy].toLowerCase().indexOf(PlaceHolder.toLowerCase()) != -1) {
            if (getElement(pipedQuestionCtl[ixy]).innerHTML) // ensure object has
            {
                repVal = PlaceHolder;
                newVal = unescape(getPipeValue(repVal));
                if (newVal.length > 0) {
                    //if text contains a bar it means first value is the pipe text and the second display value
                    splValues = newVal.split('^');
                    displayVal = newVal;
                    if (splValues.length == 2) {
                        newVal = splValues[0];
                        displayVal = splValues[1];
                    }
                    getElement(pipedQuestionCtl[ixy]).innerHTML = HtmlDecode(pipedQuestionText[ixy].replace(repVal, displayVal));
                    getElement(pipedQuestionCtl[ixy].replace('lbl_', 'pv_')).value = newVal; //set piped text value
                }
            }
        }
    }
}
function loadPipedText() {
    pipeText = getElement("__Pipe").value.split('|');
}
function setPlaceHolder(placeHolder, pipedText) {
    updated = false;
    loadPipedText();
    getElement("__Pipe").value = '';
    for (ixp = 0; ixp < pipeText.length; ixp++) {
        if (pipeText[ixp].length > 0) {
            if (pipeText[ixp].toLowerCase().indexOf(placeHolder.toLowerCase()) != -1) // ensure object has 
            {
                pipeText[ixp] = placeHolder + ':' + pipedText;
                updated = true;
            }
            getElement("__Pipe").value = getElement("__Pipe").value + pipeText[ixp] + '|';
        }
    }
    if (!updated)
        getElement("__Pipe").value = getElement("__Pipe").value + placeHolder + ':' + escape(pipedText);
    loadPipedText();
}
function HtmlDecode(s) {
    var out = "";
    if (s == null) return;

    var l = s.length;
    for (var i = 0; i < l; i++) {
        var ch = s.charAt(i);

        if (ch == '&') {
            var semicolonIndex = s.indexOf(';', i + 1);
            notVlaid = false;
            if (semicolonIndex > 0) {
                var entity = s.substring(i + 1, semicolonIndex);
                if (entity.length > 1 && entity.charAt(0) == '#') {
                    if (entity.charAt(1) == 'x' || entity.charAt(1) == 'X')
                        ch = String.fromCharCode(eval('0' + entity.substring(1)));
                    else
                        ch = String.fromCharCode(eval(entity.substring(1)));
                }
                else {
                    switch (entity) {
                        case 'quot': ch = String.fromCharCode(0x0022); break;
                        case 'amp': ch = String.fromCharCode(0x0026); break;
                        case 'lt': ch = String.fromCharCode(0x003c); break;
                        case 'gt': ch = String.fromCharCode(0x003e); break;
                        case 'nbsp': ch = String.fromCharCode(0x00a0); break;
                        case 'iexcl': ch = String.fromCharCode(0x00a1); break;
                        case 'cent': ch = String.fromCharCode(0x00a2); break;
                        case 'pound': ch = String.fromCharCode(0x00a3); break;
                        case 'curren': ch = String.fromCharCode(0x00a4); break;
                        case 'yen': ch = String.fromCharCode(0x00a5); break;
                        case 'brvbar': ch = String.fromCharCode(0x00a6); break;
                        case 'sect': ch = String.fromCharCode(0x00a7); break;
                        case 'uml': ch = String.fromCharCode(0x00a8); break;
                        case 'copy': ch = String.fromCharCode(0x00a9); break;
                        case 'ordf': ch = String.fromCharCode(0x00aa); break;
                        case 'laquo': ch = String.fromCharCode(0x00ab); break;
                        case 'not': ch = String.fromCharCode(0x00ac); break;
                        case 'shy': ch = String.fromCharCode(0x00ad); break;
                        case 'reg': ch = String.fromCharCode(0x00ae); break;
                        case 'macr': ch = String.fromCharCode(0x00af); break;
                        case 'deg': ch = String.fromCharCode(0x00b0); break;
                        case 'plusmn': ch = String.fromCharCode(0x00b1); break;
                        case 'sup2': ch = String.fromCharCode(0x00b2); break;
                        case 'sup3': ch = String.fromCharCode(0x00b3); break;
                        case 'acute': ch = String.fromCharCode(0x00b4); break;
                        case 'micro': ch = String.fromCharCode(0x00b5); break;
                        case 'para': ch = String.fromCharCode(0x00b6); break;
                        case 'middot': ch = String.fromCharCode(0x00b7); break;
                        case 'cedil': ch = String.fromCharCode(0x00b8); break;
                        case 'sup1': ch = String.fromCharCode(0x00b9); break;
                        case 'ordm': ch = String.fromCharCode(0x00ba); break;
                        case 'raquo': ch = String.fromCharCode(0x00bb); break;
                        case 'frac14': ch = String.fromCharCode(0x00bc); break;
                        case 'frac12': ch = String.fromCharCode(0x00bd); break;
                        case 'frac34': ch = String.fromCharCode(0x00be); break;
                        case 'iquest': ch = String.fromCharCode(0x00bf); break;
                        case 'Agrave': ch = String.fromCharCode(0x00c0); break;
                        case 'Aacute': ch = String.fromCharCode(0x00c1); break;
                        case 'Acirc': ch = String.fromCharCode(0x00c2); break;
                        case 'Atilde': ch = String.fromCharCode(0x00c3); break;
                        case 'Auml': ch = String.fromCharCode(0x00c4); break;
                        case 'Aring': ch = String.fromCharCode(0x00c5); break;
                        case 'AElig': ch = String.fromCharCode(0x00c6); break;
                        case 'Ccedil': ch = String.fromCharCode(0x00c7); break;
                        case 'Egrave': ch = String.fromCharCode(0x00c8); break;
                        case 'Eacute': ch = String.fromCharCode(0x00c9); break;
                        case 'Ecirc': ch = String.fromCharCode(0x00ca); break;
                        case 'Euml': ch = String.fromCharCode(0x00cb); break;
                        case 'Igrave': ch = String.fromCharCode(0x00cc); break;
                        case 'Iacute': ch = String.fromCharCode(0x00cd); break;
                        case 'Icirc': ch = String.fromCharCode(0x00ce); break;
                        case 'Iuml': ch = String.fromCharCode(0x00cf); break;
                        case 'ETH': ch = String.fromCharCode(0x00d0); break;
                        case 'Ntilde': ch = String.fromCharCode(0x00d1); break;
                        case 'Ograve': ch = String.fromCharCode(0x00d2); break;
                        case 'Oacute': ch = String.fromCharCode(0x00d3); break;
                        case 'Ocirc': ch = String.fromCharCode(0x00d4); break;
                        case 'Otilde': ch = String.fromCharCode(0x00d5); break;
                        case 'Ouml': ch = String.fromCharCode(0x00d6); break;
                        case 'times': ch = String.fromCharCode(0x00d7); break;
                        case 'Oslash': ch = String.fromCharCode(0x00d8); break;
                        case 'Ugrave': ch = String.fromCharCode(0x00d9); break;
                        case 'Uacute': ch = String.fromCharCode(0x00da); break;
                        case 'Ucirc': ch = String.fromCharCode(0x00db); break;
                        case 'Uuml': ch = String.fromCharCode(0x00dc); break;
                        case 'Yacute': ch = String.fromCharCode(0x00dd); break;
                        case 'THORN': ch = String.fromCharCode(0x00de); break;
                        case 'szlig': ch = String.fromCharCode(0x00df); break;
                        case 'agrave': ch = String.fromCharCode(0x00e0); break;
                        case 'aacute': ch = String.fromCharCode(0x00e1); break;
                        case 'acirc': ch = String.fromCharCode(0x00e2); break;
                        case 'atilde': ch = String.fromCharCode(0x00e3); break;
                        case 'auml': ch = String.fromCharCode(0x00e4); break;
                        case 'aring': ch = String.fromCharCode(0x00e5); break;
                        case 'aelig': ch = String.fromCharCode(0x00e6); break;
                        case 'ccedil': ch = String.fromCharCode(0x00e7); break;
                        case 'egrave': ch = String.fromCharCode(0x00e8); break;
                        case 'eacute': ch = String.fromCharCode(0x00e9); break;
                        case 'ecirc': ch = String.fromCharCode(0x00ea); break;
                        case 'euml': ch = String.fromCharCode(0x00eb); break;
                        case 'igrave': ch = String.fromCharCode(0x00ec); break;
                        case 'iacute': ch = String.fromCharCode(0x00ed); break;
                        case 'icirc': ch = String.fromCharCode(0x00ee); break;
                        case 'iuml': ch = String.fromCharCode(0x00ef); break;
                        case 'eth': ch = String.fromCharCode(0x00f0); break;
                        case 'ntilde': ch = String.fromCharCode(0x00f1); break;
                        case 'ograve': ch = String.fromCharCode(0x00f2); break;
                        case 'oacute': ch = String.fromCharCode(0x00f3); break;
                        case 'ocirc': ch = String.fromCharCode(0x00f4); break;
                        case 'otilde': ch = String.fromCharCode(0x00f5); break;
                        case 'ouml': ch = String.fromCharCode(0x00f6); break;
                        case 'divide': ch = String.fromCharCode(0x00f7); break;
                        case 'oslash': ch = String.fromCharCode(0x00f8); break;
                        case 'ugrave': ch = String.fromCharCode(0x00f9); break;
                        case 'uacute': ch = String.fromCharCode(0x00fa); break;
                        case 'ucirc': ch = String.fromCharCode(0x00fb); break;
                        case 'uuml': ch = String.fromCharCode(0x00fc); break;
                        case 'yacute': ch = String.fromCharCode(0x00fd); break;
                        case 'thorn': ch = String.fromCharCode(0x00fe); break;
                        case 'yuml': ch = String.fromCharCode(0x00ff); break;
                        case 'OElig': ch = String.fromCharCode(0x0152); break;
                        case 'oelig': ch = String.fromCharCode(0x0153); break;
                        case 'Scaron': ch = String.fromCharCode(0x0160); break;
                        case 'scaron': ch = String.fromCharCode(0x0161); break;
                        case 'Yuml': ch = String.fromCharCode(0x0178); break;
                        case 'fnof': ch = String.fromCharCode(0x0192); break;
                        case 'circ': ch = String.fromCharCode(0x02c6); break;
                        case 'tilde': ch = String.fromCharCode(0x02dc); break;
                        case 'Alpha': ch = String.fromCharCode(0x0391); break;
                        case 'Beta': ch = String.fromCharCode(0x0392); break;
                        case 'Gamma': ch = String.fromCharCode(0x0393); break;
                        case 'Delta': ch = String.fromCharCode(0x0394); break;
                        case 'Epsilon': ch = String.fromCharCode(0x0395); break;
                        case 'Zeta': ch = String.fromCharCode(0x0396); break;
                        case 'Eta': ch = String.fromCharCode(0x0397); break;
                        case 'Theta': ch = String.fromCharCode(0x0398); break;
                        case 'Iota': ch = String.fromCharCode(0x0399); break;
                        case 'Kappa': ch = String.fromCharCode(0x039a); break;
                        case 'Lambda': ch = String.fromCharCode(0x039b); break;
                        case 'Mu': ch = String.fromCharCode(0x039c); break;
                        case 'Nu': ch = String.fromCharCode(0x039d); break;
                        case 'Xi': ch = String.fromCharCode(0x039e); break;
                        case 'Omicron': ch = String.fromCharCode(0x039f); break;
                        case 'Pi': ch = String.fromCharCode(0x03a0); break;
                        case 'Rho': ch = String.fromCharCode(0x03a1); break;
                        case 'Sigma': ch = String.fromCharCode(0x03a3); break;
                        case 'Tau': ch = String.fromCharCode(0x03a4); break;
                        case 'Upsilon': ch = String.fromCharCode(0x03a5); break;
                        case 'Phi': ch = String.fromCharCode(0x03a6); break;
                        case 'Chi': ch = String.fromCharCode(0x03a7); break;
                        case 'Psi': ch = String.fromCharCode(0x03a8); break;
                        case 'Omega': ch = String.fromCharCode(0x03a9); break;
                        case 'alpha': ch = String.fromCharCode(0x03b1); break;
                        case 'beta': ch = String.fromCharCode(0x03b2); break;
                        case 'gamma': ch = String.fromCharCode(0x03b3); break;
                        case 'delta': ch = String.fromCharCode(0x03b4); break;
                        case 'epsilon': ch = String.fromCharCode(0x03b5); break;
                        case 'zeta': ch = String.fromCharCode(0x03b6); break;
                        case 'eta': ch = String.fromCharCode(0x03b7); break;
                        case 'theta': ch = String.fromCharCode(0x03b8); break;
                        case 'iota': ch = String.fromCharCode(0x03b9); break;
                        case 'kappa': ch = String.fromCharCode(0x03ba); break;
                        case 'lambda': ch = String.fromCharCode(0x03bb); break;
                        case 'mu': ch = String.fromCharCode(0x03bc); break;
                        case 'nu': ch = String.fromCharCode(0x03bd); break;
                        case 'xi': ch = String.fromCharCode(0x03be); break;
                        case 'omicron': ch = String.fromCharCode(0x03bf); break;
                        case 'pi': ch = String.fromCharCode(0x03c0); break;
                        case 'rho': ch = String.fromCharCode(0x03c1); break;
                        case 'sigmaf': ch = String.fromCharCode(0x03c2); break;
                        case 'sigma': ch = String.fromCharCode(0x03c3); break;
                        case 'tau': ch = String.fromCharCode(0x03c4); break;
                        case 'upsilon': ch = String.fromCharCode(0x03c5); break;
                        case 'phi': ch = String.fromCharCode(0x03c6); break;
                        case 'chi': ch = String.fromCharCode(0x03c7); break;
                        case 'psi': ch = String.fromCharCode(0x03c8); break;
                        case 'omega': ch = String.fromCharCode(0x03c9); break;
                        case 'thetasym': ch = String.fromCharCode(0x03d1); break;
                        case 'upsih': ch = String.fromCharCode(0x03d2); break;
                        case 'piv': ch = String.fromCharCode(0x03d6); break;
                        case 'ensp': ch = String.fromCharCode(0x2002); break;
                        case 'emsp': ch = String.fromCharCode(0x2003); break;
                        case 'thinsp': ch = String.fromCharCode(0x2009); break;
                        case 'zwnj': ch = String.fromCharCode(0x200c); break;
                        case 'zwj': ch = String.fromCharCode(0x200d); break;
                        case 'lrm': ch = String.fromCharCode(0x200e); break;
                        case 'rlm': ch = String.fromCharCode(0x200f); break;
                        case 'ndash': ch = String.fromCharCode(0x2013); break;
                        case 'mdash': ch = String.fromCharCode(0x2014); break;
                        case 'lsquo': ch = String.fromCharCode(0x2018); break;
                        case 'rsquo': ch = String.fromCharCode(0x2019); break;
                        case 'sbquo': ch = String.fromCharCode(0x201a); break;
                        case 'ldquo': ch = String.fromCharCode(0x201c); break;
                        case 'rdquo': ch = String.fromCharCode(0x201d); break;
                        case 'bdquo': ch = String.fromCharCode(0x201e); break;
                        case 'dagger': ch = String.fromCharCode(0x2020); break;
                        case 'Dagger': ch = String.fromCharCode(0x2021); break;
                        case 'bull': ch = String.fromCharCode(0x2022); break;
                        case 'hellip': ch = String.fromCharCode(0x2026); break;
                        case 'permil': ch = String.fromCharCode(0x2030); break;
                        case 'prime': ch = String.fromCharCode(0x2032); break;
                        case 'Prime': ch = String.fromCharCode(0x2033); break;
                        case 'lsaquo': ch = String.fromCharCode(0x2039); break;
                        case 'rsaquo': ch = String.fromCharCode(0x203a); break;
                        case 'oline': ch = String.fromCharCode(0x203e); break;
                        case 'frasl': ch = String.fromCharCode(0x2044); break;
                        case 'euro': ch = String.fromCharCode(0x20ac); break;
                        case 'image': ch = String.fromCharCode(0x2111); break;
                        case 'weierp': ch = String.fromCharCode(0x2118); break;
                        case 'real': ch = String.fromCharCode(0x211c); break;
                        case 'trade': ch = String.fromCharCode(0x2122); break;
                        case 'alefsym': ch = String.fromCharCode(0x2135); break;
                        case 'larr': ch = String.fromCharCode(0x2190); break;
                        case 'uarr': ch = String.fromCharCode(0x2191); break;
                        case 'rarr': ch = String.fromCharCode(0x2192); break;
                        case 'darr': ch = String.fromCharCode(0x2193); break;
                        case 'harr': ch = String.fromCharCode(0x2194); break;
                        case 'crarr': ch = String.fromCharCode(0x21b5); break;
                        case 'lArr': ch = String.fromCharCode(0x21d0); break;
                        case 'uArr': ch = String.fromCharCode(0x21d1); break;
                        case 'rArr': ch = String.fromCharCode(0x21d2); break;
                        case 'dArr': ch = String.fromCharCode(0x21d3); break;
                        case 'hArr': ch = String.fromCharCode(0x21d4); break;
                        case 'forall': ch = String.fromCharCode(0x2200); break;
                        case 'part': ch = String.fromCharCode(0x2202); break;
                        case 'exist': ch = String.fromCharCode(0x2203); break;
                        case 'empty': ch = String.fromCharCode(0x2205); break;
                        case 'nabla': ch = String.fromCharCode(0x2207); break;
                        case 'isin': ch = String.fromCharCode(0x2208); break;
                        case 'notin': ch = String.fromCharCode(0x2209); break;
                        case 'ni': ch = String.fromCharCode(0x220b); break;
                        case 'prod': ch = String.fromCharCode(0x220f); break;
                        case 'sum': ch = String.fromCharCode(0x2211); break;
                        case 'minus': ch = String.fromCharCode(0x2212); break;
                        case 'lowast': ch = String.fromCharCode(0x2217); break;
                        case 'radic': ch = String.fromCharCode(0x221a); break;
                        case 'prop': ch = String.fromCharCode(0x221d); break;
                        case 'infin': ch = String.fromCharCode(0x221e); break;
                        case 'ang': ch = String.fromCharCode(0x2220); break;
                        case 'and': ch = String.fromCharCode(0x2227); break;
                        case 'or': ch = String.fromCharCode(0x2228); break;
                        case 'cap': ch = String.fromCharCode(0x2229); break;
                        case 'cup': ch = String.fromCharCode(0x222a); break;
                        case 'int': ch = String.fromCharCode(0x222b); break;
                        case 'there4': ch = String.fromCharCode(0x2234); break;
                        case 'sim': ch = String.fromCharCode(0x223c); break;
                        case 'cong': ch = String.fromCharCode(0x2245); break;
                        case 'asymp': ch = String.fromCharCode(0x2248); break;
                        case 'ne': ch = String.fromCharCode(0x2260); break;
                        case 'equiv': ch = String.fromCharCode(0x2261); break;
                        case 'le': ch = String.fromCharCode(0x2264); break;
                        case 'ge': ch = String.fromCharCode(0x2265); break;
                        case 'sub': ch = String.fromCharCode(0x2282); break;
                        case 'sup': ch = String.fromCharCode(0x2283); break;
                        case 'nsub': ch = String.fromCharCode(0x2284); break;
                        case 'sube': ch = String.fromCharCode(0x2286); break;
                        case 'supe': ch = String.fromCharCode(0x2287); break;
                        case 'oplus': ch = String.fromCharCode(0x2295); break;
                        case 'otimes': ch = String.fromCharCode(0x2297); break;
                        case 'perp': ch = String.fromCharCode(0x22a5); break;
                        case 'sdot': ch = String.fromCharCode(0x22c5); break;
                        case 'lceil': ch = String.fromCharCode(0x2308); break;
                        case 'rceil': ch = String.fromCharCode(0x2309); break;
                        case 'lfloor': ch = String.fromCharCode(0x230a); break;
                        case 'rfloor': ch = String.fromCharCode(0x230b); break;
                        case 'lang': ch = String.fromCharCode(0x2329); break;
                        case 'rang': ch = String.fromCharCode(0x232a); break;
                        case 'loz': ch = String.fromCharCode(0x25ca); break;
                        case 'spades': ch = String.fromCharCode(0x2660); break;
                        case 'clubs': ch = String.fromCharCode(0x2663); break;
                        case 'hearts': ch = String.fromCharCode(0x2665); break;
                        case 'diams': ch = String.fromCharCode(0x2666); break;
                        default: notVlaid = true; break;
                    }
                }
                if (notVlaid)
                    i = i + 1;
                else
                    i = semicolonIndex;
            }
        }
        out += ch;
    }
    return out;
}
function restoreFormDataReTake(resDemoData) {
    formDataRestore = resDemoData.split('|');
    for (var ix = 0; ix < getFormElements().length; ix++) {
        aSrc = getElement(ix);
        if (aSrc.name) {
            if (aSrc.name.toLowerCase().indexOf('ext_') > -1) {
                for (var iy = 0; iy < formDataRestore.length; iy++) {
                    if (formDataRestore[iy].toLowerCase().indexOf(aSrc.name.toLowerCase() + ":") > -1) {
                        dataElem = formDataRestore[iy].split(':');
                        switch (aSrc.type.toLowerCase()) {
                            case "text":
                                try { aSrc.value = dataElem[1]; } catch (e) { }
                                break;
                            case "checkbox":
                                try { aSrc.checked = true; } catch (e) { }
                                break;
                            case "select-one":
                                try { setDropDown(aSrc, dataElem[1]); } catch (e) { }
                                break;
                            case "radio":
                                try { aSrc.checked = true; } catch (e) { }
                                break;
                        }
                    }
                }
            }
        }
    }
}
function trg_HideShow() {
    for (var ix = 0; ix < getFormElements().length; ix++) {
        aSrc = getElement(ix);
        switch (aSrc.type) {
            case "checkbox":
            case "radio":
                var chg = '';
                if (aSrc.onclick) {
                    if (aSrc.checked) {
                        try {
                            aSrc.click();
                            aSrc.click();
                        }
                        catch (e) { }
                    }
                }
                break;
            case "select-one":
                var chg = '';
                if (aSrc.onchange) {
                    if (!checkHidden2(aSrc)) {
                        try {
                            aSrc.onchange();
                        }
                        catch (e) { }
                    }
                }
                break;
            default:
                break;
        }
    }
}
function saveRankSort(SortList, SortField) {
    getElement(SortField).value = $("#" + SortList).sortable('toArray').join('|');
    updRankSortId(SortList)
}
function updRankSortId(SortList) {
    lineNo = 0;
    $("#" + SortList + " li").each(function(index) {
        if ($(this).find(".spRankn").length > 0) {
            $(this).find(".spRankn").html("");
            lineNo = lineNo + 1;
            $(this).find('.spRankn').html(lineNo + ".&nbsp;");
        }
    });
}
function blankRankSortId(SortList) {
    $("#" + SortList + " li").each(function(index) {
        if ($(this).find(".spRankn").length > 0) {
            $(this).find(".spRankn").html("");
        }
    });
}
var saveFilterAnsValue = new Array(5000)
var saveFilterAnsText = new Array(5000)
var saveFilterCount = 0;
//
function filterClick(aObj, ansId, filterQ) {
    dropDownQuest = false;
    //if dropdown filtering works differently
    trgObj = getElement('DropDown_' + filterQ);
    if (trgObj != null) {

        if (trgObj.type == "select-one")
            dropDownQuest = true;
    }
    if (dropDownQuest) {
        if (aObj.checked) {
            for (x = 0; x < saveFilterCount; x++) {
                if (saveFilterAnsValue[x] == ansId + ':0') {
                    oNewOption = new Option();
                    oNewOption.text = saveFilterAnsText[x];
                    oNewOption.value = saveFilterAnsValue[x];
                    trgObj.options.add(oNewOption);
                    break;
                }
            }
        }
        else {
            for (i = trgObj.options.length - 1; i >= 0; i--) {
                if (trgObj[i].value == ansId + ':0')
                    trgObj.remove(i);
            }
        }
    }
    else {
        if (aObj) {
            if (aObj.checked)
                getElement('ARow' + ansId).style.display = '';
            else {
                getElement('ARow' + ansId).style.display = 'none';
                initHiddenElements(getElement('ARow' + ansId)); //uncheck radio and check boxes if row hidden
            }
        }
    }
}
function filterClickSubscriber(ansId, filterQ, aObj) {
    if (!aObj) //element which raised the click will be passed in othwewise it will be passed in firefox etc
        aObj = event.srcElement;
    dropDownQuest = false;
    //if dropdown filtering works differently
    trgObj = getElement('DropDown_' + filterQ);
    if (trgObj != null) {

        if (trgObj.type == "select-one")
            dropDownQuest = true;
    }
    if (dropDownQuest) {
        if (aObj.checked) {
            for (x = 0; x < saveFilterCount; x++) {
                if (saveFilterAnsValue[x] == ansId + ':0') {
                    oNewOption = new Option();
                    oNewOption.text = saveFilterAnsText[x];
                    oNewOption.value = saveFilterAnsValue[x];
                    trgObj.options.add(oNewOption);
                    break;
                }
            }
        }
        else {
            for (i = trgObj.options.length - 1; i >= 0; i--) {
                if (trgObj[i].value == ansId + ':0')
                    trgObj.remove(i);
            }
        }
    }
    else {
        if (aObj.checked)
            getElement('ARow' + ansId).style.display = '';
        else {
            getElement('ARow' + ansId).style.display = 'none';
            initHiddenElements(getElement('ARow' + ansId)); //uncheck radio and check boxes if row hidden
        }
    }
}
function initFilterClick(ansId, filterQ) {
    trgObj = getElement('DropDown_' + filterQ);
    if (trgObj != null) {
        if (trgObj.type == "select-one") {

            for (i = 0; i < trgObj.options.length; i++) {
                if (Trim1(trgObj[i].text).length > 0) {
                    saveFilterAnsValue[saveFilterCount] = trgObj[i].value;
                    saveFilterAnsText[saveFilterCount] = trgObj[i].text;
                    saveFilterCount++;
                    trgObj.remove(i);
                }
            }
        }
        else
            try { getElement('ARow' + ansId).style.display = 'none'; } catch (e) { }
    }
    else
        try { getElement('ARow' + ansId).style.display = 'none'; } catch (e) { }

}
//used to restore page elements when page re-loaded
function restorePageElements(aSrc, Value, Name) {
    if (aSrc.length > 0)
        type = aSrc[0].type;
    else
        type = aSrc.type;
    if (type != null) {
        switch (type.toLowerCase()) {
            case 'radio':
                setRadio(Name, Value);
                break;
            case 'checkbox':
                aSrc.checked = true;
                break;
            default:
                aSrc.value = Value;
                break;
        }
    }
    else
        aSrc.value = Value;
}
//
// Start Survey page object
//
var Utils = {
    caculateAgeFromYear: function(date) {
        year = 0;
        if (date.length >= 4) {
            var d = new Date();
            year = parseInt(date.substring(0, 4));
            year = d.getFullYear() - year;
        }
        return year;
    },
    attachEvent: function(target, eventName, handlerName) {

        switch (eventName) {
            case 'onblur':
                target.onblur = handlerName;
                break;
            case 'onclick':
                target.onclick = handlerName;
                break;
            case 'onchange':
                target.onchange = handlerName;
                break;
            case 'onkeyup':
                target.onkeyup = handlerName;
                break;
            default:
                break;
        }
    },
    calculateAgeFromYear: function(date) {
        year = 0;
        if (date.length >= 4) {
            var d = new Date();
            year = parseInt(date.substring(0, 4));
            year = d.getFullYear() - year;
        }
        return year;
    },
    validateWithRegex: function(aFiledName, regExpression, msg) {
        aObj = Survey.fieldValue(aFiledName);
        var Regx = new RegExp(regExpression);
        if (!Regx.test(aObj.value)) {
            if (msg.length > 0)
                PageError.add(aFiledName, msg);
            return false;
        }
        else
            return true;
    },
    openWindow: function(aPage,aPageID,iWidth,iHeight) {
	    var sWindowInfo="";
	    sWindowInfo = "resizable=yes,width=" + iWidth + ",height=" + iHeight + ",top=" + (window.screenTop + 10) + ",left=" + (window.screenLeft + 10) + ",toolbar=no, status=yes, scrollbars=yes"
        var aWin = window.open(aPage, aPageID, sWindowInfo);
	    if(aWin.focus)
    	    aWin.focus();
	return aWin;
    },
    setRadioClick: function(aName, aValue) {
        if (getElement(aName)) {
            var ix = 0;
            var found = false
            if (getElement(aName).length) {
                while (ix < getElement(aName).length && !found) {
                    if (getElement(aName)[ix].value.indexOf(aValue) > -1) {
                        getElement(aName)[ix].checked = true;
                        try { getElement(aName)[ix].onClick(); }
                        catch (e) { if (advancedLogicDebug) alert('setRadioClick failed: ' + e.message) }
                        found = true;
                    }
                    ix++;
                }
            }
            else {
                if (getElement(aName).value.indexOf(aValue) > -1) {
                    getElement(aName).checked = true;
                    try { getElement(aName).onClick(); }
                    catch (e) { if (advancedLogicDebug) alert('setRadioClick failed: ' + e.message) }
                }
            }
        }
    }
}
var Question = {
    getAnswerClickTotal: function(QuestionSeq) {
        values = QuestionSeq.split('.');
        if (values.length == 4)
            xx = eval(values[0] + ".a" + values[1] + "_e" + values[2] + "_" + values[3]);
        if (values.length == 3)
            xx = eval(values[0] + ".a" + values[1] + "_e" + values[2]);
        if (values.length == 2)
            xx = eval(values[0] + ".a" + values[1]);
        if (values.length == 1)
            xx = eval(values[0]);
        //
        try { yy = parseInt(xx); 
              if (isNaN(xx))
                 yy=0;  
        }
        catch (e) { 
            yy = 0; 
        }
        return yy;
    }
}
var Survey = {
    setPipeText: function(placeHolder, value) {
        try { setPlaceHolder(placeHolder, unescape(value)); setPipedText(placeHolder); }
        catch (e) { };
    },
    fieldValue: function(elementName) {
        var elem;
        if (navigator.appName == 'Microsoft Internet Explorer')
            elem = document.all(elementName);
        else {
            if (navigator.appName == 'Opera')
                elem = document.forms[0].elements[elementName];
            else {
                elem = document.getElementById(elementName);
                if (elem == null) // get element by index number
                    elem = document.forms[0].elements[elementName];
            }
        }
        return elem;
    },
    selectAnswer: function(QType, Question, AnsId, AnsSeq, AnsMax) {
        switch (QType) {
            case 0: // QuestionType.Radio
                Utils.setRadioClick('Radio_' + Question, AnsId);
                break;
            case 20: // QuestionType.Checkbox
                getElement('Check_' + AnsId).checked = true;
                try { getElement('Check_' + AnsId).onClick(); }
                catch (e) { if (advancedLogicDebug) alert('SelectAnswer checkbox failed: ' + e.message) }
                break;
        }
    },
    checkAnswer: function(QType, Question, AnsId, AnsSeq, AnsMax) {
        switch (QType) {
            case 0: // QuestionType.Radio
                return getElement('Radio_' + Question)[AnsSeq].checked;
                break;
            case 20: // QuestionType.Checkbox
                return getElement('Check_' + AnsId).checked;
                break;
            case 50: // QuestionType.LikertText
            case 170: // QuestionType.LikertTextScale
                if (AnsMax == -1) //check if any item on the line selected
                {
                    for (ix = 0; ix < getElement('RadioL_' + AnsId).length; ix++) {
                        if (getElement('RadioL_' + AnsId)[ix].checked)
                            return true;
                    }
                    return false;
                }
                else
                    return getElement('RadioL_' + AnsId)[AnsMax].checked;
                break;
            case 90: // Rank
                return Survey.fieldValueNumeric('RankQ_' + AnsId);
            case 40: // drop down
                aSrc = getElement('DropDown_' + Question);
                return aSrc.options[aSrc.selectedIndex].text;
                break;
        }
    },
    setPhantomAnswer: function(QType, Question, AnsId, AnsSeq, AnsMax) {
        switch (QType) {
            case 0: // QuestionType.Radio
                getElement('__QueueData').value += '|radio_' + AnsId + ':0:0:Radio_' + Question;
                break;
            case 20: // QuestionType.CheckBox |Check_8ac3807a-fc6c-4d2c-a63e-2fc6b9b6c9f7:0|Check_6945aec4-71e2-45e9-91b6-b21290fd5304:0
                getElement('__QueueData').value += '|Check_' + AnsId + ':0';
                break;
        }
    },
    removePhantomAnswer: function(QType, Question, AnsId, AnsSeq, AnsMax) {
        switch (QType) {
            case 0: // QuestionType.Radio
                getElement('__QueueData').value = getElement('__QueueData').value.replace('|radio_' + AnsId + ':0:0:Radio_' + Question, '');
                break;
            case 20: // QuestionType.CheckBox |Check_8ac3807a-fc6c-4d2c-a63e-2fc6b9b6c9f7:0|Check_6945aec4-71e2-45e9-91b6-b21290fd5304:0
                getElement('__QueueData').value = getElement('__QueueData').value.replace('|Check_' + AnsId + ':0', '');
                break;
        }
    },
    // validate allocation question
    fieldValueNumeric: function(elementName) {
        var val = 0;
        try {
            val1 = Survey.formatInteger(getElement(elementName));
            val = parseInt(val1);
        }
        catch (e) {
            val = 0;
        }
        //initialize to 0 
        if (isNaN(val))
            val = 0;
        return val;
    },
    formatInteger: function(aVal1) {
        var aVal = aVal1.value.toString().replace(groupSep, '').replace(decSep, '');
        aVal1.value = aVal;
        return aVal;
    },
    getQueryStringValue: function(name) {
        var qs = new Querystring();
        return qs.get(name, '');
    },
    createCookie: function(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=/";
    },
    readCookie: function(cookieName) {
        var theCookie = "" + document.cookie;
        var ind = theCookie.indexOf(cookieName);
        if (ind == -1 || cookieName == "") return "";
        var ind1 = theCookie.indexOf(';', ind);
        if (ind1 == -1) ind1 = theCookie.length;
        return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
    },
    generateRandonNumberList: function(max, listLength) {
        var list = new Array(listLength);
        var iy = 0;
        for (var ix = 0; ix < list.length; ix++)
            list[ix] = -1;
        //debug = '';
        //
        while (iy < listLength) {
            var rand_no = Math.floor(max * Math.random())
            for (var ix = 0; ix < list.length; ix++) {
                if (list[ix] == rand_no)
                    break;
                if (list[ix] == -1) {
                    list[ix] = rand_no;
                    iy++;
                    //debug = debug + rand_no + ' ';
                    break;
                }
            }
        }
        return list;
    },
    randomHideAnswerLines: function(numAnsToHide, ansList) {
        maxNumber = ansList.length
        var list = Survey.generateRandonNumberList(maxNumber, numAnsToHide)
        for (var ix = 0; ix < list.length; ix++) {
            Survey.hideAnswerLines(ansList[list[ix]]);
        }
        return list;
    },
    randomHideAnswerLinesOddEvenColor: function(numAnsToHide, ansList, evenColor, oddColor) {
        rList = Survey.randomHideAnswerLines(numAnsToHide, ansList);
        //set odd even color
        odd = true;
        for (var ix = 0; ix < ansList.length; ix++) {
            try {
                curElement = getElement('ARow' + ansList[ix]);
                if (curElement.style.display != 'none') {
                    if (odd) {
                        if (oddColor.length > 0)
                            curElement.style.backgroundColor = oddColor;
                        odd = false;
                    }
                    else {
                        if (evenColor.length > 0)
                            curElement.style.backgroundColor = evenColor;
                        odd = true;
                    }
                }
            } catch (e) { }

        }

    },
    randomizeArray: function(arrayList) {
        var retList = new Array(arrayList.length);
        maxNumber = arrayList.length
        var list = Survey.generateRandonNumberList(maxNumber, arrayList.length)
        for (var ix = 0; ix < list.length; ix++) {
            retList[ix] = arrayList[list[ix]];
        }

        return retList;
    },
    setNextPageFromArrayList: function(pageListArray, defaultNextPage) {
        remainingPages = '';
        if (pageListArray.length >= 1) {

            if (pageListArray[0].length > 0) {
                Survey.setNextPage(pageListArray[0]);
                for (var ix = 1; ix < pageListArray.length; ix++) {
                    if (ix + 1 < pageListArray.length)
                        remainingPages += pageListArray[ix] + ',';
                    else
                        remainingPages += pageListArray[ix];
                }
            }
            else
                Survey.setNextPage(defaultNextPage);
        }
        else
            Survey.setNextPage(defaultNextPage);
        return remainingPages;
    },
    addToFavorites: function() {
        try {
            if (window.sidebar) { // Mozilla Firefox Bookmark
                window.sidebar.addPanel(document.title, location.href, "");
            }
            else {
                if (window.external) { // IE Favorite
                    window.external.AddFavorite(location.href, document.title);
                }
                else
                    alert('To save this survey so you can finish later just bookmark the page.');
            }
        }
        catch (e) { alert('To save this survey so you can finish later just bookmark the page.'); }
    },
    resumeSurvey: function() {
        url = document.location.toString().substring(0, document.location.toString().lastIndexOf('/')) +
            '/SR.aspx?SurveyId=' + getElement('__SurveyId').value + '&PageId=' +
            getElement('__PageId').value + '&Ox=' + getElement('__Ox').value + '&EM=' +
            getElement('__em').value + '&InstanceId=' + getElement('__InstanceId').value
        mail_str = "mailto:?subject=Saved Survey Link.";
        mail_str += "&body=You have saved a survey in progress. ";
        mail_str += "You can resume by clicking the following link: " + escape(url);
        location.href = mail_str;
    },
    expired: function() {
        document.location = Survey.fieldValue('__ExpUrl').value;
    },
    hideSurveyLines: function(lineList) {
        lines = lineList.split(',');
        for (var ix = 0; ix < lines.length; ix++) {
            try { getElement('M_DetailsLine' + lines[ix]).style.display = 'none'; } catch (e) { }
        }
    },
    hideAnswerLines: function(lineList) {
        lines = lineList.split(',');
        for (var ix = 0; ix < lines.length; ix++) {
            try { getElement('ARow' + lines[ix]).style.display = 'none'; } catch (e) { }
        }
    },
    showAnswerLines: function(lineList) {
        lines = lineList.split(',');
        for (var ix = 0; ix < lines.length; ix++) {
            try { getElement('ARow' + lines[ix]).style.display = ''; } catch (e) { }
        }
    },
    showSurveyLines: function(lineList) {
        lines = lineList.split(',');
        for (var ix = 0; ix < lines.length; ix++) {
            try { getElement('M_DetailsLine' + lines[ix]).style.display = ''; } catch (e) { }
        }
    },
    setLanguageCode: function(LanCode) {
        Survey.fieldValue('__MultiLan').value = LanCode;
    },
    setNextPage: function(page) {
        getElement('__Next').value = page;
        getElement('__Status').value = '0';
    },
    setNextPageUrl: function(page, url) {
        getElement('__Next').value = page;
        getElement('__Status').value = '0';
    },
    setFinishPage: function(page) {
        getElement('__Next').value = '';
        getElement('__LastPageId').value = page;
        getElement('__Status').value = '10';
    },
    //set multi select checkbox type
    addRemoveQuestionState: function(aobj, stateValue) {

        if (!pageLoading) {
            stateValue = 'Q' + stateValue;
            var state = getElement('__QState').value;
            state = state.replace(stateValue + '|', '')
            if (aobj.checked)
                state += stateValue + "|";
            getElement('__QState').value = state;
        }
    },
    //set single select radio/drop down
    addRemoveQuestionStateSingle: function(aobj, stateValue) {
        if (!pageLoading) {
            stateValue = 'Q' + stateValue;
            if (aobj) { //if null being called from code advanced logic no object availiable
                if (aobj.type == "select-one")
                    stateValue = stateValue + '.' + aobj.selectedIndex
            }
            statePart = stateValue.split('.');
            var removeQuestion = statePart[0] + '.';
            var clearEnteriesUpTo = statePart[0] + '.';

            if (statePart.length > 1)
                clearEnteriesUpTo = statePart[0] + '.' + statePart[1] + '.';
            if (statePart.length > 2)
                removeQuestion = statePart[0] + '.' + statePart[1] + '.';
            //rebuild state removing all entries for this question
            var statevalues = getElement('__QState').value.split('|');
            var state = '';
            //remove all question entries form the state bag
            for (var ix = 0; ix < statevalues.length; ix++) {

                if (statevalues[ix].indexOf(removeQuestion) > -1 && statevalues[ix].length > 0)
                    statevalues[ix] = '';
            }
            //Add to state bag
            for (var ix = 0; ix < statevalues.length; ix++) {

                if (statevalues[ix].indexOf(clearEnteriesUpTo) == -1 && statevalues[ix].length > 0)
                    state += statevalues[ix] + '|';
            }
            getElement('__QState').value = state + stateValue + '|';
        }
    },

    checkAnswerInStateBag: function(value) {
        if (getElement('__QState').value.indexOf(value + '|') > -1)
            return true;
        else
            return false;
    }
}
//
// End Survey page object
//
var PageButtons = {
    checkDoubleSubmit: function() {
        if (ctlSubmitCount > 0) {
            ctlSubmitCount++;
           
            return true;
        }
        else {
            ctlSubmitCount++;
            
            return false;
        }
    },
    disableAll: function() {
        alreadySubmitted = false;
        for (var ix = 0; ix < ctlButtons.length; ix++) {
            if (getElement(ctlButtons[ix]).disabled)
                alreadySubmitted = true;
            getElement(ctlButtons[ix]).disabled = true;
        }
        return alreadySubmitted;
    },
    enableAll: function() {
        ctlSubmitCount = 0; //if buttons are being re-enabled the set click count back to 0
        for (var ix = 0; ix < ctlButtons.length; ix++) {
            getElement(ctlButtons[ix]).disabled = false;
        }
    }
}
//
// End Survey page object
//
var PageError = {
    add: function(name, msg) {
        aObj = getElement(name);
        aObj.value = '';
        if (cErrorsCount < cErrors.length) {
            if (aObj.id.length > 0)
                foundm = checkItem(aObj.id);
            else
                foundm = checkItem(aObj.name);
            if (!foundm) {
                cErrorsCount = cErrorsCount + 1;
                cErrors[cErrorsCount] = msg;
                if (aObj.id.length > 0)
                    cErrorsObj[cErrorsCount] = aObj.id;
                else
                    cErrorsObj[cErrorsCount] = aObj.name;
            }
        }
    },

    addQuestionError: function(qid, msg) {

        if (cErrorsCount < cErrors.length) {

            foundm = checkItem(qid);
            if (!foundm) {
                cErrorsCount = cErrorsCount + 1;
                cErrors[cErrorsCount] = msg;
                cErrorsObj[cErrorsCount] = qid;
                cErrorsType[cErrorsCount] = "Q";
            }
        }
    },
    checkItem: function(aid) {
        foundm = false;
        //remove error item from list
        for (ix = 0; ix < cErrors.length; ix++) {
            if (cErrorsObj[ix].length > 0) {
                if (cErrorsObj[ix] == aid)
                    foundm = true;
            }
        }
        return foundm;
    },
    removeErrorItem: function(id) {
        //remove error item from list
        for (ix = 0; ix < cErrors.length; ix++) {
            if (cErrorsObj[ix].length > 0) {
                if (cErrorsObj[ix] == id) {
                    cErrors[ix] = '';
                    cErrorsObj[ix] = '';
                }
            }
        }
    }
}
//
// Question click event validation
//
var QEvents = {
    //likert matrix question with none as the last element make sure it cannot be selected with any others
    exclusive: function(aid, headValue) {
        if (headValue) {
            if (headValue.length == 0)
                headValue = 'none';
        }
        else
            headValue = 'none';
        //last element is none which cannot be selected with another value
        ansRow = Survey.fieldValue('Checkl_' + aid)
        if (ansRow[ansRow.length - 1].checked) {
            for (ix = 0; ix < ansRow.length; ix++) {
                if (ix != ansRow.length - 1 && ansRow[ix].checked) {
                    alert(headValue + ' is exclusive and cannot be selected with another value ');
                    ansRow[ansRow.length - 1].checked = false;
                    break;
                }
            }
        }
    }
}
//
// End Page error object
//


