I would, in each window, store a index to the window in front of it.
So if you were to click on W2, you should swap the index of W2 and W3, and make W1 point to W3
So its kind of a linked list. If you make it doubly linked (indices to the other dir. too) you could start from the topmost window (perhaps always store the top window index somewhere) and stop on the first window which the mouse is on top of to find the window you click.
If you want to use the same system for buttons and stuff, i would make each of those W's able to contain many same-depth elements (eg. buttons on the same window)
I suggest you also google for how to handle this.
Another way to handle it would be to have a separate list which contains indices to the list of the windows in depth order. This way you dont need the windows to know about their depth.
-List of windows
-List of indices to windows, in depth order
To move a window in depth, you just remove the index, move all the indices above down by 1, and place it at the top. However this requires you to find the window from the depth sorted list first, but if you just used the depth list to find which window you clicked on, you should have that information available.