﻿// JavaScript for the dataset page.
// This encompasses all clicks.

var grid;
// function RowCreated(row)
// {
//    
//    for(var i = 0; i < row.Control.cells.length; i++)
//     {
//        var Cell = row.Control.cells[i];
//        var CellStr1 = (Cell.innerText)? Cell.innerText : Cell.textContent;
//        if(Cell.innerText != "" && CellStr1.replace(/\s+/g,"") != "")
//        {

//           row.Control.cells[i].onmouseover = function()
//           {
//              this.className = "HoverClass";

//           };
//           row.Control.cells[i].onmouseout = function()
//           {

//             if(this.selected != "1")
//             {
//               this.className = "";
//             }
//             else
//             {
//               var cssName = (this.selected == "1") ? "SelCell" : ""
//               this.className = cssName;
//               return;
//             }
//           };
//           
//         }  
//     }
//     
// }
 
 function SelectGroupLink(windowObj, cellID)
 {
     var srcObj = document.getElementById(cellID);
     if (srcObj != null)
     {
         srcObj.onclick();
         return false;
     }
     else
         windowObj.parentNode.onclick();
         
    
    
 }
 
function SelectGroupClick(srcObj)
{
    bChangedSelections = true;
    
    var miscObj = this;
    var cellNode = srcObj.parentNode;
    var ColumnIndex = cellNode.cellIndex;
    var NextColumn = ColumnIndex + 1;
    var adjacentCell = cellNode.nextSibling;
    var RowIndex = cellNode.parentNode.rowIndex;
    
    //get node code
    var dotnetcode = cellNode.id.split("_");
    var parentNodeID = dotnetcode[dotnetcode.length - 1];
    var ttNode = tabletree[parentNodeID];
    
    var checkedStatus = ttNode.checked;
    //click the checkboxes in the next column, with the chillens list
    var chillens = ttNode.chillens;
    var aChillens = chillens.split(',');
    
    outerloop:
    for(var i = 0; i < aChillens.length; i++)
    {
        var cell = grid.MasterTableView.Rows[Number(aChillens[i])].Control.cells[NextColumn];
        for (var j = 0; j < cell.childNodes.length; j++)
        {
            if(cell.childNodes[j].type == "checkbox")
            {
                
                var varName = GetVarName(cell.childNodes[j].id);
                if(ExclusiveJurisdiction[varName])
                {
                    if(!checkedStatus)
                    {
                        cell.childNodes[j].disabled = true;
                        continue outerloop;
                    }
                    else
                    {
                        
                        cell.childNodes[j].disabled = (GetSelectedVars() < 1);
                        continue outerloop;
                    }
                }
                cell.childNodes[j].checked = !checkedStatus;
                if(!checkedStatus)
                {
                    selectedJurs[varName] = 1;
                    cell.style.backgroundColor = clickedColor;
                }
                else
                {
                    delete selectedJurs[varName];
                    cell.style.backgroundColor = "";
                }
                
                continue outerloop;
            }
        }
    }
    CheckExclusiveJurisdictions();
    ttNode.checked = !checkedStatus;
    srcObj.checked = ttNode.checked;
    
    //Now that I have the node, if the group isn't open, I have to open it.
    if(!ttNode.selected)
        cellNode.onclick();
}

function GetVarName(str)
{
    var thisObjCode = str.split("_");
    return thisObjCode[thisObjCode.length - 1];                
}
 
