Take a look at the logic here.
1. if the "login" button (?) was clicked,
2. Else if $ret>0 or userlvl is 1,
3. Else if $ret>0 or userlvl is 2,
4. Else
Do those all make sense together? Not really. What you want is
1. If the "login" button was clicked
and that's it. The stuff about $ret and userlvl happens inside the if. Which means you need another if.