recommended products based on recently viewed
===

I have a php script on a product page that shows the users last 5 viewed products inside a box, and a php script on the same product page that shows 10 random products from all of the scategories that are similar in name to the main product. 

What I would like to do is have the random products based on the recently viewed products instead of product title name and limited to all the products inside the subcategorys of the parent category of the product they are viewing.

Here is the last viewed product code http://pastebin.com/3LrLKHFT and here is the random products code http://pastebin.com/16zy411R

Can anyone help me achieve this?