var overrideCell = 0;
function ShowCells(cellList, thisCell, cellRowIndex, nodeName)
{
    if(!tabletree[nodeName].selected && overrideCell < 1)
    {
        tabletree[nodeName].selected = true;
        thisCell.selected = "1";
        //change cell color
        thisCell.className = "SelCell";
        //change image
        for(var i = 0; i < thisCell.childNodes.length; i++)
        {
            if(thisCell.childNodes[i].tagName == "A")
            {
                var anchor = thisCell.childNodes[i];
                for(var j = 0; j < anchor.childNodes.length; j++)
                {
                    if(anchor.childNodes[j].tagName=="IMG")
                    {
                        anchor.childNodes[j].src = "app_themes\/" + themename + "\/images\/arrow_down.gif";
                        anchor.childNodes[j].title = "collapse";
                        break;
                    }
                }
            }
        }
        //select cell by opening cell list
        var aCells = cellList.split(",");
        for(var i = 0; i < aCells.length; i++)
        {
            if(cellRowIndex != aCells[i])
                grid.MasterTableView.ShowRow(aCells[i]);
        }
        //turn on adjacent cells
        // this next, commented rule is for the variables table
        var cells = thisCell.parentNode.cells;
        for(var j = thisCell.cellIndex + 1; j < cells.length; j++)
            cells[j].style.display = '';
  
    }
    else
    {
        tabletree[nodeName].selected = false;
        thisCell.selected = "0";
        thisCell.className = "NSelCell";
        //change image
        for(var i = 0; i < thisCell.childNodes.length; i++)
        {
            if(thisCell.childNodes[i].tagName == "A")
            {
                var anchor = thisCell.childNodes[i];
                for(var j = 0; j < anchor.childNodes.length; j++)
                {
                if(anchor.childNodes[j].tagName=="IMG")
                {
                    anchor.childNodes[j].src = "app_themes\/" + themename + "\/images\/arrow_rt.gif";
                    anchor.childNodes[j].title = "expand";
                    break;
                }
                }
            }
        }
        //deselect cell by closing the cell list
        var aCells = cellList.split(",");
        for(var i = 0; i < aCells.length; i++)
        {
            if(cellRowIndex != aCells[i])
            {
                grid.MasterTableView.HideRow(aCells[i]);
            }
            if(grid.MasterTableView.Rows[aCells[i]].Control.cells[thisCell.cellIndex + 1].selected == "1")
            {
                //fire the onclick for that selected cell and make it unselected/closed
                grid.MasterTableView.Rows[aCells[i]].Control.cells[thisCell.cellIndex + 1].onclick();
            }
        }

        var cells = thisCell.parentNode.cells;
        for(var j = thisCell.cellIndex + 1; j < cells.length; j++)
            cells[j].style.display = 'none';
    }
    setTimeout('CheckTableScroll()', 1);
}

// this checks the scroll and adds a margin if it is needed
function CheckTableScroll()
{
    if(accessibleOn)
        return;
    //check the scroll div
    if(grid.MasterTableView.Control.scrollHeight > 360)
    {
      grid.GridHeaderDiv.style.width = "";
       grid.GridHeaderDiv.style.marginRight = "17px";
    }
    else
    {
    //writeToWindow(grid.GridHeaderDiv.style.marginRight);
        grid.GridHeaderDiv.style.marginRight = "0px";
    }
}


function GridCreated()
{
  grid = this;
  if (bCheckCheckboxes)
  {
    UpdateCurrentState();
  }
}

var sSubjectValue = "NA";




function ShowError(HTMLFromServer,context)
{
    alert("ERROR:" + HTMLFromServer);
}

function ShowAccordion(HTMLFromServer,context)
{
    //insert the HTML and register it.
    var srcObj = context[2];
    var insertObj = srcObj.nextSibling;
    while(insertObj != null &&
        insertObj.tagName != "SPAN")
    {    
        insertObj = insertObj.nextSibling
    }
    if(insertObj.tagName == "SPAN")
    {
        insertObj.innerHTML = HTMLFromServer;
    
        //initialize it
        Sys.Application.add_init(
          function() {
            $create(
                AjaxControlToolkit.AccordionBehavior,
                {"ClientStateFieldID" : context[0] + "_AccordionExtender_ClientState",
                "FadeTransitions":true,"SelectedIndex":-1,
                "id" : context[0] + "_AccordionExtender","requireOpenedPane":false},
                null,
                null,
                $get(context[0])
            );
          }
        );
        //fire it again now that it's loaded
       OpenAcc(context[0],context[1],context[2]);
     }
}
var selAnchors = {};

function OpenAcc(ctrlname, level, srcObj)
{
    var obj = $find(ctrlname + "_AccordionExtender");
    // if this obj doesn't exist,
    if(!obj)
    {
        // create or get it
        GetAccordion(ctrlname, srcObj.parentNode.childNodes[0].checked, [ctrlname, level, srcObj]);
    }
    else
    {
        if (obj.get_SelectedIndex() == level)
        {
            //close logic
            if(srcObj.innerText)
            {
                srcObj.innerText = "details";
            }
            else
            {
                srcObj.textContent = "details";
            }
            obj.set_SelectedIndex(-1);
        }
        else
        {
           //open logic
            if(srcObj.innerText)
            {
                srcObj.innerText = "hide details";
            }
            else
            {
                srcObj.textContent = "hide details";
            }
            if(selAnchors[ctrlname])
            {
                delete selAnchors[ctrlname]
            }
            obj.set_SelectedIndex(level);
            selAnchors[ctrlname] = srcObj;
        }
    }
    return false;
}

