// GLOBALS
var uSNodeId;
var uSSiteId;
var uSUrsRegId;
var uSProductName;
var uSProductId;
var uSContainer;
var uSSurvey;
var sTit;
var sB;
var sI;
var uSQuestions;
var uSPercents;
var req;
var isIE = false;
var ACTION;
var GET_QUESTIONS = 0;
var GET_PERCENTS = 1;
var OTHER_TEXT = "Enter other ways you use this product";
var isUsageSurveyPainted = false;

function howDoYouUseYours(p, u, pId, n, s) {
    initUsageSurvey(p, u, pId, n, s);
    loadXMLDoc("/4113-" + n + "_" + s + "-0-1.html?action=getQuestions", GET_QUESTIONS);
}

function initUsageSurvey(p, u, pId, uNId, uSId) {
    uSQuestions = new Array();
    uSPercents = new Array();
    uSProductName = p;
    uSUrsRegId = u;
    uSProductId = pId;
    uSNodeId = uNId;
    uSSiteId = uSId;
    uSContainer = document.getElementById("uContainer");
    uSSurvey = document.getElementById("uSurvey");
    uSSurvey.innerHTML = "";
    sTit = document.getElementById("sTitle");
    sB = document.getElementById("sBlurb");
    sI = document.getElementById("sInstructions");

}

function uSSubmit() {
    var theForm = document.getElementById("productUsageSurveyForm");
    var els = theForm.getElementsByTagName("input");
    var out = "";
    for (var i = 0; i < els.length; i++) {
        if (els[i].type == "checkbox") {
            if (els[i].checked) {
                if (out == "") {
                    out = els[i].name + "=t";
                } else {
                    out = out + "&" + els[i].name + "=t";
                }
            }
        } else if (els[i].name == "otherItem") {
            if (els[i].value != OTHER_TEXT) {
                if (els[i].value != "") {
                    out = out + "&" + els[i].name + "=" + escape(els[i].value);
                }
            }
        } else {
            out = out + "&" + els[i].name + "=" + els[i].value;
        }
    }
    loadXMLDoc("/4113-" + uSNodeId + "_" + uSSiteId + "-0-2.html?" + out, GET_PERCENTS);
}

function sClose() {
    sToggle(uSContainer);
    sToggle(uSSurvey);
}


function sToggle(e) {
    if (e.style.display == "inline") {
        sHide(e);
    } else {
        sShow(e);
    }

}

function sShow(e) {
    e.style.display = "inline";
}

function sHide(e) {
    e.style.display = "none";
}

// XML functions
function loadXMLDoc(url, a) {
    ACTION = a;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
        // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }

}

function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // DO SOMETHING
            if (ACTION == GET_QUESTIONS) {
                loadQuestions(req.responseXML);
            }

            if (ACTION == GET_PERCENTS) {
                loadPercents(req.responseXML);
            }

        } else {
            alert("There was a problem retrieving the survey data:\n" + req.statusText);
        }
    }
}

// uhm.. lifted from the example at apple.com http://developer.apple.com/internet/webcontent/xmlhttpreq.html
// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        // the namespace versions of this method
        // (getElementsByTagNameNS()) operate
        // differently in Safari and Mozilla, but both
        // return value with just local name, provided
        // there aren't conflicts with non-namespace element
        // names
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
            return result.firstChild.nodeValue;
        }
    } else {
        return "n/a";
    }
}



function loadQuestions(xml) {
    var items = xml.getElementsByTagName("item");
    for (var i = 0; i < items.length; i++) {
        uSQuestions[uSQuestions.length] = { "usageItemId" : getElementTextNS("", "usageItemId", items[i], 0),
            "categoryId" : getElementTextNS("", "categoryId", items[i], 0),
            "name" : getElementTextNS("", "name", items[i], 0)
        };
    }
    paintSurvey();
}

function loadPercents(xml) {
    var items = xml.getElementsByTagName("item");
    for (var i = 0; i < items.length; i++) {
        uSPercents[uSPercents.length] = { "usageItemId" : getElementTextNS("", "usageItemId", items[i], 0),
            "sessionId" : getElementTextNS("", "sessionId", items[i], 0),
            "name" : getElementTextNS("", "name", items[i], 0),
            "count" : getElementTextNS("", "count", items[i], 0),
            "percentage" : getElementTextNS("", "percentage", items[i], 0)
        };
    }
    paintResponse();
}

