D&D 3.5e understanding attacks of opportunity

I am currently assisting in the dming of the game as far as understanding rules. in the last game session we played i experianced a AoO for the first time as did the actual dm. A pc(1) was engaged in combat with an enemy another pc(2) standing next to him moved away from that fight does that provoke an attack of opportunity from the enemy. also i understand an AoO to be a free attack so does that mean it doesnt have to roll hit? then one last question in the aforementioned situation if an enemy is engaged with pc(1) and pc(2) attacks enemy does the enemy shift target to pc(2) and does the pc(2) take any negatives for attacking the enemy via melee like a ranged attack would.

thank you for any feed back