That script is a mess! Yuck!
Wish I could jump in with constructive advice but apparently I'm just full of criticism today lol.
So you are simply looking for somehting that allows you to select an itemtype and have everything of that item type in your backpack get toggled as a quest item?