//<![CDATA[
var workingCount = 0;
var year = null;
var intXML = null;
var groupsInfo = new Object(); 
var billsSelectedInfo = new Object();
var classNameToRealName = new Object();
var repsData = [];
var columnSet = null;
var repConfig = null;

function normalizeGroupName(groupName) {
    return groupName.replace(/ |,|'|}|{|;/g, "");
}

function getClassNameFromGroupName(groupName) {
    return "interests" + normalizeGroupName(groupName);
}

function startWorking() {
    workingCount++;
    if (workingCount == 1) {
        setWorking(true);
    }
}

function endWorking() {
    workingCount--;
    if (workingCount == 0) {
        setWorking(false);
    }
}

function setWorking(isWorking) {
    setVisibility(document.getElementById("loading"), isWorking);
}

function setYear(aYear) {
    // Make the year link bold, and all other links not bold.
    var yearsElem = document.getElementById('years');
    for (var i = 0; i < yearsElem.childNodes.length; i++) {
        var node = yearsElem.childNodes[i];
        if (node.nodeName.toLowerCase() == 'a') {
            var nodeYear = parseInt(getDOMText(node.childNodes));
            if (nodeYear == aYear) {
                node.style.fontWeight = 'bold';
            } else {
                node.style.fontWeight = 'normal';
            }
        }
    }
    year = aYear;
    startWorking();
    doRequest('cgiHandler.cgi?action=interest&year=' + year, true, processInterestGroupsResponse, 'GET', null);
    startWorking();
    doRequest('cgiHandler.cgi?action=reps&year=' + year, true, processRepsResponse, 'GET', null);
    /*startWorking();
    doRequest('cgiHandler.cgi?action=bills&year=' + year, true, processBillsResponse, 'GET', null);*/
}

function processInterestGroupsResponse(o) {
    intXML = getDocElem(o);
    var groupsXPath = getXPathFromXML(intXML);
    var voteElems = groupsXPath.selectNodes('//iVote');
    groupsInfo = new Object();
    billsSelectedInfo = new Object();
    var groupSpan = document.getElementById('intGroupsList');
    clearAll(groupSpan);
    setVisibility(document.getElementById('intGroups'), true);
    for (var i=0; i< voteElems.length; i++) {
        var voteXPath = getXPathFromXML(voteElems[i]);
        var groupName = getNestedXPathText(voteXPath, 'iVote', 'group');
        var voteName = getNestedXPathText(voteXPath, 'iVote', 'vote');
        var voteNum = getNestedXPathText(voteXPath, 'iVote', 'voteNum');
        var url = getNestedXPathText(voteXPath, 'iVote', 'url');
        var yOrN = getNestedXPathText(voteXPath, 'iVote', 'yOrN');
        voteObject = new Object();
        voteObject['voteName'] = voteName;
        voteObject['voteNum'] = parseInt(voteNum);
        voteObject['url'] = url;
        voteObject['yOrN'] = yOrN;
        var foundGroup = false;
        for (existingGroupName in groupsInfo) {
            if (existingGroupName == groupName) {
                groupsInfo[existingGroupName].push(voteObject);
                foundGroup = true;
            }
        }
        if (!foundGroup) {
            groupsInfo[groupName] = new Array();
            groupsInfo[groupName].push(voteObject);
            classNameToRealName[getClassNameFromGroupName(groupName)] = groupName;
            var li = document.createElement('li');
            li.id = "groupLi" + groupName;
            var link = document.createElement('a');
            link.appendChild(document.createTextNode(groupName));
            link.href='javascript:selectGroup("' + groupName + '");';
            var allButton = document.createElement('input');
            allButton.type = "button";
            allButton.value = 'All';
            allButton.groupName = groupName;
            allButton.onclick = function() {selectGroupBills(this.groupName, true);}
            var noneButton = document.createElement('input');
            noneButton.type = "button";
            noneButton.value = 'None';
            noneButton.groupName = groupName;
            noneButton.onclick = function() {selectGroupBills(this.groupName, false);}
            var testP = document.createElement('p');
            testP.style.marginTop = '0px';
            testP.style.marginBottom = '0px';
            testP.appendChild(link);
            testP.appendChild(document.createTextNode(' '));
            testP.appendChild(allButton);
            testP.appendChild(noneButton);
            li.appendChild(testP);
            groupSpan.appendChild(li);
        }
    }
    for (groupName in groupsInfo) {
        addGroupInterests(groupName);
    }
    endWorking();
}

function selectGroup(gName) {
    toggleClassVisibility(getClassNameFromGroupName(gName));
}

function selectGroupBills(gName, isAll) {
    var className = getClassNameFromGroupName(gName);
    for (key in groupsInfo[gName]) {
        var voteObject = groupsInfo[gName][key];
        var checkObj = document.getElementById('check' + className + voteObject['voteNum']);
        if (checkObj.checked != isAll)  {
            checkObj.checked = isAll;
            setSelectEnabled(className, voteObject['voteNum'], isAll);
        }
    }
}

function voteChanged(voteNum, group) {
    checkForConflict(voteNum, billsSelectedInfo[voteNum]);
    updateScoreButton();
}

function weightChanged(voteNum, group) {
    var newWeight = document.getElementById('weightSelect' + group + voteNum).value;
    var allGroups = billsSelectedInfo[voteNum];
    // Update all votes that are the same to have the same weight.
    for (var i = 0; i < allGroups.length; i++){
        if (allGroups[i] != group) {
            document.getElementById('weightSelect' + allGroups[i] + voteNum).value = newWeight;
        }
    }
}

function anyConflictExists() {
    var conflict = false;
    for (key in billsSelectedInfo) {
        if (conflictExists(key)) {
            conflict = true;
        }
    }
    return conflict;
}

function conflictExists(voteNum) {
    return (document.getElementById('conflict' + voteNum) != null);
}

function checkForConflict(voteNum, groups) {
    var rightChoice = null;
    var isConflict = false;
    for (var i = 0; i < groups.length; i++) {
        var curChoice = document.getElementById('select' + groups[i] + voteNum).value;
        if (rightChoice == null) {
            rightChoice = curChoice;
        } else {
            if (rightChoice != curChoice) {
                isConflict = true;
            }
        }
    }
    if (isConflict) {
        showConflict(voteNum, groups);
    } else if (!isConflict && conflictExists(voteNum)) {
        removeConflict(voteNum);
    }
}

function showConflict(voteNum, groups) {
    var bList = document.getElementById("billConflictsList"); 
    var li = document.getElementById("conflict" + voteNum);
    if (li != null) {
        clearAll(li);
    } else {
        li = document.createElement("li");
        li.id = "conflict" + voteNum;
    }
    var innerUL = document.createElement("ul");
    for (var i = 0; i < groups.length; i++) {
        var realName = classNameToRealName[groups[i]];
        var voteName = "";
        var yOrN = "";
        var info = groupsInfo[realName];
        for (var j = 0; j < info.length; j++) {
            if (info[j]['voteNum'] == voteNum) {
                voteName = info[j]['voteName'];
            }
        }
        if (voteName != "") {
            yOrN = (document.getElementById('select' + groups[i] + voteNum).value == "True") ? "Yes" : "No";
        }
        var tempLI = document.createElement("li");
        tempLI.appendChild(document.createTextNode(realName + " - " + voteName + " (" + yOrN + ")"));
        innerUL.appendChild(tempLI);
    }
    li.appendChild(innerUL);
    bList.appendChild(li);
    setVisibility(document.getElementById("billConflictsDiv"), true); 
}

function removeConflict(voteNum) {
    var bList = document.getElementById("billConflictsList"); 
    for (var i = 0; i < bList.childNodes.length; i++) {
        if (bList.childNodes[i].id == "conflict" + voteNum) {
            bList.removeChild(bList.childNodes[i]);
        }
    }
    setVisibility(document.getElementById("billConflictsDiv"), (bList.childNodes.length > 1));
}

function updateScoreButton() {
    var shouldEnable = false;
    for (key in billsSelectedInfo) {
        if (billsSelectedInfo[key] != null && billsSelectedInfo[key].length > 0) {
            shouldEnable = true;
        }
    }
    if (anyConflictExists()) {
        shouldEnable = false;
    }
    setEnabled(document.getElementById("scoreButton"), shouldEnable);
}

function setSelectEnabled(classGroupName, voteNum, enabled) {
    setEnabled(document.getElementById("select" + classGroupName + voteNum), enabled);
    setEnabled(document.getElementById("weightSelect" + classGroupName + voteNum), enabled);
    // Keep track of this internally.
    var existingData = null;
    for (key in billsSelectedInfo) {
        if (key == voteNum) {
            existingData = billsSelectedInfo[key];
        }
    }
    if (existingData == null || existingData.length == 0) {
        if (enabled) {
            billsSelectedInfo[voteNum] = new Array(classGroupName);
        } else {
            // If it''s disabled, we''ve screwed up somewhere, but oh well.
        }
    } else {
        // Update this weight with a weight that exists already.
        document.getElementById("weightSelect" + classGroupName + voteNum).value = document.getElementById("weightSelect" + existingData[0] + voteNum).value;
        if (enabled) {
            var otherExisting = false;
            var inArrayAlready = false;
            for (var i = 0; i < existingData.length; i++) {
                if (existingData[i] != classGroupName) {
                    otherExisting = true;    
                } else {
                    inArrayAlready = true;
                }
            }
            if (!inArrayAlready) {
                existingData.push(classGroupName);
            }
        } else {
            var foundIndex = -1;
            for (var i = 0; i < existingData.length; i++) {
                if (existingData[i] == classGroupName) {
                    foundIndex = i;
                }
            }
            if (foundIndex != -1) {
                existingData.splice(foundIndex, 1);
            }
        }
        checkForConflict(voteNum, existingData);
    }
    updateScoreButton();
}

function doScore() {
    var queryString = "action=score&year=" + year;
    for (key in billsSelectedInfo) {
        if (billsSelectedInfo[key] != null && billsSelectedInfo[key].length > 0) {
            var yOrN = document.getElementById('select' + billsSelectedInfo[key][0] + key).value;
            var weight = document.getElementById('weightSelect' + billsSelectedInfo[key][0] + key).value;
            queryString += "&num=" + key + "&val=" + yOrN + "&weight=" + weight;
        }
    }
    startWorking();
    doRequest('cgiHandler.cgi', true, processScoreResponse, 'POST', queryString);
}

function addGroupInterests(gName) {
    // FFV - don''t use intXML, use groupsInfo
    var groupsXPath = getXPathFromXML(intXML);
    var voteElems = groupsInfo[gName];
    if (voteElems.length > 0) {
        var groupLI = document.getElementById("groupLi" + gName);
        clearAllButFirstElement(groupLI);
        var newUL = document.createElement('ul');
        var classGroupName = getClassNameFromGroupName(gName);
        newUL.className = classGroupName;
        for (var i = 0; i < voteElems.length; i++) {
            var curElem = voteElems[i];
            var selectId = classGroupName + curElem['voteNum']
            var newLI = document.createElement('li');
            var check = document.createElement('input');
            check.id = "check" + selectId;
            check.type = 'checkbox';
            check.voteNum = curElem['voteNum'];
            check.classGroupName = classGroupName;
            check.onclick = function() {setSelectEnabled(this.classGroupName, this.voteNum, this.checked);}
            //check.setAttribute("onclick", "toggleSelect('" + classGroupName + curElem['voteNum'] + "')");
            newLI.appendChild(check);
            newLI.appendChild(document.createTextNode(' ' + curElem['voteName'] + ' ('));
            var infoLink = document.createElement('a');
            infoLink.href = curElem['url'];
            infoLink.appendChild(document.createTextNode("info"));
            newLI.appendChild(infoLink);
            newLI.appendChild(document.createTextNode(') '));
            var select = document.createElement('select');
            select.id = "select" + selectId;
            select.voteNum = curElem['voteNum'];
            select.classGroupName = classGroupName;
            select.onchange = function() {voteChanged(this.voteNum, this.classGroupName);}
            var yesVote = document.createElement("option");
            yesVote.value = "True";
            yesVote.appendChild(document.createTextNode("Yes"));
            var noVote = document.createElement("option");
            noVote.value = "False";
            noVote.appendChild(document.createTextNode("No"));
            if (curElem['yOrN'] == "yes") {
                yesVote.style.fontWeight = "bold";
                // Opera doesn''t work with selected
                // IE doesn''t work with defaultSelected
                yesVote.defaultSelected = true;
                yesVote.selected = true;
                yesVote.appendChild(document.createTextNode("*"));
            } else {
                noVote.style.fontWeight = "bold";
                noVote.defaultSelected = true;
                noVote.selected = true;
                noVote.appendChild(document.createTextNode("*"));
            }
            select.appendChild(yesVote);
            select.appendChild(noVote);
            select.disabled = true;
            newLI.appendChild(select);
            newLI.appendChild(document.createTextNode(" Weight: "));
            var weightSelect = document.createElement('select');
            weightSelect.id = "weightSelect" + selectId;
            weightSelect.voteNum = curElem['voteNum'];
            weightSelect.classGroupName = classGroupName;
            weightSelect.onchange = function() {weightChanged(this.voteNum, this.classGroupName);}
            var highWeight = document.createElement("option");
            highWeight.value = 3;
            highWeight.appendChild(document.createTextNode("High"));
            var medWeight = document.createElement("option");
            medWeight.value = 2;
            medWeight.appendChild(document.createTextNode("Medium"));
            // Opera doesn''t work with selected
            // IE doesn''t work with defaultSelected
            medWeight.defaultSelected = true;
            medWeight.selected = true;
            var lowWeight = document.createElement("option");
            lowWeight.value = 1;
            lowWeight.appendChild(document.createTextNode("Low"));
            weightSelect.appendChild(highWeight);
            weightSelect.appendChild(medWeight);
            weightSelect.appendChild(lowWeight);
            weightSelect.disabled = true;
            newLI.appendChild(weightSelect);
            newUL.appendChild(newLI);
        }
        groupLI.appendChild(newUL);
        // add the CSS rule to show this list. (so we can turn it off later)
        var stylesheet = document.styleSheets[0];
        if (stylesheet.insertRule) {
            stylesheet.insertRule("." + classGroupName + " {display: block;}", 0);
        } else {
            stylesheet.addRule("." + classGroupName, "{display: block;}");
        }
    }
}

function processScoreResponse(o) {
    var scoreXML = getDocElem(o);
    // We could do this using XPath, but let''s iterate over nodes
    // the old-fashioned way, just for fun.  (maybe faster, too?)
    var scoreData = new Object();
    for (var i = 0; i < scoreXML.childNodes.length; i++) {
        var curNode = scoreXML.childNodes[i];
        var leg = '';
        var mat = 0;
        var tot = 0;
        for (var j = 0; j < curNode.childNodes.length; j++) {
            var curChildNode = curNode.childNodes[j];
            if (curChildNode.nodeName == 'leg') {
                leg = getDOMText(curChildNode.childNodes);
            } else if (curChildNode.nodeName == 'mat') {
                mat = parseInt(getDOMText(curChildNode.childNodes));
            } else if (curChildNode.nodeName == 'tot') {
                tot = parseInt(getDOMText(curChildNode.childNodes));
            }
        }
        var score = 0;
        if (tot != 0) {
            score = Math.round((100*mat)/tot);
        }
        scoreData[leg] = score;
    }
    // Update repsData with scoreData.
    for (var i = 0; i < repsData.length; i++) {
        var curLeg = repsData[i]['name'];
        var curScore = scoreData[curLeg];
        if (curScore == undefined || curScore == 0) {
            // "0" will display in the table, but 0 won''t.
            curScore = "0";
        }
        repsData[i]['score'] = curScore;
    }
    // Sort repsData by score.
    repsData = repsData.sort(function(a, b) {return b['score'] - a['score'];});
    // Make sure the score chart is showing
    var dataSource = new YAHOO.util.DataSource(repsData);
    dataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
    dataSource.responseSchema =  {
        fields : ["name", "state", "party", "score"]
    };
    var dataTable = new YAHOO.widget.DataTable("scoreResults", columnSet, dataSource, repConfig);
    dataTable.subscribe("cellClickEvent", dataTable.onEventSelectRow); 
    setVisibility(document.getElementById('scoreResults'), true);
    endWorking();
}

function processRepsResponse(o) {
    // Make sure the score chart is hidden 
    setVisibility(document.getElementById('scoreResults'), false);
    var repsXML = getDocElem(o);
    if (repsXML == null) {
        alert('repsXML NULL!!!!!');
    }
    var repsXPath = getXPathFromXML(repsXML);
    var repsElems = repsXPath.selectNodes('//rep');
    if (repsElems.length > 0) {
        var repsColumnHeaders = [
            {key:"name", text: "Name", sortable: true, className:"nameCol"},
            {key:"state", text: "State", sortable: true, className:"stateCol"},
            {key:"party", text: "Party", sortable: true, className:"partyCol"},
            {key:"score", text: "Score (of 100)", sortable: true, className:"scoreCol"}];
        repsData = [];
        var legsElem = document.getElementById('legs');
        clearAll(legsElem);
        for (var i = 0; i < repsElems.length; i++) {
            var repXPath = getXPathFromXML(repsElems[i]);
            var repName = getNestedXPathText(repXPath, 'rep', 'name');
            var repState = getNestedXPathText(repXPath, 'rep', 'state');
            var repParty = getNestedXPathText(repXPath, 'rep', 'party');
            var data = {name: repName, state: repState, party: repParty, score: 0};
            repsData.push(data);
        }
        columnSet = new YAHOO.widget.ColumnSet(repsColumnHeaders);
        repConfig = {
            caption: "Scores",
            scrollable: true,
            rowSingleSelect: true,
            sortedBy: {colKey:"score", dir:"desc"}
        };
    }
    endWorking();
}

function processBillsResponse(o) {
    var billsXML = getDocElem(o);
    var xpath = getXPathFromXML(billsXML);
    var xpathExpr = '//bill';
    var elems = xpath.selectNodes(xpathExpr);
    //var elems = zXPath.selectNodes(billsXML, '//bill');
    if (elems.length > 0) {
        var legsElem = document.getElementById('bills');
        clearAll(legsElem);
        for (var i = 0; i < elems.length; i++) {
            var repXPath = getXPathFromXML(elems[i]);
            //var titleElem = zXPath.selectSingleNode(elems[i], 'title');
            var billTitle = getNestedXPathText(repXPath, 'bill', 'title');
            if (billTitle != '' && billTitle != undefined) {
                var opt = document.createElement('option');
                opt.appendChild(document.createTextNode(billTitle));
                legsElem.appendChild(opt);
            }
        }
    }
    endWorking();
}

function processYearResponse(o) {
    var yearsXML = getDocElem(o);
    var xpath = getXPathFromXML(yearsXML);
    var xpathExpr = '//year';
    var elems = xpath.selectNodes(xpathExpr);
    if (elems.length > 0) {
        var yearsElem = document.getElementById('years');
        for (var i = 0; i < elems.length; i++) {
            var year = getDOMText(elems[i].childNodes);
            var link = document.createElement('a');
            link.href="javascript:setYear(" + year + ");";
            link.appendChild(document.createTextNode(year));
            yearsElem.appendChild(link);
            yearsElem.appendChild(document.createTextNode(' '));
        }
    }
    endWorking();
}

function getYears() {
    startWorking();
    doRequest('cgiHandler.cgi?action=years', true, processYearResponse, 'GET', null);
}

function doRequest(url, async, callback, method, postData) {
    var cb = {
        success : callback,
        failure : function() { alert("Failure loading!");}
    };
    if (async) {
        var request = YAHOO.util.Connect.asyncRequest(method, url + ((method.toLowerCase() == 'get') ? ("&ignorethis=" + Math.random()) : ""), cb, postData);
    } else {
        alert('Unimplemented');
    }
}

//var logReader = new YAHOO.widget.LogReader("myLogger");
getYears();

//]]>