function paintSurvey() {
    sTit.innerHTML = "How do you use this product? <br />" + uSProductName;

    var orSaying = "";
    var suBlob = "";
    var suInst = "";
    if (uSQuestions.length > 0) {
        suBlob = "Share the most common ways you use this product, and see how your vote compares with the rest of the CNET Community.";
        suInst = "Select all options below that may apply:";
        orSaying = "or&nbsp;";
    } else {
        suBlob = "Share the most common ways you use this product: "
               + "Please place a comma between each use.<p /><b>Example: </b> When I'm commuting, to save time at work, to keep in touch with family.";
        suInst = "";
        OTHER_TEXT = "Enter the ways you use this product";
    }
    sB.innerHTML = suBlob;
    sI.innerHTML = suInst;

    sI.style.marginTop = "10px";

    var f = document.createElement("form");
    f.style.marginTop = "0px";
    f.style.paddingTop = "0px";
    f.id = "productUsageSurveyForm";
    for (var i = 0; i < uSQuestions.length; i ++) {
        var e = document.createElement("div");
        e.appendChild(makeInputCheckBoxSpan("item_" + uSQuestions[i].usageItemId));
        e.appendChild(makeSpan(uSQuestions[i].name));
        f.appendChild(e);
    }

    var ue = document.createElement("input");
    ue.type = "hidden";
    ue.name = "ursRegId";
    ue.value = uSUrsRegId;
    f.appendChild(ue);

    var pi = document.createElement("input");
    pi.type = "hidden";
    pi.name = "productId";
    pi.value = uSProductId;
    f.appendChild(pi);

    var o = document.createElement("div");
    o.innerHTML = orSaying;
    o.className = "uOtherDiv";
    oI = document.createElement("input");
    oI.name = "otherItem";
    oI.type = "text";
    oI.value = OTHER_TEXT;
    oI.onfocus = function() {
        this.value = "";
    };
    oI.size = "40";
    o.appendChild(oI);
    f.appendChild(o);

    var sub = makeSubmitButton("<a href=\"javascript:uSSubmit();\"><img border=\"0\" src=\"http://i.i.com.com/cnwk.1d/i/uo/usage_btn_submit.gif\" /></a>");
    f.appendChild(sub);
    f.onsubmit = function (){
        uSSubmit();
        return false;
    }

    uSSurvey.appendChild(f);

    sToggle(uSContainer);
    sToggle(uSSurvey);

    isUsageSurveyPainted = true;
}

function paintResponse() {
    sTit.innerHTML = "Thank you for participating!";
    sB.innerHTML = "";
    sI.style.marginTop = "10px";


    uSSurvey.innerHTML = "";

    if((uSPercents.length == 1) && (uSPercents[0].name == "Other")){
        sI.innerHTML = "";
    }
    else
    {
        sI.innerHTML = "Instant Poll Results";
        var uSPTab = document.createElement("table");
        uSPTab.id = "uSPercentTable";
        for (var i = 0; i < uSPercents.length; i++) {
            var r = uSPTab.insertRow(uSPTab.rows.length);

            var n = r.insertCell(r.cells.length);
            n.className = "percentCDiv";
            n.innerHTML = (i + 1) + ": ";

            var q = r.insertCell(r.cells.length);
            q.className = "percentNDiv";
            q.width = "100%";
            q.innerHTML = uSPercents[i].name;

            var p = r.insertCell(r.cells.length);
            p.className = "percentUDiv";
            p.innerHTML = uSPercents[i].percentage + "%";
        }
        uSSurvey.appendChild(uSPTab);
    }


    var h = document.createElement("hr");
    h.size = "1";
    h.style.paddingBottom = "10px";
    uSSurvey.appendChild(h);

    // now, just grab the first element, see if we have a sessionId in there, and if so, create the login link...
    var firstPercentRes = uSPercents[0];
    var sessionId = firstPercentRes.sessionId;
    if (sessionId != '' && sessionId != 0) {
      if (uSSiteId == '7') {
        var loginHead = document.createElement("div");
        loginHead.className = "loginHead";
        loginHead.innerHTML = "To save your votes to your CNET profile: ";
        uSSurvey.appendChild(loginHead)
      }
        // ok, gonna need the escaped href...
        var escapedHref = escape(location.href);
        // but, we also need to know the page we are redirecting to...
        var ursRedirectTo = '/4113-4_' + uSSiteId + '-0-4.html?sessionId=' + sessionId + '&origUrl=' + escapedHref;
        // ok, now use both of those peices to build out the URS url...
        var ursUrl = '/1320-7600-110.html?path=' + escape(ursRedirectTo);
        // now, create some html... k?
        var loginArea = document.createElement("div");
        loginArea.className = "loginWelcome";
        loginArea.innerHTML = '<a href="' + ursUrl + '"><b>Log In</b></a> | Not a member? <a href="' + ursUrl + '"><b>Join now</b></a>';
        uSSurvey.appendChild(loginArea);
    }
}



function makeSubmitButton(n) {
    var sub = document.createElement("div");
    sub.className = "uSubDiv";
    sub.innerHTML = n;
    return sub;
}

function makeInputCheckBoxSpan(inId) {
    var e = document.createElement("span");
    e.className = "checkboxSpan";
    var i = document.createElement("input");
    i.type = "checkbox";
    i.name = inId;
    e.appendChild(i);
    return e;
}

function makeSpan(c) {
    var e = document.createElement("span");
    e.innerHTML = c;
    return e;
}