Switch to Mr. Brown and repair the broken wheel. Next build the machine using the smoking red parts. Then use the switch next to the machine.  Now pick up the carrot from the bucket and give it to the donkey.
Get on the donkey and ride it to pull the mechanism on the left. When Sparrow appears hit him with your sword.
The pirate will escape up. Use the bricks from the smashed wagon to rebuild the wall which you can climb.  When you climb up fight with Sparrow - run after him and hit him with your sword.
Escape from the cell
Go to the last cell on the right. When the grille falls down, pick up the bone.  Give it to the dog and enter the vent in the wall on the left side. Push down the beam on the other side.
Put the object on the green floor panel in front of Jack's cell and release him.  Use the dog to dig up the mechanism's element - it is hidden in the last cell. Put the mechanism in the right place and simultaneously activate two winches.
Outside look for the barrel lying upside down. Jump on it and go towards the door. Here put the barrel on the mechanism and roll it till you unblock the passage.  On the beach use Jack's compass to find the treasure.
The treasure is hidden under the wall. You need to use the dog to dig it up and rebuild.  Go left for the barrel and roll it through the just built bridge above the heaps of rubble.
Put the barrel on the mechanism in front of the gate in the courtyard. Go to the wharf and get inside one of the barrels standing there. Head into the water and go towards the cage. 
Next go to the most protruding pier and lift the winch.  Put it a bit higher in the right mechanism and use it.
Jump on the platform and grab the rope.  Activate another mechanism with a character who uses the sword and slide down at the ship's deck. Spin the helm.