var ExclusiveJurisdiction = { };
/**********************************************
    CBVarClick is a misnomer. This is jurisdictions
        we are dealing with.
***********************************************/
var ExclusiveJurClicked = false;
function CBVarClick(srcObj)
{
   bChangedSelections = true;
   //   determine what the variable is
   var varName = GetVarName(srcObj.id);
   
   //add checks to see if the parent node is checked, if we are unchecking then it should be unchecked
   
   //add a check to see if all of the subnodes are checked, and then to check the parent node.
   if(srcObj.checked)
   {
        selectedJurs[varName] = 1;
        srcObj.parentNode.style.backgroundColor = clickedColor;
   }
   else
   {
        selectedJurs[varName] = 0;
        srcObj.parentNode.style.backgroundColor = "";
   }
   
   if(ExclusiveJurisdiction[varName])
   {
        //disable all other jurisdictions
        var disabledStatus = ExclusiveJurClicked;
        //cycle through this column and execute the operation
        var Rows = grid.MasterTableView.Rows;
        outerloop:
        for(var i = 0; i < Rows.length; i++)
        {
        ///////////////////////////////////////
        // disable the group check boxes
        ///////////////////////////////////////
            var cell = Rows[i].Control.cells[0];
            //do things to the group cell.
            for (var j = 0; j < cell.childNodes.length; j++)
            {
                if(cell.childNodes[j] && cell.childNodes[j].id && cell.childNodes[j].id != "")
                {
                    
                    
                    if(cell.childNodes[j].type == "checkbox")
                    {
                        cell.childNodes[j].disabled = !disabledStatus;
                         cell.style.color = (!disabledStatus) ? "#BBBBBB" : "#000000";
                        var thisNodeName = GetVarName(cell.id);    
                        // this is supposed to uncheck disabled checkboxes
                        if(!disabledStatus)
                        {
                            cell.childNodes[j].checked = disabledStatus;
                            tabletree[thisNodeName].checked = 1;
                        }
                        else
                        {
                            tabletree[thisNodeName].checked = 0;
                        }
                    }
                    
                }
            }
            
        ///////////////////////////////////////
        // check/uncheck check boxes in the Jurisdiction column
        ///////////////////////////////////////
            cell = Rows[i].Control.cells[1];
            for (var j = 0; j < cell.childNodes.length; j++)
            {
                if(cell.childNodes[j] && cell.childNodes[j].id && cell.childNodes[j].id != "")
                {
                    var thisObjCode = cell.childNodes[j].id.split("_");
                    var thisVarName = thisObjCode[thisObjCode.length - 1];
                    if(cell.childNodes[j].type == "checkbox" && thisVarName != varName)
                    {   
                        cell.childNodes[j].disabled = !disabledStatus;
                        
                         cell.style.color = (!disabledStatus) ? "#BBBBBB" : "#000000";
                        if(!disabledStatus)
                        {
                            cell.childNodes[j].checked = disabledStatus;
                            
                            delete selectedJurs[thisVarName];
                        }
                        continue outerloop;
                    }
                }
            }
        }
        ExclusiveJurClicked = !ExclusiveJurClicked;
        
        
        
        
        
   }
   else
   {
        CheckExclusiveJurisdictions();
        
   }
  
   CheckIfGroupFull(srcObj);


}

