On line 327, try adding:
<?php
mysql_data_seek($rsPatterns, 0);
$row_rsPatterns = mysql_fetch_assoc($rsPatterns);
?>
I think the problem is that it doesn't go back to the first record automatically after the loop and since you have one loop nested inside the other it needs to reset after the nested loop completes.