Here goes:
Enemy Gyms (either other color from your own team)
The enemy Gym, depending on its level, will have a certain number of Pokemon defending it and you can review them all beforehand by swiping. To battle them, you select a team of 6 pokemon. They will pop out in the order of top left first, all the way to bottom right last (that's where you want to put your "ringers," your strongest or type-advantageous pokemon).
If you defeat the Gym you will lower its prestige. Depending on how fortified it was this may or may not have cleared it out. If not, you'll battle again, though if its level went down there will be fewer Pokemon inside. When it is completely demolished, the gym is white and you can install whatever pokemon you like, become Leader, and get the Daily Bonus (go to the shop and click the shield in the top right).
Friendly Gyms (your color)
If a friendly gym is already owned, you'll get options to either train at it or, if there's an open slot, add a Pokemon. The number of slots for Pokemon is determined by the Gym's level. To train, you select one Pokemon. And attempt to fight through all defenders. The defenders won't actually be harmed, and your Pokemon won't faint if you lose (though it will take damage). For this, you want to choose a Pokemon you can win with (you and the gym get nothing if you lose), but the closer in CP to the highest Pokemon in the Gym, the better- especially if you can win with lower. An ideal pokemon for this task is one of the super effective type of the strongest Pokemon in the gym, slightly below that Pokemon in CP.
If you defeat the Gym, you'll gain XP and the Gym gets Prestige. There's a 5 min cooldown on training. With enough Prestige it will level up, thus unlocking a new slot and you can then choose to add a new Pokemon to defend it, and gain access to the Daily Bonus (go to the shop and click the shield in the top right). If the Pokemon you add now has the highest CP of the Gym you become its leader (and the last to be fought when attacked)
--
There's a little bit of a meta in your roster for attacking/defending. When you conquer a gym and place a pokemon inside, it's really tempting to choose your best in an effort to make it hard to retake. But, when you contribute the Pokemon you lose access to it until the Gym is beaten, so you won't have it to attack other Gyms with. Also, certain types are kind of just worth making sure you keep on you for attacking. I have access to a total of one electric type at the moment that is also my strongest, I can't possibly give him away even though he'd stand a really good chance in my local Gyms at the mall.