function CheckIfGroupFull(srcObj)
{
    /*
        the srcObj here is the jur checkbox
    */
    //get the parent node.
    var cellNode = srcObj.parentNode;
    var ColumnIndex = cellNode.cellIndex;
    var RowIndex = cellNode.parentNode.rowIndex;
    //compensating for an extra row here.
    if (accessibleOn)
        RowIndex = RowIndex - 1;
    //get node code
    var parentNodeID = GetParentTTNode(RowIndex);
    var ttNode = tabletree[parentNodeID];
    
    // accessing these properties implies that this is a parent node in the tree
    var chillens = ttNode.chillens;
    var aChillens = chillens.split(',');
    
    //count the selected items in that group
    var checkboxcount = aChillens.length;
    var loopctr = 0;
    var exctr = 0;
    outerloop:
    for(var i = 0; i < aChillens.length; i++)
    {
        var cell = grid.MasterTableView.Rows[Number(aChillens[i])].Control.cells[ColumnIndex];
        for (var j = 0; j < cell.childNodes.length; j++)
        {
            if(cell.childNodes[j].type == "checkbox" && 
              cell.childNodes[j].checked  )
            {
                loopctr++;
                continue outerloop;
            }
            else if(cell.childNodes[j].id &&
            ExclusiveJurisdiction[GetVarName(cell.childNodes[j].id)])
                    exctr++;
        }
     }
     if((loopctr + exctr) == checkboxcount)
     {
        //check the parent checkbox
        ttNode.checked = true;
        var cbox = GetCellCheckboxFromTT(parentNodeID)
        cbox.checked = true;
        //if the group isn't open, I have to open it.
        if(!ttNode.selected)
        {
            cbox.parentNode.onclick();
        }
        
     }
     else if ((loopctr - exctr) < checkboxcount)
     {
        //uncheck the parent checkbox
        ttNode.checked = false;
        GetCellCheckboxFromTT(parentNodeID).checked = false;
     }
}

/*
    pass this the name of the tabletree node and it'll return the checkbox
        for instance: 'n4' (an automatically generated name)
        would return the checkbox 'select all' for 'region'
*/
function GetCellCheckboxFromTT(sName)
{
    var Rows = grid.MasterTableView.Rows;
        outerloop:
        for(var i = 0; i < Rows.length; i++)
        {
            // this is checking the first column
            var cell = Rows[i].Control.cells[0];
            if(GetVarName(cell.id) == sName)
            {
                for (var j = 0; j < cell.childNodes.length; j++)
                {
                    if(cell.childNodes[j].type == "checkbox")
                    {
                        return cell.childNodes[j];
                    }
                }
            }
        }
        
}

function GetParentTTNode(RowIndex)
{
    for(var node in tabletree)
    {
        if(tabletree[node].chillens)
        {
            var as = "," + tabletree[node].chillens + ",";
            if(as.indexOf(RowIndex) > -1)
            {
                return node;
            }
            
        }
    }
    return null;
}

function CheckExclusiveJurisdictions()
{
    //decide whether to disable or enable the exclusive Jurisdictions
        var disabledStatus = (GetSelectedJurs() < 1 );
        var strVarNames = "";
        for (var jur in ExclusiveJurisdiction)
        {
            strVarNames += jur + ",";
        }   
        //Cycle through this column and compare
        // the current jurisdiction to the list of exclusive j's so that 
        // they can be enabled.
        var Rows = grid.MasterTableView.Rows;
        outerloop:
        for(var i = 0; i < Rows.length; i++)
        {
            var cell = Rows[i].Control.cells[1];
            for (var j = 0; j < cell.childNodes.length; j++)
            {
                if(cell.childNodes[j] && cell.childNodes[j].id)
                {
                    var thisObjCode = cell.childNodes[j].id.split("_");
                    var thisVarName = thisObjCode[thisObjCode.length - 1];
                    
                    if(cell.childNodes[j].type && cell.childNodes[j].type == "checkbox" 
                        && strVarNames.indexOf(thisVarName) > -1)
                    {   
                        cell.childNodes[j].disabled = !disabledStatus;
                        cell.style.color = (!disabledStatus) ? "#BBBBBB" : "#000000";
                        if(!disabledStatus)
                        {
                            cell.childNodes[j].checked = disabledStatus;
                            delete selectedJurs[thisVarName];
                        }
                        continue outerloop;
                    }
                }
            }
        }
}

function GetSelectedJurs()
{
        var ctr = 0;
        for(var vr in selectedJurs)
        {
            if(selectedJurs[vr]==1)
            ctr++;
        }
        return ctr;
}
function GetSelectedVars()
{
        var ctr = 0;
        for(var vr in selectedVars)
        {
            if(selectedVars[vr]==1)
            ctr++;
        }
        return ctr;
}

function CBSSClick(srcObj)
{
    var varName = GetVarName(srcObj.id);
    bChangedSelections = true;
   if(srcObj.checked)
   {
        selectedVars[varName] = 1;
        srcObj.parentNode.style.backgroundColor = clickedColor;
   }
   else
   {
        selectedVars[varName] = 0;
        srcObj.parentNode.style.backgroundColor = "";
   }

}



