oh, I see now where that code meant to go...my bad
I know it's irrelevant now, but the reason you got that error is because in this particular case you have to escape every single-quote in your HTML/JavaScript with a back slash: \'
As of exclude some categories, try replace
if ($bgcounter == 1)
with:
if ($bgcounter == 1 && !in_array($cat_id, array(1,2,3)))
(numbers 1,2,3 are the categories IDs you want to exclude)