First off your missing the JSON that should be added in the posted code.
Next is the ton load of set var then the messy unset var. you could of used local var
Next you have all that code and not even supporting all the youtube link formats.
I think you should re do this and make sure you post all the needed code for it to work.