function SaveTTreeState()
{
    var retstr = "";
    for(var node in tabletree)
    {
        if(tabletree[node].selected)
        {
            retstr += node + ":" + tabletree[node].selected + ",";
        }
    }
    retstr = retstr.substring(0, retstr.length - 1);
    document.getElementById(hfttstate).value = retstr;
}
function SaveState()
{
    SaveTTreeState();
    SaveVarState();
    SaveJurState();
    SaveSWStudy();
    SaveYearState();
    document.getElementById(hfChangedSelectionsID).value = bChangedSelections;
}

var previousSelectedSubjectIndex;

// ================= Validation Code ==================

var switchingStudy = false;
// This "infunc" var handles a strange bug in firefox
// where OnSelectStudyChanging fires twice because
// of the user prompt.
var infunc = false;

function OnSelectedStudyChanging(combobox)
{
    if(combobox.Value == "")
        return false;

    if(!infunc && !bTableVisible && CohortID.GetText() == "")
    {
        CohortID.SetText("Loading...");
        CohortID.RequestItems(combobox.Value, false);
        StudyID.AutoPostBack = false;
        StudyID.SetText(combobox.Text);
        StudyID.SetValue(combobox.Value);
        
    }
    else if(!infunc)
    {
        infunc = true;
        var cboBox = StudyID;
        if(cboBox.SelectedItem)
            previousSelectedValueIndex = cboBox.SelectedItem.Index;
        else
            previousSelectedValueIndex = 0;
        if(hasVariables && confirm(
              "------------------------------------------------------------" 
            + "\n\nChanging the study will"
            + " result in losing all user settings.\n\n Choose OK to continue. Cancel to stop.\n\n"
            + "------------------------------------------------------------"))
            {
                switchingStudy = true;
                bChangedSelections = true;
            }
        else
        {
            if(hasVariables)
            {
                // hide dropdown
                // In Firefox, cancelling this makes it happen
                //  again anyway.
                var str = cboBox.OnSelectedStudyChanging;
                cboBox.OnSelectedStudyChanging = "";
                cboBox.HideDropDown();
                cboBox.OnSelectedStudyChanging = str;
                infunc = false;
                return false;
            }
            else
            {
                switchingStudy = true;
                bChangedSelections = true;
            }
        }
        infunc = false;
    }
    else
    {
        return false;
    }
}
/*===========================================================================

    working right here

===========================================================================*/
function OnSelectedStudyChanged()
{
    
}
var dbugctr = 0;
function OnSelectedGradeChanging(combobox)
{
    
    if(combobox.Value == "")
        return false;
    
    if(!infunc && !bTableVisible&& StudyID.GetValue() == "")
    {
        StudyID.SetText("Loading...");
        StudyID.RequestItems(combobox.Value, false);
        CohortID.AutoPostBack = false;
        CohortID.SetText(combobox.Text);
        CohortID.SetValue(combobox.Value);
    }
    else if(!infunc)
    {
        infunc = true;
        var cboBox = CohortID;
        if(cboBox.SelectedItem)
            previousSelectedValueIndex = cboBox.SelectedItem.Index;
        else
            previousSelectedValueIndex = 0;
        if(hasVariables && confirm(
              "------------------------------------------------------------" 
            + "\n\nChanging the study will"
            + " result in losing all user settings.\n\n Choose OK to continue. Cancel to stop.\n\n"
            + "------------------------------------------------------------"))
            {
                switchingStudy = true;
                bChangedSelections = true;
            }
        else
        {
            if(hasVariables)
            {
                // hide dropdown
                // In Firefox, cancelling this makes it happen
                //  again anyway.
                var str = cboBox.OnSelectedGradeChanging;
                cboBox.OnSelectedGradeChanging = "";
                cboBox.HideDropDown();
                cboBox.OnSelectedGradeChanging = str;
                infunc = false;
                return false;
            }
            else
            {
                switchingStudy = true;
                bChangedSelections = true;
            }
        }
        infunc = false;
    }
    else
    {
        return false;
    }
    // update other box
    
}

function OnSelectedFrameworkChanging()
{
    switchingStudy = true;
    bChangedSelections = true;
    //alert("OnSelectedFrameworkChanging");
}

