

function toggleAllBoxes(formName, value){

    var form = document.getElementById(formName);
    if(!form)
        return;
        
    for(i = 0; i < form.elements.length; i++){
        if(form.elements[i].type=="checkbox"){
            form.elements[i].checked = value;
        }
    }
}

function updateMasterCheckbox(formName){

    var form = document.getElementById(formName);
    if(!form)
        return;
    
    // assume all are checked
    var flag_all_checked = true;
    var master_box = null;
    
    // try to find an unchecked box
    for(i = 0; i < form.elements.length; i++){
        if(form.elements[i].type=="checkbox" && form.elements[i].id.toLowerCase().indexOf('master') >= 0){
            master_box = form.elements[i];
        }
        else if( form.elements[i].type=="checkbox" && !form.elements[i].checked){
            flag_all_checked = false;
            break;
        }
    }
    
    if(master_box)
        master_box.checked = flag_all_checked;

    return;
}

// Change the Total Selection state
function toggleTotalSelect(listing_id,
                            checked_status,
                            shown_size,
                            total_size){
    var el = document.getElementById('total_select_'+listing_id);
    
    if(!el)
        return;
    
    if(checked_status){
        el.innerHTML = '<span>All '+shown_size+' items on this page are selected. <a href="javascript:totalSelect(\''+listing_id+'\', true, '+total_size+')">Select all '+total_size+' items in the manager</a></span>';
    }else{
        // Uncheck the total selection input
        totalSelect(listing_id, false, total_size);
        toggleAllBoxes('form_'+listing_id, false);
    }
    el.style.display = checked_status ? 'block' : 'none';
}

/**
    This function checks/unchecks the hidden Total Selection input
*/
function totalSelect(listing_id, value, total_size){
    var el = document.getElementById('total_select_'+listing_id);
    var input = document.getElementById('total_select_input_'+listing_id);
    
    if(!el || !input)
        return;
    input.value = value;

    el.innerHTML = '<span>All '+total_size+' items in the manager are selected. <a href="javascript:toggleTotalSelect(\''+listing_id+'\', false, \'\',\'\')">Clear selection</a></span>';

}

