It all looks too interrelated to me to pick out just one spot. You might want to look at this section:
around line #87 to see if fudging that number helps:
However, that's likely to cause an error. The way you're describing things sounds like some of the markup and/or the custom code could be at issue.
Have you looked at the page in a browser and then used the browser's 'view source'? That may show you that the markup is different than expected/required for this script. If so, you can tweak how the page is getting put together.
If it were me, I'd try to get the script working on its own with my desired content first, without anything else involved. Then work at integrating it into a system. That way one can see if the problem is with the script, its implementation, or with its integration into other code.