function OnSubjectBoxBlur(combobox)
{

}

function OnGradeBoxBlur(combobox)
{

}

function ItemsLoaded(combo)
{
    if (combo.Items.length > 0)
    {
        combo.SetText(combo.Items[0].Text);
        combo.Items[0].Highlight();
    }
    combo.ShowDropDown();
    
}


function ValidateDepSelected(val, args)
{

    var selectedVarsNum = 0;
    for(var vari in selectedVars)
    {
        if (selectedVars[vari] == 1)
            selectedVarsNum++;
    }
    if(selectedVarsNum > 0)
    {
        args.IsValid = true;
    }
    else
    {
        //if table there fail it, otherwise
        //  let the request go so the user can
        //  get the table
        if(bTableVisible && !switchingStudy)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }
    
}

function ValidateJurSelected(val, args)
{
    var selectedJursNum = 0;
    for(var vari in selectedJurs)
    {
        if (selectedJurs[vari] == 1)
            selectedJursNum++;
    }
    if(selectedJursNum > 0)
    {
        args.IsValid = true;
    }
    else
    {
        //if table there fail it, otherwise
        //  let the request go so the user can
        //  get the table
        if(bTableVisible && !switchingStudy)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }
}

function SaveVarState()
{
    var retstr = "";
    for(var variable in selectedVars)
    {
        retstr += variable + ":" + selectedVars[variable] + ",";
    }
    retstr = retstr.substring(0, retstr.length - 1);
    document.getElementById(varstate).value = retstr;
}

function SaveJurState()
{
    var retstr = "";
    for(var variable in selectedJurs)
    {
        retstr += variable + ":" + selectedJurs[variable] + ",";
    }
    retstr = retstr.substring(0, retstr.length - 1);
    document.getElementById(jurisdictionstate).value = retstr;
}

function SaveSWStudy()
{
    document.getElementById(hfSWStudy).value = switchingStudy;
}

// This is called when the page is opened from another page
// to update the client state. It runs off the bCheckCheckboxes flag.
function UpdateCurrentState()
{
    CheckExclusiveJurisdictions();   
    
    
    //In order to use the same functionality, I'll just pick a
    //  juris checkbox in each parent
    var Rows = grid.MasterTableView.Rows;
    outerloop:
    //find a checkbox to check it's parent
    for(var i = 0; i < Rows.length; i++)
    {
        var cell = Rows[i].Control.cells[0];
        if(cell.innerHTML != "&nbsp;")
        {
            var srcObj = GetCheckBoxInCell(Rows[i].Control.cells[1]);
            if(srcObj != null)
            {
                CheckIfGroupFull(srcObj);
                continue outerloop;
            }
            
        }
    }
    
    

    // these boxes are merely for feedback purposes
    //  the server doesn't know about them.
    CheckIfAllYearsShouldBeChecked();
    
    OpenTreeItemsThatContainSelections();
}

function OpenTreeItemsThatContainSelections()
{
    var Rows = grid.MasterTableView.Rows;
    
    // This opens the tree for the checked jurisdictions
    var parentcell;
    for(var i = 0; i < Rows.length; i++)
    {
        var firstcell = Rows[i].Control.cells[0];
        if(i == 0)
            parentcell = firstcell;
        else if (firstcell.id != "")
        {
            parentcell = firstcell;
        }
        if(parentcell.selected == 1)
            continue;
        var cell = Rows[i].Control.cells[1];
        if(cell.innerHTML != "&nbsp;")
        {
            var srcObj = GetCheckBoxInCell(cell);
            if(srcObj != null)
            {
                if(srcObj.checked)
                {
                    // open parent node
                    
                    var ttn = tabletree[GetParentTTNode(i)];
                    if(ttn.selected != 1)
                    {
                        // the ttnode is
                        parentcell.onclick();
                    }
                        
                }
            }
            
        }
    }
}

function GetCheckBoxInCell(cell)
{
    for (var j = 0; j < cell.childNodes.length; j++)
    {
        if(cell.childNodes[j].type == "checkbox")
        {
            return cell.childNodes[j];
        }
    }
    return null;
}

