﻿function CheckBoxListFilterState() {
    // this is path to GridView control
    this.stateField = arguments[0];
    this.controlPath = arguments[1];
    if(this.stateField)
        this.state = 
            Sys.Serialization.JavaScriptSerializer.deserialize(
                $get(this.stateField).value
                );
    
    // Checks all checkboxes in the grid
    this.CheckAll = function() {
        this.__IterateOverRows(true, false);
        this.UpdateStateField();
    };
    
    // Unchecks all checkboxes in the grid
    this.UnckeckAll = function() {
        this.__IterateOverRows(false, false);
        this.UpdateStateField();
    };
    
    // Inverts checked state for all checkboxes in the grid
    this.InvertAll = function() {
        this.__IterateOverRows(false, true);
        this.UpdateStateField();
    };
    
    // Updates state for single checkbox
    this.UpdateState = function(chk) {
        if(this.state) {
            this.state.CheckBoxStates[chk.attributes.getNamedItem("rowID").value+""] = chk.checked;
        }   
    };
    
    // Serializes state into hidden field
    this.UpdateStateField = function() {
        $get(this.stateField).value = 
            Sys.Serialization.JavaScriptSerializer.serialize(
                this.state
                );
    }
    
    this.__IterateOverRows  = function(checked, invert) {
        var grid = $get(this.controlPath);
        var row; var cell; var i=0;var j=0;
        for(i=0; i<grid.rows.length; i++) {
            row = grid.rows[i];
            cell = row.cells[0];
            var chkChecked = cell.firstChild;
            while(chkChecked) {
                    if(chkChecked.tagName=="INPUT") {
                        if (invert) {
                            chkChecked.checked = !chkChecked.checked;
                        } else {
                            chkChecked.checked = checked;
                        }
                        if(
                            this.state && 
                            chkChecked.attributes && 
                            chkChecked.attributes.getNamedItem("rowID")
                          ) {
                            this.state.CheckBoxStates[chkChecked.attributes.getNamedItem("rowID").value+""] = 
                                chkChecked.checked;
                        }                         
                        break;
                    }
                chkChecked = chkChecked.nextSibling;
            }
        }
    }
}