Just glancing at it the only thing I see maybe is this line:
Code:
<input type="hidden" name="securitytoken" value="$bbuserinfo[securitytoken]" />
you probably need the actual value of the security token in there. When it's in a template it gets 'eval'ed and the value of $bbuserinfo[securitytoken] is inserted, but if you're not doing that in your custom code then you'll have to do it yourself.
Also, IIRC the code for that popup has a javascript function that gets called when the form is submitted which handles the actual file data (in some way I don't really understand, so maybe you've got that covered somewhere else).