You might want to attempt a PMU reset. Turn the computer off, then hold the power button for 10 Seconds, it will make a tone(It might not if the volume is muted). then you can turn it on. Also, you can reset the PRAM. Do this by turning the computer on, then immediately holding "Command[Apple]"+"Option"+"P"+"R" until it has chimed 3 times. You mentioned that it would randomly turn off, if this doesn't fix the problem, then your iMac may be suffering from bad capacitors, this plagued many iMac G5's and requires replacing about 25 capacitors on the logic board, or the logic board itself, depending on how repair-savy you are. This is a degenerative problem that starts with random shutdowns, screen distortion, and not starting up, and progress to not powering up at all.