Danyele,
Be advised that you're not recycling your document object "rep". This will cause a memory leak and might possibly crash your server eventually. There's an example on the XPages Cheatsheet.
I would also recommend moving this code to a function in a Server JavaScript Library. Pass the doc in as a parameter. It's a good practice to use.
Just some thoughts.