I think you're short an END IF. Last I checked, plpgsql didn't havean "else if" construct, so it wants an END IF to go with each IF.
regards, tom lane