//=========== Year Click logic =======================
function YRClick(yearSample, srcObj)
{
// this tells the server that I clicked something so kill the cache state
   bChangedSelections = true;
    if(srcObj.checked)
    {
        selectedYears[yearSample] = 1;
        
    }
    else
    {
        selectedYears[yearSample] = 0;
    }
    // loop through similarly valued objects and check them as well
    var sYearVal = GetVarName(srcObj.id);  
    if(hYearControls[sYearVal])
    {
        var controls = hYearControls[sYearVal];
        for(var i = 0; i < controls.length; i++)
        {
            ctrl = document.getElementById(controls[i]);
            if(ctrl && ctrl.checked != srcObj.checked)
                ctrl.checked = srcObj.checked;
        }
    }
    CheckIfAllYearsShouldBeChecked();
}
//==============All year click logic================================
function ToggleAllYearsClick(srcObj)
{
    bChangedSelections = true;
    if(hAllYearControls)
    {
        for(var ctrlname in hAllYearControls)
        {
            var controlID = hAllYearControls[ctrlname];
            ctrl = document.getElementById(controlID);
                if(ctrl && ctrl.checked != srcObj.checked)
                    ctrl.checked = srcObj.checked;
        }
    }
    if(hYearControls)
    {
        for(var ctrlname in hYearControls)
        {
            var ctrls = hYearControls[ctrlname];
            for(var i = 0; i < ctrls.length; i++)
            {
                ctrl = document.getElementById(ctrls[i]);
                if(ctrl)
                {
                    ctrl.checked = srcObj.checked;
                    var yearname = GetVarName(ctrl.id)
                    selectedYears[yearname] = (srcObj.checked) ? 1 : 0;
                }
            }
        }
    }
}

function CheckIfAllYearsShouldBeChecked()
{
    
    //count the selected years
    var iYearCount = 0;
    for(var year in selectedYears)
    {
        if(selectedYears[year] == 1)
            iYearCount++;
    }
    //count the hYearControls
    var iCtrlCount = 0;
    for(var ctrlname in hYearControls)
        iCtrlCount++;
        
    //test them and uncheck the all years boxes if they don't match
    var checkedState = (iYearCount == iCtrlCount);
    
        if(hAllYearControls)
        {
            for(var ctrlname in hAllYearControls)
            {
                var controlID = hAllYearControls[ctrlname];
                ctrl = document.getElementById(controlID);
                    if(ctrl)
                        ctrl.checked = checkedState;
            }
         }
    
}

function SaveYearState()
{
    var retstr = "";
    for(var year in selectedYears)
    {
        retstr += year + ":" + selectedYears[year] + ",";
    }
    retstr = retstr.substring(0, retstr.length - 1);
    document.getElementById(yearstate).value = retstr;
}

// do something to distinguish the combobox focus
function ComboboxFocus(combobox) {
    combobox.DomElement.style["border"] = "dotted 1px #1e4c79";
}

function ComboboxBlur(combobox) {
    combobox.DomElement.style["border"] = "none";
}

//===========================================================
//
//          508 control functions
//
//===========================================================

function ComboChange508()
{
    //subjCombo508
    var subjCombo = $get(subjCombo508);
    //cohortCombo508
    var cohortCombo = $get(cohortCombo508);

    //writeToWindow(GetSelectedDDLLabel(subjCombo) + "<br>" + GetSelectedDDLLabel(cohortCombo));
    if (GetSelectedDDLLabel(subjCombo) != "select an option" 
        && GetSelectedDDLLabel(cohortCombo) != "select an option")
    {
        //postback
        Postback();
    }

}

function GetSelectedDDLLabel(ddl)
{
    for (var i = 0; i < ddl.length; i++)
    {
        if (ddl[i].selected)
            return ddl[i].text;
    }
    return "not found";
}


//===========================================================
//
//          Reset Function
//
//===========================================================

function ResetClick()
{
    if (confirm('This action will delete all user settings on this page.\n\nChoose OK to continue or Cancel to stop.'))
    {
        var form = document.createElement("form");

            form.method = "post";
            var div = document.createElement("div");
            document.body.appendChild(form);
            var elem = document.createElement("input");
            elem.name = "accessibility";
            elem.type = "hidden";
            elem.value = (accessibleOn) ? "on" : "";
            form.appendChild(elem);
            elem = document.createElement("reset");
            elem.name = "resetselections";
            elem.value = "true";
            form.appendChild(elem);
            form.submit();
 
        return false;
    }
    else
        return false;
}