diff --git a/Application.hs b/Application.hs
new file mode 100644
--- /dev/null
+++ b/Application.hs
@@ -0,0 +1,80 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+{-# LANGUAGE CPP #-}
+module Application
+    ( makeApplication
+    , getApplicationDev
+    , makeFoundation
+    ) where
+
+import Import
+import Data.Default (def)
+import Yesod.Default.Config
+import Yesod.Default.Main (defaultDevelApp)
+#if MIN_VERSION_fast_logger(2,1,0)
+import Network.Wai.Middleware.RequestLogger
+    ( mkRequestLogger, outputFormat, OutputFormat (..), IPAddrSource (..), destination
+    )
+import qualified Network.Wai.Middleware.RequestLogger as RequestLogger
+import System.Log.FastLogger (newStdoutLoggerSet, defaultBufSize)
+import Network.Wai.Logger (clockDateCacher)
+import Yesod.Core.Types (loggerSet, Logger (Logger))
+#else
+import Network.Wai.Middleware.RequestLogger
+import System.Log.FastLogger (mkLogger)
+import System.IO (stdout)
+#endif
+import System.FilePath ((</>))
+
+-- Import all relevant handler modules here.
+-- Don't forget to add new modules to your cabal file!
+import Handler.Home
+import Handler.Play
+import Handler.Replay
+import Handler.PlaceShips
+import Handler.Rules
+import Handler.About
+import Handler.SaveGame
+
+import Logic.GameExt
+
+mkYesodDispatch "App" resourcesApp
+
+makeApplication :: AppConfig DefaultEnv Extra -> IO Application
+makeApplication conf = do
+    foundation <- makeFoundation conf
+    logWare <- mkRequestLogger def
+        { outputFormat =
+            if development
+            then Detailed True
+            else Apache FromSocket
+#if MIN_VERSION_fast_logger(2,1,0)
+        , destination = RequestLogger.Logger $ loggerSet $ appLogger foundation
+#else
+        , destination = Logger $ appLogger foundation
+#endif
+        }
+    app <- toWaiAppPlain foundation
+    return $ logWare app
+
+makeFoundation :: AppConfig DefaultEnv Extra -> IO App
+makeFoundation conf = do
+#if MIN_VERSION_fast_logger(2,1,0)
+    loggerSet' <- newStdoutLoggerSet defaultBufSize
+    (getter, _) <- clockDateCacher
+
+    let logger = Yesod.Core.Types.Logger loggerSet' getter
+#else
+    logger <- mkLogger True stdout
+#endif
+    s <- staticSite
+    key <- loadKey (extraDataDir (appExtra conf) </> "key.aes")
+    let foundation = App conf s logger key
+    return foundation
+
+-- for yesod devel
+getApplicationDev :: IO (Int, Application)
+getApplicationDev =
+    defaultDevelApp loader makeApplication
+  where
+    loader = Yesod.Default.Config.loadConfig (configSettings Development)
+        { csParseExtra = parseExtra }
diff --git a/Foundation.hs b/Foundation.hs
new file mode 100644
--- /dev/null
+++ b/Foundation.hs
@@ -0,0 +1,112 @@
+{-# LANGUAGE CPP, MultiParamTypeClasses, TypeFamilies #-}
+module Foundation where
+
+import Prelude
+import qualified Codec.Crypto.SimpleAES as AES
+import Logic.GameExt
+import Logic.Types
+import Settings.Development (development)
+import Settings (widgetFile, Extra (..))
+import Settings.StaticFiles
+import Text.Hamlet (hamletFile)
+import Text.Jasmine (minifym)
+import Text.Julius (rawJS)
+import Yesod
+import Yesod.Static
+import Yesod.Default.Config
+import Yesod.Default.Util
+#if MIN_VERSION_fast_logger(2,1,0)
+import Yesod.Core.Types (Logger)
+#else
+import System.Log.FastLogger (Logger)
+#endif
+
+data App = App
+    { settings :: AppConfig DefaultEnv Extra
+    , getStatic :: Static -- ^ Settings for static file serving.
+    , appLogger :: Logger
+    , appKey    :: AES.Key
+    }
+
+-- Set up i18n messages. See the messages folder.
+mkMessage "App" "messages" "en"
+
+mkYesodData "App" $(parseRoutesFile "config/routes")
+
+type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
+
+instance Yesod App where
+    approot = ApprootMaster $ appRoot . settings
+
+    -- REPLACE whole right-hand side by "return Nothing" if no cookies needed;
+    -- (avoids some potential complications, and makes things more efficient)
+    makeSessionBackend _ = return Nothing
+
+    defaultLayout widget = do
+        -- master <- getYesod
+        mmsg <- getMessage
+        messageRender <- getMessageRender
+
+        -- We break up the default layout into two components:
+        -- default-layout is the contents of the body tag, and
+        -- default-layout-wrapper is the entire page. Since the final
+        -- value passed to hamletToRepHtml cannot be a widget, this allows
+        -- you to use normal widget features in default-layout.
+
+        requestedRoute <- getCurrentRoute
+        let 
+            isHome = case requestedRoute of
+                Just HomeR -> True
+                _          -> False
+            isReplay = case requestedRoute of 
+                Just (ReplayR _) -> True
+                _                -> False
+        pc <- widgetToPageContent $ $(widgetFile "default-layout")
+        giveUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
+
+    -- was BottomOfBody: Place Javascript at bottom of the body tag so the rest of the page loads first
+    jsLoader _ = BottomOfHeadBlocking
+
+    -- What messages should be logged. The following includes all messages when
+    -- in development, and warnings and errors in production.
+    shouldLog _ _source level =
+        development || level == LevelWarn || level == LevelError
+
+    makeLogger = return . appLogger
+
+    -- This is done to provide an optimization for serving static files from
+    -- a separate domain. Please see the staticRoot setting in Settings.hs
+    -- urlRenderOverride y (StaticR s) =
+    --     Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
+    -- urlRenderOverride _ _ = Nothing
+
+    -- This function creates static content files in the static folder
+    -- and names them based on a hash of their content. This allows
+    -- expiration dates to be set far in the future without worry of
+    -- users receiving stale content.
+    addStaticContent fileExt mimeType content = do
+        staticContentPath <- fmap extraStaticDir getExtra
+        addStaticContentExternal mini genFileName staticContentPath (StaticR . flip StaticRoute []) fileExt mimeType content
+      where
+        -- Generate a unique filename based on the content itself
+        genFileName = base64md5
+        mini
+            | development = Right 
+            | otherwise   = minifym
+
+
+-- | Can be used instead of defaultLayout for simple pages such as "About".
+plainLayout :: Widget -> Handler Html
+plainLayout widget = do
+  -- master <- getYesod
+  -- mmsg <- getMessage
+  pc <- widgetToPageContent widget
+  giveUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
+
+-- This instance is required to use forms. You can modify renderMessage to
+-- achieve customized and internationalized form validation messages.
+instance RenderMessage App FormMessage where
+    renderMessage _ _ = defaultFormMessage
+
+getExtra :: Handler Extra
+getExtra = fmap (appExtra . settings) getYesod
diff --git a/Handler/About.hs b/Handler/About.hs
new file mode 100644
--- /dev/null
+++ b/Handler/About.hs
@@ -0,0 +1,26 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.About
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Handler for a static page displaying information about the project.
+
+module Handler.About
+  ( getAboutR
+  ) where
+
+import Import
+import Handler.Util
+
+getAboutR :: Handler Html
+getAboutR = do 
+  extra <- getExtra
+  plainLayout $ do 
+    setNormalTitle
+    let 
+      sourceURL = extraSourceURL extra
+      aiURL = extraAIURL extra
+      maxTurns = (extraMaxTurns extra) `div` 2
+      countdownTurns = (extraCountdownTurns extra) `div` 2
+    $(widgetFile "about")
diff --git a/Handler/GameEnded.hs b/Handler/GameEnded.hs
new file mode 100644
--- /dev/null
+++ b/Handler/GameEnded.hs
@@ -0,0 +1,33 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.GameEnded
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Handler for an end screen revealing both boards and informing the user
+-- whether he has lost or won.
+
+module Handler.GameEnded (getGameEndedR, gameEndedView) where
+
+import Import
+import Handler.Util
+import Logic.Game
+import Logic.GameExt
+import Logic.Types
+
+getGameEndedR :: GameStateExt -> Handler Html
+getGameEndedR gameE = withGame gameE $ \game -> gameEndedView game gameE
+
+gameEndedView :: GameState a -> GameStateExt -> Handler Html
+gameEndedView game gameE = do
+  let 
+    remShipsComputer = numRemainingShips $ playerFleet $ otherPlayer game
+    remShipsHuman    = numRemainingShips $ playerFleet $ currentPlayer game
+    timedOut = isTimedOut game
+    humanWon = allSunk (playerFleet $ otherPlayer game) ||
+                 timedOut && remShipsComputer < remShipsHuman
+    drawn    = isDrawn game
+  defaultLayout $ do
+    setNormalTitle
+    $(widgetFile "board")
+    $(widgetFile "gameended")
diff --git a/Handler/Home.hs b/Handler/Home.hs
new file mode 100644
--- /dev/null
+++ b/Handler/Home.hs
@@ -0,0 +1,22 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.Home
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Handler for a static home page.
+
+module Handler.Home
+  ( getHomeR
+  ) where
+
+import Import
+import Handler.Util
+
+getHomeR :: Handler Html
+getHomeR = do
+  extra <- getExtra
+  let defaultOptions = extraOptions extra
+  defaultLayout $ do
+    setNormalTitle
+    $(widgetFile "home")
diff --git a/Handler/PlaceShips.hs b/Handler/PlaceShips.hs
new file mode 100644
--- /dev/null
+++ b/Handler/PlaceShips.hs
@@ -0,0 +1,101 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.PlaceShips
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Handler for a UI for placing the player's ships. The user configures the
+-- fleet placement in a javascript client side UI, which then posts the fleet
+-- JSON encoded to the handler.
+--
+-- Random completion of a fleet is implemented using a POST request
+-- to the 'PlaceShipsRndR' route by the javascript code, which uses 'completeFleet'
+-- to try and complete the player's ship placement.
+
+module Handler.PlaceShips
+  ( getPlaceShipsR
+  , postPlaceShipsR
+  , postPlaceShipsRndR
+  ) where
+
+import           Import
+import           Data.Aeson (encode, decode)
+import           Data.Maybe
+import qualified Data.Text.Encoding as TE
+import           Handler.Util
+import           Handler.Play
+import           Logic.AIUtil
+import           Logic.Game
+import           Logic.DefaultAI
+import           Logic.Binary (fromStrict)
+import           Logic.Types
+
+-------------------------------------------------------------------------------
+-- * Handler
+-------------------------------------------------------------------------------
+
+-- | Displays a client side UI for placing the player's fleet.
+getPlaceShipsR :: Options -> Handler Html
+getPlaceShipsR options = defaultLayout $ do
+  setNormalTitle
+  messageRender <- getMessageRender
+  addScript $ StaticR js_jquery_js
+  addScript $ StaticR js_json2_js
+  addScript $ StaticR js_map_js
+  $(widgetFile "board")
+  $(widgetFile "placeships")
+
+-- | Validates the player's fleet; if it's correct, the game is started.
+postPlaceShipsR :: Options -> Handler Html
+postPlaceShipsR options = do
+  ships <- getPostedFleet
+  case ships of
+    Nothing             -> redirect $ PlaceShipsR options
+    Just fleetPlacement -> startGame options fleetPlacement
+
+-- | Starts a game, given the placement of the player's fleet.
+startGame :: Options -> FleetPlacement -> Handler Html
+startGame Options{..} fleetPlacement = do
+  extra <- getExtra
+  let
+    rules = Rules
+      { rulesAgainWhenHit   = againWhenHit
+      , rulesMove           = move
+      , rulesDifficulty     = difficulty
+      , rulesMaximumTurns   = extraMaxTurns extra
+      , rulesCountdownTurns = extraCountdownTurns extra
+      }
+  game  <- liftIO (newGame rules noviceMode (development && devMode) fleetPlacement HumanPlayer :: IO (GameState DefaultAI))
+  expGameH game >>= playView True game -- redirect . PlayR True
+
+-------------------------------------------------------------------------------
+-- * Random Completion
+-------------------------------------------------------------------------------
+
+-- | POST handler for completing a player's fleet.
+--
+-- Accepts a posted fleet and tries to complete it; if there is a valid
+-- completion, that one is sent back to the UI. Otherwise an empty fleet is
+-- returned in order to indicate that no such completion exists.
+postPlaceShipsRndR :: Handler TypedContent
+postPlaceShipsRndR = do
+  fleet  <- fmap (fromMaybe []) getPostedFleet
+  fleet' <- liftIO $ completeFleet fleet
+  return $ jsonFleet $ fromMaybe [] fleet'
+
+-------------------------------------------------------------------------------
+-- * JSON Fleet Import/Export
+-------------------------------------------------------------------------------
+
+-- | Parses fleet submitted by POST in a field named "fleetData".
+getPostedFleet :: Handler (Maybe FleetPlacement)
+getPostedFleet = do
+  jsonStr <- runInputPost $ ireq textField "fleetData"
+  return $ decode (fromStrict $ TE.encodeUtf8 jsonStr)
+
+-- | Converts a FleetPlacement to JSON data
+jsonFleet :: FleetPlacement -> TypedContent
+jsonFleet
+  = TypedContent typeJson
+  . toContent
+  . encode
diff --git a/Handler/Play.hs b/Handler/Play.hs
new file mode 100644
--- /dev/null
+++ b/Handler/Play.hs
@@ -0,0 +1,156 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.Play
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Handler for playing the battleships game.
+--
+-- Beside the GET handler for displaying the UI, two POST handlers for performing
+-- the two actions of the game (moving and shooting) are provided. After a validation
+-- step, these advance the simulation and redirect the user either to the game UI
+-- again, if the game is still on, or to the game ended screen.
+
+module Handler.Play
+  ( getPlayR
+  , playView
+  , postMoveR
+  , postFireR
+  ) where
+
+import Import
+import Control.Applicative
+import Control.Monad.State
+import Data.List (nub)
+import Data.Map ((!))
+import Data.Serialize (Serialize)
+import Handler.Util
+import Handler.GameEnded
+import Logic.Game
+import Logic.GameExt
+import Logic.Render
+import Logic.Types
+import Text.Julius (rawJS)
+
+-------------------------------------------------------------------------------
+-- * Forms
+-------------------------------------------------------------------------------
+
+-- | A form with two required double fields named "X" and "Y".
+fireForm :: FormInput Handler (Double, Double)
+fireForm = (,) <$> ireq doubleField "X" <*> ireq doubleField "Y"
+
+-- | A form with two optional double fields named "X" and "Y".
+moveForm :: FormInput Handler (Maybe (Double, Double))
+moveForm = liftA2 (liftA2 (,)) (iopt doubleField "X") (iopt doubleField "Y")
+
+-------------------------------------------------------------------------------
+-- * Handler
+-------------------------------------------------------------------------------
+
+-- | Displays the game UI to the user.
+getPlayR :: Bool -> GameStateExt -> Handler Html
+getPlayR firstContact gameE = withGame gameE $ \game -> playView firstContact game gameE
+
+playView :: Bool -> GameState a -> GameStateExt -> Handler Html
+playView firstContact game@GameState{..} gameE = defaultLayout $ do
+  setNormalTitle
+  addScript $ StaticR js_jquery_js
+  messageRender <- getMessageRender
+  let remTurns = remainingTurns game `div` 2
+  let showAlert = firstContact && isCountdownStart game
+  $(widgetFile "board")
+  $(widgetFile "play")
+
+-- | Handles a request to move one of the player's ships.
+postMoveR :: GameStateExt -> Handler Html
+postMoveR gameE = withGame gameE $ \game -> case expectedAction game of
+  ActionFire -> invalidMove game gameE
+  ActionMove -> do
+    mpos <- runInputPost moveForm
+    case mpos of 
+      Just (x, y) -> case fieldPos (x,y) of
+        -- invalid click
+        Nothing  -> invalidMove game gameE
+        -- valid click
+        Just pos ->
+          let humanFleet = playerFleet $ currentPlayer game
+          in case desiredMove pos humanFleet of
+              Just (ship,movement) 
+                | isMovable movement humanFleet (humanFleet!ship)
+                  -> performMove game (Just pos)
+              _   -> invalidMove game gameE
+      -- player skips moving
+      _ -> performMove game Nothing
+  where
+    performMove game pos = do
+      game' <- execStateT (moveHuman pos >>= executeMove) game
+      performAI game'
+
+-- | Handles a request to fire at an enemy position.
+postFireR :: GameStateExt -> Handler Html
+postFireR gameE = withGame gameE $ \game -> do
+  (x,y) <- runInputPost fireForm
+  case fieldPos (x,y) of
+    -- invalid click
+    Nothing  -> invalidMove game gameE
+    -- valid click
+    Just pos -> case expectedAction game of
+      ActionMove -> invalidMove game gameE
+      ActionFire -> do
+        (result, game') <- runStateT (humanTurnFire pos) game
+        -- evaluate outcome
+        case result of
+          Over  -> gameEnded game'
+          -- shoot again. expectedAction has not changed
+          Again -> continue False game'
+          -- either perform AI turn or let human move
+          Next
+            | expectedAction game' == ActionMove -> continue False game'
+            | otherwise -> performAI game'
+
+-- | A widget that displays a table showing which ships of the opponent are remaining.
+shipsOpponentWidget :: GameState a -> Orientation -> WidgetT App IO ()
+shipsOpponentWidget game orientation =
+  let sizes = sizesOfShips $ unsunkShips $ playerFleet $ otherPlayer game
+  in $(widgetFile "shipsOpponent")
+
+-- | A widget that renders the legend in the given orientation.
+legendWidget :: Orientation -> Bool -> Widget
+legendWidget orientation movesAllowed = $(widgetFile "legend")
+
+-------------------------------------------------------------------------------
+-- * Redirections
+-------------------------------------------------------------------------------
+
+-- | Redirects to the game UI in case of an invalid move.
+invalidMove :: GameState a -> GameStateExt -> Handler Html
+invalidMove = playView False -- \_ -> redirect . PlayR False
+
+-- | Redirects to the game ended screen.
+gameEnded :: (Serialize a, AI a) => GameState a -> Handler Html
+gameEnded game = expGameH game >>= gameEndedView game -- redirect . GameEndedR
+
+-- | Redirects to the game UI in case the game is still on.
+continue :: (Serialize a, AI a) => Bool -> GameState a -> Handler Html
+continue firstContact game = expGameH game >>= playView firstContact game -- redirect . PlayR firstContact
+
+-------------------------------------------------------------------------------
+-- * AI
+-------------------------------------------------------------------------------
+
+-- | Performs the AI actions.
+performAI :: (Serialize a, AI a) => GameState a -> Handler Html
+performAI game = do
+  (result, game') <- liftIO $ runStateT aiTurn game
+  case result of
+    Over  -> gameEnded game'
+    Next  -> continue True game'
+    Again -> error "impossible. `Again` is handled by aiTurn"
+
+-- | Determines whether the countdown should already be shown.
+-- Should be shown when at most countdownTurns turns remain.
+showCountdown :: GameState a -> Bool
+showCountdown game = remTurns <= cdTurns where
+  remTurns = remainingTurns game 
+  cdTurns = rulesCountdownTurns . gameRules $ game
diff --git a/Handler/Replay.hs b/Handler/Replay.hs
new file mode 100644
--- /dev/null
+++ b/Handler/Replay.hs
@@ -0,0 +1,134 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.Replay
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Handler for displaying a replay of the game.
+
+module Handler.Replay
+  ( getReplayR
+  ) where
+
+import           Import
+import           Prelude (last)
+import           Control.Monad.State
+import qualified Data.Map (lookup)
+import           Handler.Util
+import           Logic.Game
+import           Logic.GameExt
+import           Logic.Render
+import           Logic.Types
+
+getReplayR :: GameStateExt -> Handler Html
+getReplayR gameE = withGame gameE $ \game -> defaultLayout $ do
+  messageRender <- getMessageRender -- needed for i18n in julius
+  let rules       = gameRules game
+      history     = zip [0 :: Int ..] $ reconstructHistory game
+      humanGrids  = map (renderHumanGrid rules) history
+      aiGrids     = map (renderAIGrid rules) history
+      numSteps    = length history
+  setNormalTitle
+  addScript $ StaticR js_jquery_js
+  $(widgetFile "board")
+  $(widgetFile "replay") where
+    renderHumanGrid rules (time, (humansState, aisState)) = (time, renderSvgHtml $
+      renderPlayerGrid (playerFleet humansState) (playerShots aisState) ActionFire rules time)
+    renderAIGrid rules (time, (humansState, aisState)) = renderHumanGrid rules (time, (aisState, humansState))
+
+-- | Generate all the player states leading up to the current game situation.
+-- Given a game state, this function generates a list of pairs of PlayerStates
+-- (one for the human player, one for the AI player) which are "snapshots" of
+-- previous game states. A snapshot is taken whenever `turnNumber` increases.
+reconstructHistory :: GameState a -> [(PlayerState, PlayerState)]
+reconstructHistory g = evalState (reconstructAndCheck g) initialGameState where
+  initialGameState = GameState
+    { currentPlayer  = humanPlayer
+    , otherPlayer    = aiPlayer
+    , aiState        = undefined
+    , gameRules      = gameRules g
+    , noviceModeOpt  = undefined
+    , devModeOpt     = undefined
+    , expectedAction = ActionFire
+    , turnNumber     = 0
+    }
+  humanPlayer = let s = humanPlayerState g
+                in s { playerShots = []
+                     , playerFleet = reconstructOriginalFleet (playerMoves s) (playerFleet s)
+                     , playerMoves = []
+                     }
+  aiPlayer    = let s = aiPlayerState g
+                in s { playerShots = []
+                     , playerFleet = reconstructOriginalFleet (playerMoves s) (playerFleet s)
+                     , playerMoves = []
+                     }
+
+-- | Reconstruct game history given the current game state and check for consistency.
+reconstructAndCheck :: MonadState (GameState a) m =>GameState a -> m [(PlayerState, PlayerState)]
+reconstructAndCheck g = do
+  let hsExpected = humanPlayerState g
+      asExpected = aiPlayerState g
+  history <- reconstruct -- player shots are reversed as they are originally sorted from most recent to oldest
+    (reverse . playerShots $ humanPlayerState g, reverse . playerMoves $ humanPlayerState g)
+    (reverse . playerShots $ aiPlayerState g, reverse . playerMoves $ aiPlayerState g)
+  let (hs, as) = last history
+  if as /= asExpected || hs /= hsExpected
+    then error "Replay preparation: Game reconstruction unsuccessful. This shouldn't happen!"
+    else return history
+
+-- | Reconstruct the game history given the player's actions.
+reconstruct :: MonadState (GameState a) m
+   => (TrackingList, [ShipMove]) -- ^ current player's actions
+   -> (TrackingList, [ShipMove]) -- ^ other players's actions
+   -> m [(PlayerState, PlayerState)] -- ^ list of pairs of PlayerStates for every previous game situation
+reconstruct ([], _) _ = do
+  humansState <- gets humanPlayerState
+  aisState    <- gets aiPlayerState
+  return [(humansState, aisState)]
+reconstruct (fstPShots, fstPMoves) sndPState = do
+  humansState <- gets humanPlayerState
+  aisState    <- gets aiPlayerState
+  fstPShots'  <- execShots fstPShots
+  fstPMoves'  <- execMove  fstPMoves
+  switchRoles
+  states      <- reconstruct sndPState (fstPShots', fstPMoves')
+  return $ (humansState, aisState) : states
+
+execShots :: MonadState (GameState a) m => [Shot] -> m [Shot]
+execShots []           = return []
+execShots (shot:shots) = do
+  time <- gets turnNumber
+  if shotTime shot == time
+    then
+      fireAt (shotPos shot)
+        >>= executeShot
+        >>  execShots shots
+    else return $ shot:shots
+
+execMove :: MonadState (GameState a) m => [ShipMove] -> m [ShipMove]
+execMove []           = return []
+execMove (move:moves) = do
+  time <- gets turnNumber
+  case move of
+    ShipMove mId mDir mTime | time == mTime
+      -> executeMove (Just (mId, mDir)) >> return moves
+    _ -> return $ move:moves
+
+-- | Reconstruct the original fleet given the moves performed.
+reconstructOriginalFleet :: [ShipMove] -> Fleet -> Fleet
+reconstructOriginalFleet moves = undoMoves moves . unsinkFleet
+
+unsinkFleet :: Fleet -> Fleet
+unsinkFleet = fmap unsinkShip where
+  unsinkShip s = s { shipDamage = fmap (const $ Time Nothing) $ shipDamage s }
+
+undoMoves :: [ShipMove] -> Fleet -> Fleet
+undoMoves ms fleet = foldl undo fleet ms where
+  undo f m = case Data.Map.lookup (shipMoveID m) f of
+    Just ship -> uncheckedMoveShip ship (reverseDirection $ shipMoveDirection m) f
+    Nothing   -> error "Replay preparation: Irreversible ship movement. This shouldn't happen!"
+
+reverseDirection :: Movement -> Movement
+reverseDirection m = case m of
+  Forward  -> Backward
+  Backward -> Forward
diff --git a/Handler/Rules.hs b/Handler/Rules.hs
new file mode 100644
--- /dev/null
+++ b/Handler/Rules.hs
@@ -0,0 +1,61 @@
+-------------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.Rules
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Handler for page that allows the user to customize the game's rules.
+
+module Handler.Rules 
+  ( getRulesR
+  , postRulesR
+  ) where
+
+import Import
+import Data.Maybe
+import Handler.Util
+import Logic.Types
+
+-------------------------------------------------------------------------------
+-- * Handler
+-------------------------------------------------------------------------------
+
+-- | Handler for the rule configuration page.
+getRulesR :: Handler Html
+getRulesR = do
+  extra <- getExtra
+  let defaultOptions = extraOptions extra
+  defaultLayout $ do
+    setNormalTitle
+    $(widgetFile "rules")
+
+-- | Handler to accept the configured game rules.
+postRulesR :: Handler Html
+postRulesR = do
+  rules <- runInputPost rulesForm
+  redirect $ PlaceShipsR rules
+
+-------------------------------------------------------------------------------
+-- * Forms
+-------------------------------------------------------------------------------
+
+rulesForm :: FormInput Handler Options
+rulesForm = Options
+  <$> (fromMaybe False <$> iopt boolField "againWhenHit")
+  <*> (fromMaybe False <$> iopt boolField "move")
+  <*> (fromMaybe False <$> iopt boolField "noviceMode")
+  <*> (fromMaybe False <$> iopt boolField "devMode")
+  <*> (fromMaybe Hard  <$> iopt (selectFieldList difficultyList) "difficulty")
+
+difficultyList :: [(AppMessage, DifficultyLevel)]
+difficultyList =
+  [ (MsgInputDifficultyHard, Hard)
+  , (MsgInputDifficultyMedium, Medium)
+  , (MsgInputDifficultyEasy, Easy)
+  ]
+
+indexedDifficultyList :: [(Int, (AppMessage, DifficultyLevel))]
+indexedDifficultyList = zip [1 ..] difficultyList
+
+indexOfDifficulty :: DifficultyLevel -> Int
+indexOfDifficulty difficulty = fromJust . lookup difficulty $ map (\(i,(_,d)) -> (d,i-1)) indexedDifficultyList
diff --git a/Handler/SaveGame.hs b/Handler/SaveGame.hs
new file mode 100644
--- /dev/null
+++ b/Handler/SaveGame.hs
@@ -0,0 +1,20 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.SaveGame
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Handler for a page displaying the link that leads to the current game state.
+
+module Handler.SaveGame
+  ( getSaveGameR
+  ) where
+
+import Import
+import Handler.Util
+import Logic.GameExt
+
+getSaveGameR :: GameStateExt -> Handler Html
+getSaveGameR gameE = withGame gameE $ \game -> plainLayout $ do
+    setNormalTitle
+    $(widgetFile "savegame")
diff --git a/Handler/Util.hs b/Handler/Util.hs
new file mode 100644
--- /dev/null
+++ b/Handler/Util.hs
@@ -0,0 +1,153 @@
+-------------------------------------------------------------------------------
+-- |
+-- Module      :  Handler.Util
+-- Stability   :  experimental
+-- Portability :  portable
+--
+-- Several utilities for the handlers of this package.
+{-# LANGUAGE CPP #-}
+module Handler.Util
+  ( withGame
+  , fieldPos
+  , setNormalTitle
+  , legendStatic
+  , timedLegendStatic
+  , gridStatic
+  , impGameH
+  , expGameH
+  , renderDiaSVG
+  , renderSvgHtml
+  , playerGridHtml
+  , enemyGridHtml
+  ) where
+
+import Import
+import Data.Maybe
+import Data.Serialize (Serialize)
+import Data.Text.Lazy (toStrict)
+import Data.Text as T
+import Diagrams.Prelude
+import Diagrams.Backend.SVG
+import Logic.DefaultAI
+import Logic.GameExt
+import Logic.Render
+import Logic.Types
+import Text.Blaze.Svg.Internal (Svg)
+import Text.Blaze.Svg.Renderer.Text (renderSvg)
+import Yesod.Routes.Class
+
+-------------------------------------------------------------------------------
+-- * Game Import/Export
+-------------------------------------------------------------------------------
+
+-- | Imports a game state in the Handler monad.
+impGameH :: Serialize a => GameStateExt -> Handler (Either String (GameState a))
+impGameH game = do
+  key <- appKey <$> getYesod
+  return $ impGame key game
+
+-- | Exports a game state in the Handler monad.
+expGameH :: Serialize a => GameState a -> Handler GameStateExt
+expGameH game = do
+  key <- appKey <$> getYesod
+  expGame key game
+
+-- | Bracket for actions in the Handler monad that require the game state.
+withGame :: GameStateExt -> (GameState DefaultAI -> Handler a) -> Handler a
+withGame gameE act = impGameH gameE >>= \g -> case g of
+  Left _     -> redirect HomeR
+  Right game -> act game
+
+-------------------------------------------------------------------------------
+-- * Static routes
+-------------------------------------------------------------------------------
+
+-- | Static route for the specified legend icon.
+legendStatic :: LegendIcon -> Route App
+legendStatic ico = StaticR $ case ico of
+  LIShipWithArrow -> img_LIShipWithArrow_svg
+  LIShipMovable   -> img_LIShipMovable_svg
+  LIShipImmovable -> img_LIShipImmovable_svg
+  LIShipHit       -> img_LIShipHit_svg
+  LIShipSunk      -> img_LIShipSunk_svg
+  LIFogOfWar      -> img_LIFogOfWar_svg
+  LIWater         -> img_LIWater_svg
+  LILastShot      -> img_LILastShot_svg
+
+-- | Static route for the specified time-dependent icon.
+timedLegendStatic :: TimedLegendIcon -> Route App
+timedLegendStatic ico = StaticR $ case ico of
+  TLIWater 0   -> img_TLIWater_0_svg
+  TLIWater 5   -> img_TLIWater_5_svg
+  TLIWater 10  -> img_TLIWater_10_svg
+  TLIWater 15  -> img_TLIWater_15_svg
+  TLIWater 20  -> img_TLIWater_20_svg
+  TLIMarker 0  -> img_TLIMarker_0_svg
+  TLIMarker 5  -> img_TLIMarker_5_svg
+  TLIMarker 10 -> img_TLIMarker_10_svg
+  TLIMarker 15 -> img_TLIMarker_15_svg
+  TLIMarker 20 -> img_TLIMarker_20_svg
+  _            -> img_LIFogOfWar_svg
+
+-- | Static route for the grid.
+gridStatic :: Route App
+gridStatic = StaticR img_grid_svg
+
+-------------------------------------------------------------------------------
+-- * Misc
+-------------------------------------------------------------------------------
+
+-- | Converts coordinates in the grid SVG to a field position.
+fieldPos :: (Double, Double) -> Maybe Pos
+fieldPos p = listToMaybe $ sample renderReferenceGrid $ p2 p
+
+-- | Set a default html title.
+setNormalTitle :: Widget 
+setNormalTitle = setTitleI MsgGameName
+
+-- | Renders the player grid as inline SVG for HTML
+playerGridHtml :: GameState a -> Action -> Html
+playerGridHtml (GameState {..}) requiredAction
+  = renderSvgHtml
+  $ renderPlayerGrid
+    (playerFleet currentPlayer)
+    (playerShots otherPlayer)
+    requiredAction
+    gameRules
+    turnNumber
+
+-- | Renders the enemy grid as inline SVG for HTML
+enemyGridHtml :: GameState a -> Bool -> Html
+enemyGridHtml (GameState {..}) uncoverFleet
+  = renderSvgHtml
+  $ renderEnemyGrid
+    (playerFleet otherPlayer)
+    (playerShots currentPlayer)
+    gameRules
+    noviceModeOpt
+    turnNumber
+    (uncoverFleet || devModeOpt)
+
+-- | Renders a diagram as an SVG text.
+--
+-- Uses breakOn to omit doctype and xml declaration, so the text can
+-- be embedded in HTML. TODO: Is there a less hacky way to do that?
+
+renderSvgHtml :: (Semigroup m, Monoid m) => QDiagram SVG R2 m -> Html
+renderSvgHtml
+  = preEscapedToMarkup
+  . snd
+  . T.breakOn "<svg xmlns="
+  . toStrict
+  . renderSvg
+  . renderDiaSVG
+
+-- | Renders a diagram to SVG
+renderDiaSVG :: (Monoid m, Semigroup m) =>
+                QDiagram SVG R2 m -> Text.Blaze.Svg.Internal.Svg
+renderDiaSVG =
+#if MIN_VERSION_diagrams_svg(0,8,0)
+  renderDia SVG (SVGOptions Absolute Nothing)
+#else
+  renderDia SVG (SVGOptions Absolute)
+#endif
diff --git a/Import.hs b/Import.hs
new file mode 100644
--- /dev/null
+++ b/Import.hs
@@ -0,0 +1,19 @@
+module Import
+    ( module Import
+    ) where
+
+import Prelude              as Import hiding (head, init, last,
+                                       readFile, tail, writeFile)
+import Yesod                as Import hiding (Route (..))
+
+import Control.Applicative  as Import (pure, (<$>), (<*>))
+import Data.Text            as Import (Text)
+
+import Foundation           as Import
+import Settings             as Import
+import Settings.Development as Import
+import Settings.StaticFiles as Import
+
+import Data.Monoid          as Import
+                                       (Monoid (mappend, mempty, mconcat),
+                                       (<>))
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,24 @@
+Copyright (c) 2014, Meike Grewing, Lukas Heidemann, Fabian Thorand, Fabian Zaiser
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+    * Neither the name of the <organization> nor the
+      names of its contributors may be used to endorse or promote products
+      derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Logic/AIUtil.hs b/Logic/AIUtil.hs
new file mode 100644
--- /dev/null
+++ b/Logic/AIUtil.hs
@@ -0,0 +1,177 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.AIUtil
+-- Stability   :  experimental
+-- Portability :  portable
+--
+-- Utilities for the enemy AI.
+
+module Logic.AIUtil
+  (
+  -- * Type Synonyms
+    Score
+  , ScoreGrid
+  , TrackingGrid
+  -- * Grid Functions
+  , isHit
+  , isHitOrSunk
+  , isWater
+  -- * Ship Functions
+  , completeFleet
+  -- * Helper Functions
+  , fromBool
+  , maximum'
+  -- * Debugging Functions
+  , showFleet
+  , showFleetPlacement
+  , showPositions
+  , showScoreGrid
+  , showTracking
+  , showTrackingList
+  ) where
+
+import           Prelude
+import           Control.Monad
+import           Control.Monad.Trans
+import           Control.Monad.Trans.List
+import           Control.Monad.Random
+import           Data.Array
+import           Data.List
+import qualified Data.Map as Map
+import           Data.Maybe (listToMaybe)
+import           Logic.Util
+import           Logic.Game
+import           Logic.Random
+import           Logic.Types
+import           Text.Printf
+
+--------------------------------------------------------------------------------
+-- * Data types
+--------------------------------------------------------------------------------
+
+type Score = Double
+type ScoreGrid = Array Pos Score
+
+-- | A grid where the results of shots are tracked.
+type TrackingGrid = Grid (Maybe HitResponse)
+
+--------------------------------------------------------------------------------
+-- * Placing ships
+--------------------------------------------------------------------------------
+
+-- | Random completion of a given fleet, if one exists.
+completeFleet :: MonadRandom m => FleetPlacement -> m (Maybe FleetPlacement)
+completeFleet fleet = do
+  let ships' = reverse fleetShips \\ fmap shipSize fleet
+  fleets <- runRandM $ runListT $ foldM completeFleet' fleet ships'
+  return $ listToMaybe fleets
+
+-- | Helper for 'completeFleet'.
+completeFleet'
+  :: RandomGen g
+  => FleetPlacement
+  -> Int
+  -> ListT (Rand g) FleetPlacement
+
+completeFleet' fleet len = do
+  let admissible = admissibleShips fleet len
+  shuffled  <- lift $ shuffleRandom admissible
+  placement <- choose shuffled
+  return $ placement : fleet
+
+-- | Calculates all possible placements for a ship of the given length.
+admissibleShips :: FleetPlacement -> Int -> [ShipShape]
+admissibleShips fleet len = do
+  let (w, h) = boardSize
+  x <- [0 .. w - 1]
+  y <- [0 .. h - 1]
+  o <- [Horizontal, Vertical]
+  let ship = ShipShape (x, y) len o
+  guard $ shipAdmissible fleet ship
+  return ship
+
+--------------------------------------------------------------------------------
+-- * Hit Response
+--------------------------------------------------------------------------------
+
+isHit :: Maybe HitResponse -> Bool
+isHit (Just Hit) = True
+isHit _          = False
+
+isSunk :: Maybe HitResponse -> Bool
+isSunk (Just Sunk) = True
+isSunk _           = False
+
+isWater :: Maybe HitResponse -> Bool
+isWater (Just Water) = True
+isWater _            = False
+
+isHitOrSunk :: Maybe HitResponse -> Bool
+isHitOrSunk h = isSunk h || isHit h  -- equivalent: isJust h && not (isWater h)
+
+--------------------------------------------------------------------------------
+-- * Misc
+--------------------------------------------------------------------------------
+
+-- | Lift a list into a 'MonadPlus'.
+choose :: MonadPlus m => [a] -> m a
+choose = msum . fmap return
+
+-- | Bool to numeric.
+fromBool :: Num a => Bool -> a
+fromBool True  = 1
+fromBool False = 0
+
+-- | Maximum function for nonnegative numbers which handles empty lists.
+maximum' :: (Ord a, Num a) => [a] -> a
+maximum' [] = 0
+maximum' xs = maximum xs
+
+--------------------------------------------------------------------------------
+-- * Debugging
+--------------------------------------------------------------------------------
+
+showPositions :: Int -> Int -> [Pos] -> String
+showPositions width height ps = concat
+  [(if (x,y) `elem` ps then "X" else " ")
+  ++ (if x == width - 1 then "\n" else "")
+  | y <- [0..height - 1]
+  , x <- [0..width - 1]
+  ]
+
+showScoreGrid :: ScoreGrid -> String
+showScoreGrid grid = concat
+  [ printf "%6.2f" (grid ! (x,y))
+  ++ (if x == width' then "\n" else "|")
+  | y <- [0..height']
+  , x <- [0..width']
+  ] where
+    ((0,0), (width', height')) = bounds grid
+
+showTracking :: TrackingGrid -> String
+showTracking grid = concat
+  [(case grid ! ((x,y) :: Pos) of
+      Nothing -> " "
+      Just Water -> "~"
+      Just Hit -> "H"
+      Just Sunk -> "S")
+  ++ (if x == width' then "\n" else "")
+  | y <- [0..height']
+  , x <- [0..width']
+  ] where
+    ((0,0), (width', height')) = bounds grid
+
+showTrackingList :: TrackingList -> String
+showTrackingList list = showTracking . buildArray ((0,0), (fst boardSize - 1, snd boardSize - 1)) $
+  \pos -> shotResult `fmap` find ((== pos) . shotPos) list
+
+showFleetPlacement :: FleetPlacement -> String
+showFleetPlacement fleet = tail $ concat
+  [ (if x == 0 then "\n" else "") ++
+    (if not . null . shipsAt fleet $ (x,y) then "O" else "~")
+  | y <- [0..height - 1]
+  , x <- [0..width - 1]
+  ] where (width, height) = boardSize
+
+showFleet :: Fleet -> String
+showFleet = showFleetPlacement . map shipShape . Map.elems
diff --git a/Logic/Binary.hs b/Logic/Binary.hs
new file mode 100644
--- /dev/null
+++ b/Logic/Binary.hs
@@ -0,0 +1,129 @@
+{-# LANGUAGE CPP #-}
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.Binary
+-- Stability   :  experimental
+-- Portability :  portable
+--
+-- Import/export for binary serializable data to text URLs.
+
+module Logic.Binary
+  ( -- * Import/Export
+    impBinary
+  , expBinary
+    -- * Misc
+  , fromStrict
+  , toStrict
+    -- * General Serialization Helpers
+  , getEnum8
+  , getIntegral8
+  , getList8
+  , putEnum8
+  , putIntegral8
+  , putList8
+  ) where
+
+import           Prelude
+import           Control.Applicative
+import           Control.Monad
+import           Data.Serialize.Get
+import           Data.Serialize.Put
+import           Data.Text (Text)
+import qualified Data.Text.Encoding          as TE
+import qualified Data.ByteString             as BS
+import qualified Data.ByteString.Lazy        as BL
+import qualified Data.ByteString.Base64.Lazy as B64
+
+--------------------------------------------------------------------------------
+-- * Import/Export
+--------------------------------------------------------------------------------
+
+-- | Imports a byte string from text.
+impBinary :: Text -> Maybe BL.ByteString
+impBinary
+  = eitherToMaybe
+  . B64.decode
+  . fromStrict
+  . fromBase64Url
+  . TE.encodeUtf8
+
+-- | Exports a byte string to text.
+expBinary :: BL.ByteString -> Text
+expBinary
+  = TE.decodeUtf8
+  . toBase64Url
+  . toStrict
+  . B64.encode
+
+--------------------------------------------------------------------------------
+-- * URL
+--
+-- Some characters used in base 64 encoding are problematic when used in URLs.
+-- These functions convert from and into a representation in which these
+-- characters are replaced with non problematic ones, using "base64url" 
+-- according to RFC 4648 (http://tools.ietf.org/html/rfc4648).
+--------------------------------------------------------------------------------
+
+toBase64Url :: BS.ByteString -> BS.ByteString
+toBase64Url = BS.map convert where
+  convert 43 = 45 -- '+' --> '-'
+  convert 47 = 95 -- '/' --> '_'
+  convert  x =  x
+
+fromBase64Url :: BS.ByteString -> BS.ByteString
+fromBase64Url = BS.map convert where
+  convert 45 = 43 -- '+' <-- '-'
+  convert 95 = 47 -- '/' <-- '_'
+  convert  x =  x
+
+--------------------------------------------------------------------------------
+-- * Misc
+--------------------------------------------------------------------------------
+
+eitherToMaybe :: Either a b -> Maybe b
+eitherToMaybe e = case e of
+  Right x -> Just x
+  _       -> Nothing
+
+#if MIN_VERSION_bytestring(0,10,0)
+toStrict :: BL.ByteString -> BS.ByteString
+toStrict = BL.toStrict
+
+fromStrict :: BS.ByteString -> BL.ByteString
+fromStrict = BL.fromStrict
+#else
+toStrict :: BL.ByteString -> BS.ByteString
+toStrict = BS.concat . BL.toChunks
+
+fromStrict :: BS.ByteString -> BL.ByteString
+fromStrict = BL.fromChunks . (:[])
+#endif
+
+-------------------------------------------------------------------------------
+-- * General Serialization Helpers
+--
+-- These functions serialize Enums with up to 255 values, integrals in the
+-- range from 0 to 255 and lists with at most 255 items. These constraints
+-- are not enforced, so usage of these functions may be unsafe.
+-------------------------------------------------------------------------------
+
+putEnum8 :: Enum a => Putter a
+putEnum8 = putWord8 . fromIntegral . fromEnum
+
+getEnum8 :: Enum a => Get a
+getEnum8 = toEnum . fromIntegral <$> getWord8
+
+putIntegral8 :: Integral a => Putter a
+putIntegral8 = putWord8 . fromIntegral
+
+getIntegral8 :: Integral a => Get a
+getIntegral8 = fromIntegral <$> getWord8
+
+putList8 :: Putter a -> Putter [a]
+putList8 pel xs = do
+  putIntegral8 $ length xs
+  forM_ xs pel
+
+getList8 :: Get a -> Get [a]
+getList8 gel = getIntegral8 >>= getList where
+  getList len = replicateM len gel
diff --git a/Logic/CleverAI.hs b/Logic/CleverAI.hs
new file mode 100644
--- /dev/null
+++ b/Logic/CleverAI.hs
@@ -0,0 +1,389 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.Binary
+-- Stability   :  experimental
+-- Portability :  non-portable
+--
+-- Clever AI for battleships that supports moving ships.
+--
+-- Firing shots:
+-- 
+-- Blocked cells:
+-- Each square is assigned a probability to be blocked (i.e. being part of no ship).
+-- For example if we just hit a water cell, we know it's blocked. (Probablity 1)
+-- But after some time a ship can move there, so this probability declines over time.
+-- (modeled as exponential decay.)
+-- 
+-- Immovable ships:
+-- For each position, we count how many ships this square can be part of. We only
+-- consider ships which are not ruled out by to the AI's information about the
+-- situation. Hit ships are weighted higher => We try to sink ships as fast as
+-- possible. (This is not the case for movable ships!)
+-- 
+-- Movable ships:
+-- There are 2 phases. In the first one, the AI follows a checkerboard pattern to
+-- hit (not sink!) as many ships as possible to immobilize them.
+-- 
+-- After a certain time has passed or enough ships have been hit, we move on to
+-- phase 2.
+-- 
+-- Now that we have (hopefully) hit all ships, we sink them (essentially) according
+-- to the strategy for immovable ships.
+-- (However, a checkerboard pattern isn't useful now.)
+--
+-- Both movable and immovable ships:
+-- Positions at the edge of the board naturally allow fewer ships to pass through
+-- them. But the AI shouldn't be a bias towards the center, so the scores are divided
+-- by the scores at the beginning of the game.
+-- 
+-- Finally: Some randomness is added to the scores. The amount of randomness depends
+-- on the selected difficulty level.
+-- The highest scoring position is then chosen.
+
+module Logic.CleverAI 
+  ( CleverAI
+  ) where
+
+import           Prelude
+import           Control.Applicative
+import           Control.Monad.Random
+import           Control.Monad.Reader
+import           Control.Monad.State
+import           Data.Array
+import qualified Data.Foldable as Foldable
+import           Data.List ((\\), elemIndex, intersect, delete)
+import qualified Data.Map as Map
+import           Data.Maybe (fromMaybe, fromJust)
+import           Data.Serialize (Serialize)
+import qualified Data.Serialize as S
+import           Logic.Util
+import           Logic.AIUtil
+import           Logic.Binary
+import           Logic.Game
+import           Logic.Random
+import           Logic.Types
+
+data CleverAI = CleverAI
+  { rules            :: Rules        -- ^ rules of this game
+  , tracking         :: TrackingGrid -- ^ stores what was hit the last time at each position
+  , shots            :: [Pos]        -- ^ AI's previous shots
+  , sunk             :: [ShipShape]  -- ^ ships of the user's fleet that are already sunk
+  , sunkTime         :: [Int]        -- ^ what was the number of shots fired when the respective ship was sunk
+  , curTurnNumber    :: Int          -- ^ approximate (maybe off by 1) turn number only in movable mode
+  , checkerboardEven :: Bool
+  }
+
+-- | Constructs an initial AI instance.
+cleverAI :: Rules -> Bool -> CleverAI
+cleverAI r checkerboardEven = CleverAI
+  { rules            = r
+  , tracking         = newGrid boardSize Nothing
+  , shots            = []
+  , sunk             = []
+  , sunkTime         = []
+  , curTurnNumber    = 0
+  , checkerboardEven = checkerboardEven
+  }
+
+instance AI CleverAI where
+  aiInit r = do
+    fleet <- liftM fromJust $ completeFleet []
+    checkerboardEven <- getRandom
+    return (cleverAI r checkerboardEven, fleet)
+  aiFire         = liftM maximumIx $ scoreGrid >>= randomize
+  aiResponse p r = modify (cleverResponse p r)
+  aiMove fleet _ = do
+    modify increaseTurnNumber
+    move <- chooseRandom $
+      [ (shipID ship, mvmt)
+      | ship <- Map.elems fleet
+      , mvmt <- [Forward, Backward]
+      , isMovable mvmt fleet ship
+      ]
+    rand <- getRandomR (0.0, 1.0)
+    return $ if rand < probMove then move else Nothing
+   where
+      -- curTurnNumber is only increased in aiMove which is invoked every other turn,
+      -- so we increase the number by 2. So this number may be off by 1, but fixing this
+      -- isn't worth the effort. (Because curTurnNumber is only needed to decide whether
+      -- one switches to phase 2 in movable mode.)
+      increaseTurnNumber ai@CleverAI{..} = ai { curTurnNumber = curTurnNumber + 2 }
+
+-- | How often should the AI use its right to move?
+probMove :: Double
+probMove = 0.5
+
+cleverResponse :: Pos -> HitResponse -> CleverAI -> CleverAI
+cleverResponse p r ai = case r of
+  Sunk -> ai'
+    { sunk     = sunkShip           : sunk ai'      -- add sunk ship
+    , sunkTime = length (shots ai') : sunkTime ai'  -- add time for sinking
+      -- remove this ship from the tracking; otherwise it will confuse other functions:
+    , tracking = tracking ai' // [(pos, Nothing) | pos <- shipArea sunkShip (tracking ai')]
+    } where
+      sunkShip = fromMaybe err $ findSunkShip (tracking ai') p
+      err      = error $ "No sunk ship found: " ++ show p ++ "\n" ++ showTracking (tracking ai')
+  _    -> ai'
+  where
+    shipArea s t = shipCoordinates 1 s `intersect` indices t
+    ai' = ai
+      { tracking = tracking ai // [(p, Just r)]
+      , shots    = p : shots ai
+      } 
+
+
+--------------------------------------------------------------------------------
+-- * Firing shots
+--------------------------------------------------------------------------------
+
+-- | Add some randomness to the scores: Multiplies each score with a
+-- | random number near 1. If the AI is configured to play not as strongly,
+-- | the range of the random numbers is increased.
+randomize :: (MonadRandom m, MonadState CleverAI m) => ScoreGrid -> m ScoreGrid
+randomize s = do
+  d <- gets $ rulesDifficulty . rules
+  move <- gets $ rulesMove . rules
+  let m = Foldable.maximum s
+  flip traverseArray s $ \r -> case d of
+    Hard   -> liftM (r *) $ getRandomR (0.95,1.05)
+    Medium -> if move
+      then liftM (r +) $ getRandomR (0, m * 2.9) -- chosen s.t. AI needs about 10 more shots
+      else liftM (r +) $ getRandomR (0, m * 2)   -- on average (using aibenchmark)
+    Easy   -> liftM (r +) $ getRandomR (0, m * 3.5) -- chosen s.t. AI needs about 20 more shots on average
+
+-- | Assigns each cell a score. If it's high, it means that it's beneficial
+-- | to attack this cell. On how this is calculated, see below.
+
+scoreGrid :: (MonadState CleverAI m) => m ScoreGrid
+scoreGrid = scoreGrid' `liftM` get
+
+scoreGrid' :: CleverAI -> ScoreGrid
+scoreGrid' ai@(CleverAI {..}) = buildArray bs $ scorePosition ai remaining where
+  (w, h)    = boardSize
+  bs        = ((0, 0), (w - 1, h - 1))
+  remaining = fleetShips \\ map shipSize sunk
+
+-- | Given a position, look in all directions to find out whether it's part of a sunk ship.
+findSunkShip :: TrackingGrid    -- ^ AI's tracking array
+             -> Pos             -- ^ cell where the ship was sunk
+             -> Maybe ShipShape -- ^ sunk ship, if one exists
+findSunkShip t p = findHorizontal `mplus` findVertical where
+  findHorizontal =
+    let left@(leftX,_) = findEnd (\(x,y) -> (x-1,y)) p
+        (rightX,_)     = findEnd (\(x,y) -> (x+1,y)) p
+        len            = rightX - leftX + 1
+    in if len < 2 then Nothing else Just $ ShipShape left len Horizontal
+  findVertical =
+    let up@(_,upY) = findEnd (\(x,y) -> (x,y-1)) p
+        (_,downY)  = findEnd (\(x,y) -> (x,y+1)) p
+        len        = downY - upY + 1
+    in if len < 2 then Nothing else Just $ ShipShape up len Vertical
+  -- | Move as long as cells are hit or sunk, until the end of the ship is reached.
+  findEnd :: (Pos -> Pos) -- ^ the movement
+          -> Pos          -- ^ start position
+          -> Pos
+  findEnd move pos = if inRange (bounds t) (move pos) && isHitOrSunk (t ! move pos)
+                     then findEnd move $ move pos
+                     else pos
+
+
+-- | Given a position pos, assign it a score. How this is calculated
+-- | depends on whether the ships are movable or not. (See comment above.)
+scorePosition :: CleverAI
+              -> [Int]          -- ^ lengths of the remaining ships
+              -> Pos            -- ^ position to be scored
+              -> Score
+scorePosition ai@(CleverAI {..}) remaining pos@(x,y) =
+  if rulesMove rules then scoreMovable else scoreImmovable where
+
+  -- | Score position when ships are immovable.
+  scoreImmovable :: Score
+  scoreImmovable = preventDoubleAttackImmovable
+                 . considerEdges
+                 . checkerboard 0.9
+                 . scoreShips
+                 $ allRemaining
+
+  -- | Score position when ships are movable.
+  scoreMovable :: Score
+  scoreMovable = if hitCellsCount < minRequiredHits
+    -- This condition determines when we have hit enough ships to move on to the second phase.
+                 && curTurnNumber < rulesMaximumTurns rules - rulesCountdownTurns rules
+    -- This condition checks whether the countdown hasn't started yet.
+    then phase1 else phase2 where
+    -- | Minimum number of hits required to move on to the 2nd phase.
+    -- | When a checkerboard pattern is applied, this is the minimum number of
+    -- | hits if all "white squares" of all ships are hit.
+    -- | For then, we want all ships to be hit at least once.
+    minRequiredHits = sum
+                    . map (`div` 2) -- we can hit half of the ships cells (checkerboard)
+                    $ remaining
+    hitCellsCount   = length
+                    . filter isHit
+                    . elems
+                    $ tracking
+    phase1          = preventDoubleAttackMovable
+                    . considerEdges
+                    . checkerboard 0
+                    $ sum (map scoreShipPhase1 allRemaining)
+    phase2          = preventDoubleAttackMovable
+                    -- considerEdges doesn't work very well here
+                    . scoreShips
+                    $ allRemaining
+  
+  allRemaining :: [ShipShape]
+  allRemaining = allShips pos remaining
+
+  -- | Special scoring function for phase 1 with movable ships.
+  -- | A different one is needed because we don't want to sink ships
+  -- | during that phase.
+  scoreShipPhase1 :: ShipShape -> Score
+  scoreShipPhase1 ship = if   any (isHit . (tracking !)) $ shipCoordinates 0 ship
+                         then 0 -- we don't want to sink ships yet! -> low score
+                         else probNotBlocked ship
+
+  -- | Score low if we recently fired at this position.
+  -- | It is unlikely to have changed.
+  preventDoubleAttackMovable :: Score -> Score
+  preventDoubleAttackMovable s = if isHitOrSunk $ tracking ! pos then 0 else factor * s where
+    factor = maybe 1 (\i -> 1 - decay ^ i) $ elemIndex pos shots
+
+  -- | Score 0 if we ever before fired at this position.
+  preventDoubleAttackImmovable :: Score -> Score
+  preventDoubleAttackImmovable = if isHitOrSunk $ tracking ! pos then const 0 else id
+
+  checkerboard :: Double -- ^ how should "black" fields be weighted? (between 0 and 1)
+               -> Score
+               -> Score
+  checkerboard p 
+    | checkerboardEven = if even (x + y) then id else (*) p
+    | otherwise        = if odd (x + y) then id else (*) p
+
+  -- | Divide the scores by the initial score of that position.
+  -- This way, edge positions won't get a low score simply because
+  -- they are at the edge. We're measuring the "difference" between
+  -- the initial scores and the current scores instead.
+  considerEdges :: Score -> Score
+  considerEdges = (/ initialScore) where
+    initialScore = fromIntegral . length $ allShips pos fleetShips
+
+  -- | Assign a score to a list of ships. Hit ships are scored higher.
+  scoreShips :: [ShipShape] -> Score
+  scoreShips ships = sum (map probNotBlocked ships)
+                   + 20 * scoreHit ships
+                   + 50 * scoreSunk ships
+
+  -- | Score ships that are hit.
+  scoreHit :: [ShipShape] -> Score
+  scoreHit ships = sum
+                 . map (\s -> probNotBlocked s * rewardMultipleHits s)
+                 $ filter shipHit ships where
+    rewardMultipleHits s = fromIntegral
+                         . length
+                         . filter (isHit . (tracking !))
+                         $ shipCoordinates 0 s
+
+  -- | Score ships that are sunk.
+  scoreSunk :: [ShipShape] -> Score
+  scoreSunk ships = sum
+                  . map probNotBlocked
+                  $ filter shipSunk ships
+
+  shipHit :: ShipShape -> Bool
+  shipHit s = any (isHit . (tracking !)) $ shipCoordinates 0 s
+
+  shipSunk :: ShipShape -> Bool
+  shipSunk s = all (isHit . (tracking !)) . delete pos $ shipCoordinates 0 s
+
+  probBlocked :: ScoreGrid
+  probBlocked = probBlockedGrid ai
+
+  -- | Compute the probability for the given ship to exist.
+  probNotBlocked :: ShipShape -> Score
+  probNotBlocked = product
+                 . map ((1 -) . (probBlocked !))
+                 . shipCoordinates 0
+
+-- | Generates all ships through the current position which are inside the
+-- | boundaries of the field.
+allShips :: Pos   -- ^ the position that all ships will contain
+         -> [Int] -- ^ the lengths of the ships to be generated
+         -> [ShipShape]
+allShips (x,y) lens = filter (shipAdmissible [])
+              $ lens >>= \len ->
+                  [ShipShape (x-dx, y) len Horizontal | dx <- [0..len-1]]
+                  ++ [ShipShape (x, y-dy) len Vertical | dy <- [0..len-1]]
+
+-- | Returns a grid where the value at each position is the estimated probability
+-- | that this position is blocked, i.e. doesn't contain a ship.
+-- | For example, when a ship was recently sunk, it's unlikely that there will be a ship at that spot.
+-- | Or say, few attacks ago, we hit water, then this will stay the same for some time.
+-- | Put the probablity for that will decline over time. (E.g. a ship can move on a (former) water cell.)
+-- | It is modeled as exponential decay.
+probBlockedGrid :: CleverAI -> ScoreGrid
+probBlockedGrid (CleverAI {..}) = array ((0, 0), (width - 1, height - 1))
+  [(pos, probBlocked pos)
+  | x <- [0..width-1]
+  , y <-[0..height-1]
+  , let pos = (x,y)] where
+    (width, height)     = boardSize
+    probBlocked p       = maximum [probWater p, probNearSunk p,  diagonalHit p]
+    numMovesAgo p       = fromMaybe (error $ "numMovesAgo with invalid position " ++ show p
+                                           ++ ", shots " ++ show shots)
+                          $ p `elemIndex` shots
+    decayFactor         = if rulesMove rules then decay else 1 :: Score
+    -- | Probability for a ship to be on a (former) water cell
+    probWater p         = if isWater $ tracking ! p
+                          then decayFactor ^ numMovesAgo p -- exponential "decay"
+                          else 0
+    -- | Probability for a ship to be within the safety zone of a sunk ship.
+    probNearSunk p      = maximum'
+                        . map (\(_,c) -> decayFactor ^ (length shots - c))
+                        . filter (\(s,_) -> p `elem` shipCoordinates 1 s)
+                        $ zip sunk sunkTime where
+    -- | If the diagonal cells are hit, there can't be a ship.
+    -- | Illustration:
+    -- | ???
+    -- | ?H?
+    -- | ???
+    -- | We know that the positions marked with X are blocked for *sure*:
+    -- | X?X
+    -- | ?H?
+    -- | X?X
+    -- | so diagonalHit returns 1
+    diagonalHit         = fromBool
+                        . any isHitOrSunk
+                        . map (tracking !)
+                        . diagonalCells
+    diagonalCells (x,y) = [ (x-1,y-1)
+                          , (x-1,y+1)
+                          , (x+1,y-1)
+                          , (x+1,y+1)
+                          ] `intersect`
+                          indices tracking
+
+-- | How quickly should the probability for a former water cell
+-- | decline? 0.99 is pretty slowly, 0.9 is very (too) quickly.
+decay :: Score
+decay = 0.98
+
+-------------------------------------------------------------------------------
+-- * Serialization
+-------------------------------------------------------------------------------
+
+instance Serialize CleverAI where
+  get = CleverAI <$> S.get
+                 <*> getSmallGrid S.get
+                 <*> getList8 getPos
+                 <*> getList8 S.get
+                 <*> getList8 getIntegral8
+                 <*> S.get
+                 <*> S.get
+  put CleverAI {..} = do
+    S.put rules
+    putSmallGrid S.put tracking
+    putList8 putPos shots
+    putList8 S.put sunk
+    putList8 putIntegral8 sunkTime
+    S.put curTurnNumber
+    S.put checkerboardEven
diff --git a/Logic/Debug.hs b/Logic/Debug.hs
new file mode 100644
--- /dev/null
+++ b/Logic/Debug.hs
@@ -0,0 +1,40 @@
+-------------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.Debug
+-- Stability   :  experimental
+-- Portability :  portable
+--
+-- Some functions for debugging purposes, wrapping the functions from 
+-- `Debug.Trace`. These functions inhibit output when `development` is `False`
+
+module Logic.Debug
+  ( debugShow
+  , debugId
+  , debug
+  , debugShowM
+  , debugM
+  , debug'
+  ) where
+
+import Prelude
+import Settings.Development (development)
+
+import Debug.Trace
+
+debugShow :: Show a => a -> b -> b
+debugShow = if development then traceShow else flip const
+
+debug :: String -> a -> a
+debug = if development then trace else flip const
+
+debug' :: (a -> String) -> a -> a
+debug' f x = debug (f x) x
+
+debugId :: Show a => a -> a
+debugId x = debugShow x x
+
+debugShowM :: (Show a, Monad m) => a -> m ()
+debugShowM = flip debugShow (return ())
+
+debugM :: (Monad m) => String -> m ()
+debugM = flip debug (return ())
diff --git a/Logic/DefaultAI.hs b/Logic/DefaultAI.hs
new file mode 100644
--- /dev/null
+++ b/Logic/DefaultAI.hs
@@ -0,0 +1,9 @@
+module Logic.DefaultAI where
+
+import Logic.CleverAI
+import Logic.StupidAI
+
+-- | The AI we use by default.
+-- This way, only one line of code needs to be changed
+-- when switching to a different AI.
+type DefaultAI = CleverAI
diff --git a/Logic/Game.hs b/Logic/Game.hs
new file mode 100644
--- /dev/null
+++ b/Logic/Game.hs
@@ -0,0 +1,487 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.Game
+-- Stability   :  experimental
+-- Portability :  semi-portable
+--
+-- Logic and data structures of the battleships implementation.
+--
+-- The AI is implemented in another module to cleanly seperate it from
+-- the game logic.
+
+{-# LANGUAGE ViewPatterns #-}
+module Logic.Game
+  ( 
+  -- * Game Functions
+    boardSize
+  , gridRange
+  , fleetShips
+  , newGame
+  , humanPlayerState
+  , aiPlayerState
+  -- * Turn Functions
+  , isDrawn
+  , isTimedOut
+  , numRemainingShips
+  , remainingTurns
+  , isCountdownStart
+  , aiTurn
+  , desiredMove
+  , executeMove
+  , executeShot
+  , fireAt
+  , switchRoles
+  , humanTurnFire
+  , moveHuman
+  -- * Ship Functions
+  , allSunk 
+  , damageShip
+  , generateFleet
+  , isDamaged
+  , isMovable
+  , isShipSunk
+  , shipsAt
+  , shipSinkTime
+  , sinkTime
+  , moveShip
+  , uncheckedMoveShip
+  , numberShipsOfSize
+  , shipAdmissible
+  , shipCellIndex
+  , shipCoordinates
+  , sizesOfShips
+  , unsunkShips
+  ) where
+
+import           Prelude hiding (and, or, foldl, foldr, mapM_)
+import           Control.Monad hiding (forM_, mapM_)
+import           Control.Monad.Random
+import           Control.Monad.Trans.State (runStateT)
+import           Control.Monad.State.Class (MonadState, gets, modify)
+import           Data.Array
+import           Data.Foldable
+import           Data.List as L hiding (and, or, foldl, foldr, find)
+import qualified Data.Map as Map
+import           Data.Maybe
+import           Data.Monoid
+import           Logic.Types
+import           Logic.Util
+
+-------------------------------------------------------------------------------
+-- * Constants
+-------------------------------------------------------------------------------
+
+boardSize :: (Int, Int)
+boardSize = (10, 10)
+
+-- | A sorted list of available ships
+fleetShips :: [Int]
+fleetShips = sort [ 2, 2, 2, 2, 3, 3, 3, 4, 4, 5 ]
+
+-------------------------------------------------------------------------------
+-- * New Games
+-------------------------------------------------------------------------------
+
+-- | Creates a new game.
+newGame
+  :: (AI a, MonadRandom m)
+  => Rules          -- ^ rules of the game
+  -> Bool           -- ^ novice mode?
+  -> Bool           -- ^ developer mode?
+  -> FleetPlacement -- ^ fleet of the human player
+  -> Player         -- ^ beginning player
+  -> m (GameState a)
+newGame r noviceMode devMode pFleet begin = do 
+  (ai, eFleet) <- aiInit r
+  let
+    humanPlayer = PlayerState [] (generateFleet pFleet) HumanPlayer []
+    aiPlayer    = PlayerState [] (generateFleet eFleet) AIPlayer []
+    template    = GameState
+      { currentPlayer  = undefined
+      , otherPlayer    = undefined
+      , aiState        = ai
+      , gameRules      = r
+      , noviceModeOpt  = noviceMode
+      , devModeOpt     = devMode
+      , expectedAction = ActionFire -- the human is expected to fire a shot
+      , turnNumber     = 0
+      }
+    gameState = case begin of
+      HumanPlayer -> template { currentPlayer = humanPlayer, otherPlayer = aiPlayer }
+      AIPlayer    -> template { currentPlayer = aiPlayer, otherPlayer = humanPlayer }
+  return gameState
+
+-------------------------------------------------------------------------------
+-- * Helper Functions
+-------------------------------------------------------------------------------
+
+gridRange :: (Pos, Pos)
+gridRange = ((0, 0), (w - 1, h - 1))
+  where (w, h) = boardSize
+
+shipAdmissible :: FleetPlacement -> ShipShape -> Bool
+shipAdmissible fleet ship = rangeCheck && freeCheck where
+  -- check if ship is completely inside grid
+  rangeCheck     = L.all (inRange gridRange)
+                 $ shipCoordinates 0 ship
+  -- check if ship is not overlapping the safety margin of other ships
+  freeCheck      = L.all (null . shipsAt fleet)
+                 $ shipCoordinates 1 ship
+
+-- | Calculates the position occupied by a ship including safety margin.
+shipCoordinates :: HasShipShape s => Int -> s -> [Pos]
+shipCoordinates margin (getShipShape -> ShipShape{..}) = 
+  case shipOrientation of
+    Horizontal -> [(x + i, y + d) | i <- [-margin..shipSize - 1 + margin], d <- [-margin..margin]]
+    Vertical   -> [(x + d, y + i) | i <- [-margin..shipSize - 1 + margin], d <- [-margin..margin]]
+  where (x, y) = shipPosition
+
+-- | Returns the ships that contain the given positon.
+shipsAt :: (Foldable f, HasShipShape s) => f s -> Pos -> [s]
+shipsAt fleet (px, py) = filter containsP $ toList fleet where
+  containsP (getShipShape -> ShipShape{..}) = case shipOrientation of
+    Horizontal -> px >= sx && px < sx + shipSize && py == sy
+    Vertical   -> px == sx && py >= sy && py < sy + shipSize
+    where (sx, sy) = shipPosition
+
+-- | Determine the time when a given ship was sunk.
+shipSinkTime :: Ship -> Time
+shipSinkTime ship = if isShipSunk ship then lastHitTime ship else mempty
+
+-- | Determine the time when a given ship was sunk.
+lastHitTime :: Ship -> Time
+lastHitTime = fold . shipDamage -- let the maximum monoid take care of it
+
+-- | If at the given position there is a completely sunk ship, this stores the turn number in which it was sunk.
+sinkTime :: Fleet -> Array Pos Time
+sinkTime fleet = buildArray gridRange $ \pos ->
+  let isPosInShip = isJust . shipCellIndex pos
+  in foldMap shipSinkTime $ Map.filter isPosInShip fleet
+
+-- | Returns the zero-based index of a ship cell based on a global coordinate
+shipCellIndex :: HasShipShape s => Pos -> s -> Maybe Int
+shipCellIndex (px,py) (getShipShape -> ShipShape{..}) = case shipOrientation of
+    Horizontal 
+      | px >= sx && px < sx + shipSize && py == sy -> Just $ px - sx
+    Vertical
+      | px == sx && py >= sy && py < sy + shipSize -> Just $ py - sy
+    _ -> Nothing
+    where (sx, sy) = shipPosition
+
+-- | Inflicts damage to the specified ship cell
+damageShip :: Int -> Int -> Ship -> Ship
+damageShip time i ship = ship { shipDamage = shipDamage ship // [(i, Time $ Just time)] }
+
+allSunk :: Fleet -> Bool
+allSunk = and . fmap isShipSunk
+
+-- | Calculates how many ships of a given fleet are not sunk yet
+numRemainingShips :: Fleet -> Int
+numRemainingShips = Map.size . Map.filter (not . isShipSunk)
+
+isDamaged :: Ship -> Bool
+isDamaged = L.any (isJust . unwrapTime) . elems . shipDamage
+
+isShipSunk :: Ship -> Bool
+isShipSunk = L.all (isJust . unwrapTime) . elems . shipDamage
+
+generateFleet :: FleetPlacement -> Fleet
+generateFleet = Map.fromAscList . fmap newShip . zip [1..] where
+  newShip (sID, shape) = (sID, Ship sID shape (listArray (0,shipSize shape-1) (repeat $ Time Nothing)))
+
+numberShipsOfSize :: [Int] -> Int -> Int
+numberShipsOfSize ships size = length $ filter (== size) ships
+
+unsunkShips :: Fleet -> [Ship]
+unsunkShips fleet = filter (not . isShipSunk) (Map.elems fleet)
+
+sizesOfShips :: [Ship] -> [Int]
+sizesOfShips = map (shipSize . shipShape)
+
+humanPlayerState :: GameState a -> PlayerState
+humanPlayerState GameState{..} = case playerType currentPlayer of
+  HumanPlayer -> currentPlayer
+  AIPlayer    -> otherPlayer
+
+aiPlayerState    :: GameState a -> PlayerState
+aiPlayerState GameState{..} = case playerType currentPlayer of
+  HumanPlayer -> otherPlayer
+  AIPlayer    -> currentPlayer
+
+-------------------------------------------------------------------------------
+-- * Turn Common
+-------------------------------------------------------------------------------
+
+-- | Checks whether the game is drawn.
+-- It is drawn when it has timed out and both players 
+-- have sunk the same number of ships.
+isDrawn :: GameState a -> Bool
+isDrawn game = isTimedOut game && remA == remB where
+  remA = numRemainingShips $ playerFleet $ currentPlayer game
+  remB = numRemainingShips $ playerFleet $ otherPlayer game
+
+-- | Checks whether the game has timed out.
+-- It is timed out when the number of shots has exceeded the
+-- number rulesMaximumTurns from the rules.
+isTimedOut :: GameState a -> Bool
+isTimedOut game = curTurns >= maxTurns where
+  curTurns = turnNumber game
+  maxTurns = rulesMaximumTurns . gameRules $ game
+
+-- | Calculates the number of remaining turns overall.
+remainingTurns :: GameState a -> Int
+remainingTurns game = maxTurns - curTurns where
+  curTurns = turnNumber game
+  maxTurns = rulesMaximumTurns . gameRules $ game
+
+-- | Determines whether the countdown starts right now.
+-- It starts when exactly countdownTurns turns remain.
+isCountdownStart :: GameState a -> Bool
+isCountdownStart game = remTurns == cdTurns where
+  remTurns = remainingTurns game
+  cdTurns = rulesCountdownTurns . gameRules $ game
+
+-- | Switches the roles of active and passive player.
+-- Every time the roles are switched, the turn number is increased.
+switchRoles :: (MonadState (GameState a) m) => m ()
+switchRoles = do
+  modify(\g -> g
+    { currentPlayer = otherPlayer g
+    , otherPlayer = currentPlayer g
+    })
+  increaseTurnNumber
+
+-- | increases the turn number. This function is called by `switchRoles`
+-- and is not meant to be called directly.
+increaseTurnNumber :: (MonadState (GameState a) m) => m ()
+increaseTurnNumber = modify $ \gs -> gs {turnNumber = turnNumber gs + 1}
+
+-- | The current player fires at the other player
+-- Modifies the list of shots fired by the player and
+-- inflicts damage to the other player's ship, if hit.
+fireAt :: (MonadState (GameState a) m) 
+       => Pos -> m HitResponse
+fireAt pos = do
+  self  <- gets currentPlayer
+  other <- gets otherPlayer
+  time <- gets turnNumber
+  let remainingFleet = Map.filter (not . isShipSunk) (playerFleet other)
+  result <- case shipsAt remainingFleet pos of
+    [] -> return Water
+    [ship] -> do
+      let
+        -- inflict damage to the ship
+        Just idx = shipCellIndex pos ship
+        newShip  = damageShip time idx ship
+        -- replace ship
+        newFleet = Map.insert (shipID ship) newShip (playerFleet other)
+        other'   = other { playerFleet = newFleet }
+      -- update other player
+      modify (\gs -> gs { otherPlayer = other' })
+      return $ if isShipSunk newShip
+        then Sunk
+        else Hit
+    _ -> error $ "Multiple unsunk ships at position " ++ show pos ++ ". This shouldn't happen!"
+  -- add this shot to history
+  let self' = self { playerShots = Shot pos result time : playerShots self }
+  modify (\gs -> gs{currentPlayer = self'})
+  return result
+
+-- | Executes the supplied turn.
+executeShot :: (MonadState (GameState a) m)
+            => HitResponse -> m Turn
+executeShot result = do
+  rules <- gets gameRules
+  op <- gets otherPlayer
+  handleDraw $ case result of
+    Water -> Next
+    Hit
+      | rulesAgainWhenHit rules -> Again
+      | otherwise               -> Next
+    Sunk
+      | allSunk $ playerFleet op -> Over
+      | rulesAgainWhenHit rules  -> Again
+      | otherwise                -> Next
+  where
+    handleDraw r = do
+      timedOut <- gets isTimedOut
+      return $ case r of
+        Next | timedOut -> Over
+        _               -> r
+
+-------------------------------------------------------------------------------
+-- * Turn AI
+-------------------------------------------------------------------------------
+
+-- | Performs a full AI turn. 
+-- This function takes care of swapping the current player.
+-- 1. according to the rules, the AI may fire once or more
+-- 2. according to the rules, the AI may move one ship
+aiTurn :: (MonadState (GameState a) m, MonadRandom m, AI a)
+        => m Turn
+aiTurn = do
+    switchRoles
+    result <- shots
+    rules <- gets gameRules
+    when (result /= Over && rulesMove rules) $ moveAI >>= executeMove
+    switchRoles
+    return result
+  where
+    shots = do
+      result <- aiShot >>= executeShot
+      case result of
+        -- the AI player is allowed to shoot once more, when enabled
+        Again -> shots
+        _     -> return result
+
+-- | Performs the enemies turn
+-- assumes, that the enemy is the currentPlayer
+aiShot :: (MonadState (GameState a) m, MonadRandom m, AI a) => m HitResponse
+aiShot = do
+  -- let the AI decide where to shoot
+  ai <- gets aiState
+  (pos, s) <- runStateT aiFire ai
+  -- fire shot
+  result <- fireAt pos
+  -- give feedback to the AI
+  (_, s')  <- runStateT (aiResponse pos result) s
+  -- save modified AI state
+  modify (\g -> g{aiState = s'})
+  return result
+
+-- | Lets the AI decide on a move
+-- Assumes that the ai player is the currentPlayer
+moveAI :: (MonadState (GameState a) m, MonadRandom m, AI a) 
+     => m (Maybe (ShipID, Movement))
+moveAI = do
+  ai <- gets aiState
+  fleet <- gets (playerFleet . currentPlayer)
+  shots <- gets (playerShots . otherPlayer)
+  (mov, s) <- runStateT (aiMove fleet shots) ai
+  modify (\g -> g{aiState = s})
+  return mov
+
+
+
+-------------------------------------------------------------------------------
+-- * Turn Human
+-------------------------------------------------------------------------------
+
+-- | This function executes the fire-part of the human's turn
+-- It updates the "expectedAction" field of the state appropriately
+humanTurnFire :: (MonadState (GameState a) m)
+        => Pos -> m Turn
+humanTurnFire target = do
+  -- assert that the human is allowed to fire a shot
+  ActionFire <- gets expectedAction
+  -- setup common actions
+  rules <- gets gameRules
+  -- fire
+  result <- fireAt target >>= executeShot
+  when (result == Next) $ do
+      -- update the action to "move" if appropriate
+      humanFleet <- gets $ playerFleet . currentPlayer
+      when (rulesMove rules && anyShipMovable rules humanFleet) $
+        modify (\gs -> gs { expectedAction = ActionMove})
+  return result
+
+-- | Tries to move the human player's ship if pos is one of its endings.
+-- Assumes that the human player is the currentPlayer
+moveHuman :: (MonadState (GameState a) m) 
+     => Maybe Pos -> m (Maybe (ShipID, Movement))
+moveHuman pos = do
+  -- assert the human is really expected to move a ship
+  ActionMove <- gets expectedAction
+  -- change expected action
+  modify (\gs -> gs { expectedAction = ActionFire } )
+  -- return real move
+  case pos of
+    Nothing -> return Nothing
+    Just p  -> desiredMove p `liftM` gets (playerFleet . currentPlayer)
+
+-- | Find out which ship the player wants to move into which direction.
+desiredMove :: Pos -> Fleet -> Maybe (ShipID, Movement)
+desiredMove pos fleet = do 
+  Ship{..} <- case shipsAt remainingFleet pos of
+    []     -> Nothing
+    [ship] -> Just ship
+    _      -> error $ "Multiple unsunk ships at positon " ++ show pos ++ ". This shouldn't happen!"
+  let 
+    (x,y) = shipPosition shipShape
+    size  = shipSize shipShape
+  case shipOrientation shipShape of
+    Horizontal 
+      | pos == (x, y)            -> Just (shipID, Forward)
+      | pos == (x + size - 1, y) -> Just (shipID, Backward)
+    Vertical
+      | pos == (x, y)            -> Just (shipID, Forward)
+      | pos == (x, y + size - 1) -> Just (shipID, Backward)
+    _ -> Nothing
+  where remainingFleet = Map.filter (not . isDamaged) fleet
+
+-------------------------------------------------------------------------------
+-- * Moving Ships
+-------------------------------------------------------------------------------
+
+-- | executes a move for the current player
+executeMove :: (MonadState (GameState a) m)
+     => Maybe (ShipID, Movement) -> m ()
+executeMove move = do
+  curPlayer <- gets currentPlayer
+  let fleet = playerFleet curPlayer
+  case move of
+    Nothing                 -> return ()
+    Just (shipID, movement) -> case Map.lookup shipID fleet of
+      Just ship -> unless (isDamaged ship) $ do
+        time <- gets turnNumber
+        let
+          newFleet   = moveShip ship movement fleet
+          curPlayer' = curPlayer 
+            { playerFleet = newFleet
+            , playerMoves = ShipMove shipID movement time : playerMoves curPlayer 
+            }
+        modify (\gs -> gs { currentPlayer = curPlayer' })
+      Nothing -> return ()
+
+-- | Only moves the ship if it complies with the given rules.
+moveShip :: Ship -> Movement -> Fleet -> Fleet
+moveShip ship movement fleet = 
+  if isMovable movement fleet ship
+    then uncheckedMoveShip ship movement fleet
+    else fleet
+
+-- | Like moveShip but without movability check; needed for replay.
+uncheckedMoveShip :: Ship -> Movement -> Fleet -> Fleet
+uncheckedMoveShip ship movement = 
+  Map.adjust (\s -> s{shipShape = newShape}) (shipID ship)
+    where newShape = movedShipShape movement (shipShape ship)
+
+-- | Checks whether a ship can be moved.
+isMovable :: Movement -> Fleet -> Ship -> Bool
+isMovable movement fleet ship =
+       shipAdmissible otherShips newShape
+    && not (isDamaged ship) 
+  where
+    newShape = movedShipShape movement (shipShape ship)
+    otherShips = map (shipShape . snd)
+               . Map.toAscList
+               . Map.filter (not . isShipSunk) -- this ship can move over sunk ships
+               . Map.delete (shipID ship)
+               $ fleet
+
+-- | Returns whether any ship in the given fleet is movable.
+anyShipMovable :: Rules -> Fleet -> Bool
+anyShipMovable rules fleet = rulesMove rules 
+    && (anyForward || anyBackward)
+  where
+    anyForward  = or $ fmap (isMovable Forward fleet) fleet
+    anyBackward = or $ fmap (isMovable Backward fleet) fleet
+
+-- | Ship after movement was made.
+movedShipShape :: Movement -> ShipShape -> ShipShape
+movedShipShape movement ship = case (shipOrientation ship, movement) of
+  (Horizontal, Forward)  -> ship {shipPosition = (x - 1, y)}
+  (Horizontal, Backward) -> ship {shipPosition = (x + 1, y)}
+  (Vertical, Forward)    -> ship {shipPosition = (x, y - 1)}
+  (Vertical, Backward)   -> ship {shipPosition = (x, y + 1)}
+  where (x,y) = shipPosition ship
diff --git a/Logic/GameExt.hs b/Logic/GameExt.hs
new file mode 100644
--- /dev/null
+++ b/Logic/GameExt.hs
@@ -0,0 +1,65 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.GameExt
+-- Stability   :  experimental
+-- Portability :  semi-portable
+--
+-- External encrypted representation of the game state.
+
+module Logic.GameExt
+  ( impGame
+  , expGame
+  , loadKey
+  , GameStateExt
+  ) where
+
+import           Prelude
+import           Codec.Crypto.SimpleAES
+import           Control.Monad.IO.Class
+import qualified Data.ByteString             as BS
+import qualified Data.ByteString.Lazy        as BL
+import           Data.Serialize (Serialize, encode, decode)
+import           Logic.Binary
+import           Logic.Types
+import           Yesod (PathPiece (..))
+
+-- | External encrypted game state representation.
+data GameStateExt = GameStateExt
+  { fromStateExt :: BL.ByteString } deriving (Eq, Show, Read)
+
+-------------------------------------------------------------------------------
+-- * Conversions
+-------------------------------------------------------------------------------
+
+-- | Imports a game, given the key.
+impGame :: Serialize a => Key -> GameStateExt -> Either String (GameState a)
+impGame key game = decode dec where
+  enc = fromStateExt game
+  dec = toStrict $ decryptMsg CBC key enc
+
+-- | Exports a game, given the key.
+expGame
+  :: (MonadIO m, Serialize a)
+  => Key -> GameState a -> m GameStateExt
+expGame key game = liftIO $ do
+  let dec = fromStrict $ encode game
+  enc <- encryptMsg CBC key dec
+  return $ GameStateExt enc
+
+-- | Loads the AES key.
+loadKey :: String -> IO Key 
+loadKey = BS.readFile
+
+-------------------------------------------------------------------------------
+-- * Path Piece
+-------------------------------------------------------------------------------
+
+instance PathPiece GameStateExt where
+  fromPathPiece = fmap GameStateExt . impBinary
+  toPathPiece   = expBinary . fromStateExt
+
+instance PathPiece Bool where
+    fromPathPiece "1" = Just True
+    fromPathPiece "0" = Just False
+    fromPathPiece _   = Nothing
+    toPathPiece b = if b then "1" else "0"
diff --git a/Logic/Random.hs b/Logic/Random.hs
new file mode 100644
--- /dev/null
+++ b/Logic/Random.hs
@@ -0,0 +1,40 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.Random
+-- Stability   :  experimental
+-- Portability :  portable
+--
+-- Utilities for randomness.
+
+module Logic.Random
+  ( shuffleRandom
+  , chooseRandom
+  , runRandM
+  ) where
+
+import Prelude
+import Control.Monad
+import Control.Monad.Random
+
+-- | Extracts a random element from a list.
+extractRandom :: MonadRandom m => [a] -> m (Maybe (a, [a]))
+extractRandom [] = return Nothing
+extractRandom xs = do
+  ix <- getRandomR (0, length xs - 1)
+  let (ys, z : zs) = splitAt ix xs
+  return $ Just (z, ys ++ zs)
+
+-- | Randomly permutes an array.
+shuffleRandom :: MonadRandom m => [a] -> m [a]
+shuffleRandom xs = extractRandom xs >>= \r -> case r of
+  Nothing      -> return []
+  Just (y, ys) -> liftM (y :) $ shuffleRandom ys
+
+-- | Returns a random item of the list.
+chooseRandom :: MonadRandom m => [a] -> m (Maybe a)
+chooseRandom = (liftM . liftM) fst . extractRandom
+
+runRandM :: MonadRandom m => Rand StdGen a -> m a
+runRandM rand = do
+  i <- getRandom
+  return $ fst $ runRand rand $ mkStdGen i
diff --git a/Logic/Render.hs b/Logic/Render.hs
new file mode 100644
--- /dev/null
+++ b/Logic/Render.hs
@@ -0,0 +1,373 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.Render
+-- Stability   :  experimental
+-- Portability :  semi-portable
+--
+-- Diagrams based renderer for the game board.
+
+{-# LANGUAGE CPP, TypeFamilies #-}
+module Logic.Render
+  ( renderReferenceGrid
+  , renderEnemyGrid
+  , renderPlayerGrid
+  , renderLegend
+  , renderTimedLegend
+  , renderGrid
+  , LegendIcon (..)
+  , TimedLegendIcon (..)
+  , BattleDia
+  ) where
+
+import           Prelude
+import           Data.Colour.SRGB
+import           Data.Foldable (fold, foldMap)
+import           Data.Function (on)
+import           Data.Array
+import qualified Data.List as L
+import qualified Data.Map as Map
+import           Diagrams.Prelude hiding (Time)
+import           Diagrams.Backend.SVG
+import           Diagrams.TwoD.Text
+import           Logic.Game
+import           Logic.Types
+import           Logic.Util
+
+-- | Specialised diagram type. Backend is `SVG`, vector space is `R2` and
+-- annotations `[Pos]`.
+type BattleDia = QDiagram SVG R2 [Pos]
+
+-- | Arrows displayed on the bow and stern of undamaged ships.
+data MoveArrow = ArrowRight | ArrowUp | ArrowLeft | ArrowDown deriving Enum
+
+-- | legend icon to render
+data LegendIcon 
+  = LIShipWithArrow 
+  | LIShipMovable
+  | LIShipImmovable
+  | LIShipHit
+  | LIShipSunk
+  | LIFogOfWar
+  | LIWater
+  | LILastShot
+  deriving (Show, Enum, Bounded)
+
+-- | time-dependent legend icon to render
+data TimedLegendIcon
+  = TLIWater Int
+  | TLIMarker Int
+  deriving (Show)
+
+-------------------------------------------------------------------------------
+-- * Legend Rendering
+-------------------------------------------------------------------------------
+
+renderLegend :: LegendIcon -> Diagram SVG R2
+renderLegend icon = case icon of
+  LIShipWithArrow -> renderArrow ArrowRight <> movableSquare
+  LIShipMovable   -> movableSquare
+  LIShipImmovable -> shipSquare
+  LIShipHit       -> marker # lc markerHitColor <> shipSquare
+  LIShipSunk      -> (rect (2 * cellSize) cellSize # innerGridLineStyle 
+                     <> vrule cellSize # innerGridLineStyle 
+                     <> roundedRect (2 * cellSize) (cellSize) (0.25 * cellSize) # lw 5 # lc shipColor
+                     ) # centerXY
+                     <> rect (2 * cellSize + 5) (cellSize + 5) # fc waterColor
+  LIFogOfWar      -> square cellSize # fc fogColor
+  LIWater         -> waterSquare
+  LILastShot      -> square cellSize # alignTL <> lastShotMarker 1
+
+renderTimedLegend :: TimedLegendIcon -> Diagram SVG R2
+renderTimedLegend icon = case icon of
+  TLIWater timeDiff  -> waterSquare # opacityAfter timeDiff <> fogSquare
+  TLIMarker timeDiff -> marker # lc markerWaterColor # opacityAfter timeDiff <> waterSquare
+
+-------------------------------------------------------------------------------
+-- * High-Level Rendering for Grids
+-------------------------------------------------------------------------------
+
+renderReferenceGrid :: BattleDia
+renderReferenceGrid = renderGrid
+
+renderEnemyGrid :: Fleet -> TrackingList -> Rules -> Bool -> Int -> Bool -> Diagram SVG R2
+renderEnemyGrid fleet shots rules noviceMode turnNumber uncoverFleet = mconcat
+  [ if uncoverFleet then renderFleetHints else mempty
+  , renderSunkFleet fleet
+  , renderPositions $ renderMarker lastShotResultA rules turnNumber True
+  , renderPositions $ (if noviceMode then renderCellAndImpossible shots sinkTimeA else renderCell) lastShotResultA rules turnNumber
+  , contentSquare # fc fogColor
+  ]
+  where
+    sinkTimeA = sinkTime fleet
+    lastShotResultA = lastShotResult sinkTimeA shots turnNumber
+    renderFleetHints = lc red
+                     . lw 2
+                     . dashing [10] 0
+                     . renderFleetOutline
+                     . Map.filter (not . isShipSunk)
+                     $ fleet
+
+renderPlayerGrid :: Fleet -> TrackingList -> Action -> Rules -> Int -> Diagram SVG R2
+renderPlayerGrid fleet shots requiredAction rules@Rules{..} turnNumber = mconcat
+    [ markLastShots
+    , foldMap renderArrows . Map.filter (not . isDamaged) $ fleet
+    , renderPositions $ renderMarker lastShotResultA rules turnNumber False
+    , foldMap renderShip . Map.filter (not . isShipSunk) $ fleet
+    , renderSunkFleet fleet
+    , renderPositions $ renderCell lastShotResultA rules turnNumber
+    , contentSquare # fc waterColor
+    ]
+  where
+    sinkTimeA = sinkTime fleet
+    lastShotResultA = lastShotResult sinkTimeA shots turnNumber
+    markLastShots = case L.groupBy ((==) `on` shotTime) shots of
+      shotsLastRound:_ 
+        -> flip foldMap (zip [1::Int ..] (reverse shotsLastRound)) $ \(idx, Shot lastShotPos _ _) ->
+                 lastShotMarker idx # translateToPos lastShotPos
+      _ -> mempty
+    renderArrows ship@Ship{shipShape = ShipShape{shipPosition=(x,y),..},..} =
+      translateToPos (x,y) $ case shipOrientation of
+        Horizontal -> hcat [arrowCell i | i <- [0..shipSize-1]] # alignTL
+        Vertical   -> vcat [arrowCell i | i <- [0..shipSize-1]] # alignTL
+      where
+        arrowCell i = case requiredAction of
+          ActionMove -> maybe mempty renderArrow (movementArrowAt ship i fleet) <> transparentSquare
+          _          -> mempty
+    renderShip ship@Ship{shipShape = ShipShape{shipPosition=(x,y),..},..} = 
+      translateToPos (x,y) $ case shipOrientation of
+        Horizontal -> hcat (replicate shipSize shipCell) # alignTL
+        Vertical   -> vcat (replicate shipSize shipCell) # alignTL
+      where
+        shipCell = if isDamaged ship then shipSquare else movableSquare
+
+renderPositions :: (Pos -> Diagram SVG R2) -> Diagram SVG R2
+renderPositions f = foldMap renderPos $ range gridRange where
+  renderPos p = translateToPos p $ f p
+
+-- | Stores the result of the last shot at the given position
+-- and the corresponding shot time.
+lastShotResult :: Array Pos Time -> TrackingList -> Int -> Array Pos (Maybe (HitResponse, Int))
+lastShotResult sinkTimeA shots turnNumber = buildArray gridRange $ \pos ->
+  case L.find ((pos == ) . shotPos) shots of
+    Nothing -> Nothing
+    Just (Shot _ Hit hitTime) -> Just $ case unwrapTime $ (sinkTimeA ! pos) of
+      Just t | hitTime <= t -> (Sunk, t) -- make sure that the hit wasn't after the sinking!
+      _ -> (Hit, turnNumber) -- hit information is always up-to-date -> turnNumber instead of hitTime
+    Just (Shot _ res t) -> Just (res, t)
+
+renderMarker :: Array Pos (Maybe (HitResponse, Int)) -> Rules -> Int -> Bool -> Pos -> Diagram SVG R2
+renderMarker lastShotResultA Rules{..} turnNumber showOnlyHit pos
+ = alignMarker
+ $ case lastShotResultA ! pos of
+    Nothing            -> mempty
+    Just (Water, time) -> if showOnlyHit then mempty else marker # lc markerWaterColor # opac time
+    Just (Hit,   _   ) -> marker # lc markerHitColor
+    Just (Sunk,  _   ) -> mempty
+  where
+    opac = timedOpacity rulesMove turnNumber
+    alignMarker = translate (r2 (halfCellSize, -halfCellSize))
+
+renderCellAndImpossible :: TrackingList -> Array Pos Time -> Array Pos (Maybe (HitResponse, Int)) -> Rules -> Int -> Pos -> Diagram SVG R2
+renderCellAndImpossible shots sinkTimeA lastShotResultA rules@Rules{..} turnNumber pos@(x,y)
+ = alignTL $ case unwrapTime impossibleInfo of
+    Nothing -> renderCell lastShotResultA rules turnNumber pos
+    Just time -> case lastShotResultAtCurrentPos of
+      Just (_, t) | t >= time -> renderCell lastShotResultA rules turnNumber pos -- hint is older than player's actual information
+      _                       -> waterSquare # opac time
+  where
+    opac = timedOpacity rulesMove turnNumber
+    lastShotResultAtCurrentPos = lastShotResultA ! pos
+    impossibleInfo = findMostRecentHit diagonalCells
+      `mappend` findMostRecentlySunkShip (diagonalCells ++ adjacentCells)
+      `mappend` if sawWaterHereAfterAdjacentHitNotYetSunk then Time (Just turnNumber) else mempty
+    diagonalCells = filter (inRange gridRange) [(x + dx, y + dy) | dx <- [-1,1], dy <- [-1,1]]
+    adjacentCells = filter (inRange gridRange) ([(x + dx, y) | dx <- [-1,1]] ++ [(x, y + dy) | dy <- [-1,1]])
+    findMostRecentHit = foldMap getTimeOfHit
+    getTimeOfHit p = Time $ case lastShotResultA ! p of
+      Just (Hit, time) -> Just time
+      _                -> Nothing
+    findMostRecentlySunkShip = foldMap $ (sinkTimeA !)
+    sawWaterHereAfterAdjacentHitNotYetSunk = case lastShotResultAtCurrentPos of
+      Just (Water, sawWater) -> any (\p -> case L.find ((p == ) . shotPos) shots of
+                                             Just (Shot _ Hit hitTime) -> case unwrapTime $ (sinkTimeA ! p) of
+                                                                            Just t | hitTime <= t -> False
+                                                                            _                     -> hitTime <= sawWater
+                                             _                         -> False)
+                                adjacentCells
+      _                      -> False
+
+renderCell :: Array Pos (Maybe (HitResponse, Int)) -> Rules -> Int -> Pos -> Diagram SVG R2
+renderCell lastShotResultA Rules{..} turnNumber pos
+ = alignTL
+ $ case lastShotResultA ! pos of
+    Nothing            -> mempty
+    Just (Water, time) -> waterSquare # opac time
+    Just (Hit,   time) -> shipSquare # opac time
+    Just (Sunk,  time) -> waterSquare # opac time
+  where
+    opac = timedOpacity rulesMove turnNumber
+
+
+-------------------------------------------------------------------------------
+-- * Low-Level Rendering
+-------------------------------------------------------------------------------
+
+rowNumbers :: Int -> BattleDia
+rowNumbers n = vcat [num i | i <- [1..n]] # value [] where
+  num i = (text (show i) # fc gridColor # numberStyle) <> square cellSize
+
+colNumbers :: Int -> BattleDia
+colNumbers n = hcat [num i | i <- [0..n-1]] # value [] where
+  num i = (text (strNum i) # fc gridColor # numberStyle) <> square cellSize
+  strNum :: Int -> String
+  strNum i = [toEnum $ fromEnum 'A' + i]
+
+#if MIN_VERSION_diagrams_lib(0,7,0)
+marker, waterSquare, shipSquare, movableSquare, fogSquare, transparentSquare
+  :: (Alignable b, HasOrigin b, TrailLike b, Transformable b, Semigroup b, HasStyle b, V b ~ R2)
+  => b
+#else
+marker, waterSquare, shipSquare, movableSquare, fogSquare, transparentSquare
+  :: (Alignable b, HasOrigin b, PathLike b, Transformable b, Semigroup b, HasStyle b, V b ~ R2)
+  => b
+#endif
+marker         = lw 3 $ drawX (markerRadius * sqrt 2) where
+  drawX s      = p2 (-0.5 * s, -0.5 * s) ~~ p2 (0.5 * s, 0.5 * s)
+               <> p2 (-0.5 * s, 0.5 * s) ~~ p2 (0.5 * s, -0.5 * s)
+waterSquare    = square cellSize # fc waterColor
+fogSquare      = square cellSize # fc fogColor
+shipSquare     = rect cellSize cellSize # fc shipColor
+movableSquare  = rect cellSize cellSize # fc movableColor
+transparentSquare = rect cellSize cellSize # opacity 0
+
+renderSunkFleet :: Fleet -> Diagram SVG R2
+renderSunkFleet = lw 5
+                . lc shipColor
+                . renderFleetOutline
+                . Map.filter isShipSunk
+
+renderFleetOutline :: Fleet -> Diagram SVG R2
+renderFleetOutline = fold . fmap renderShipOutline
+
+renderShipOutline :: Ship -> Diagram SVG R2
+renderShipOutline Ship {shipShape = ShipShape {shipPosition = (x,y), ..} } =
+  roundedRect (w * cellSize) (h * cellSize) (0.25 * cellSize) # alignTL # translateToPos (x,y) where
+    (w,h) = case shipOrientation of
+        Horizontal -> (realToFrac shipSize, 1)
+        Vertical   -> (1, realToFrac shipSize)
+
+timedOpacity :: (Integral i, HasStyle c) => Bool -> i -> i -> c -> c
+timedOpacity True turnNumber shotTime = opacityAfter $ turnNumber - shotTime
+timedOpacity False _ _                = opacity 1
+
+opacityAfter :: (Integral i, HasStyle c) => i -> c -> c
+opacityAfter timeDiff = opacity (foot + if timeDiff < steps then (1 - foot) * f (fromIntegral timeDiff / fromIntegral steps) else 0)
+  where foot = 0.25  -- the minimal opacity value used
+        steps = 20   -- the number of steps in which the opacity decreases from 1 to the above value
+        -- f should be a monotone function from (0,1) to (1,0); e.g., could be f x = 1 - x
+        f x = let param = 0.3  -- a parameter by which to tweak the slowness of the decrease; should be between 0 and exp 1
+              in (1 - log (param + x * (exp 1 - param))) / (1 - log param)
+
+lastShotMarker :: (Renderable (Path R2) b, Renderable Text b) 
+               => Int -> Diagram b R2
+lastShotMarker idx = 
+    (   rect (cellSize - 4) (cellSize - 4) # lc lastShotColor # lw 3
+     <> text (show idx) # numberStyle # fc white
+    ) # alignTL # translate (r2 (2,-2))
+
+contentSquare :: Diagram SVG R2
+contentSquare
+  = rect (cellSize * realToFrac nx) (cellSize * realToFrac ny)
+  # alignTL
+  # translateToPos (0,0)
+  where
+    (nx, ny) = boardSize
+
+movementArrowAt :: Ship -> Int -> Fleet -> Maybe MoveArrow
+movementArrowAt ship@Ship{..} i fleet =
+  case shipOrientation shipShape of
+    Horizontal
+      | i == 0                      && canMove Forward  -> Just ArrowLeft
+      | i == shipSize shipShape - 1 && canMove Backward -> Just ArrowRight
+    Vertical
+      | i == 0                      && canMove Forward  -> Just ArrowUp
+      | i == shipSize shipShape - 1 && canMove Backward -> Just ArrowDown
+    _ -> Nothing
+    where 
+      canMove dir = isMovable dir fleet ship
+
+renderArrow :: MoveArrow -> Diagram SVG R2
+renderArrow arrType = arrowShape # rotateBy circleFraction # arrowStyle  where 
+  circleFraction = fromIntegral (fromEnum arrType) / 4
+  arrowShape     = fromVertices [ p2 (0, -0.8 * halfCellSize)
+                                , p2 (0.8 * halfCellSize,  0)
+                                , p2 (0,  0.8 * halfCellSize)]
+
+translateToPos :: (Transformable t, V t ~ R2) => Pos -> t -> t
+translateToPos (x,y) = 
+  let 
+    (nx, ny) = (cellSize + realToFrac x * cellSize, - cellSize - realToFrac y * cellSize)
+  in translate (r2 (nx,ny))
+
+-------------------------------------------------------------------------------
+-- * Grid Rendering
+-------------------------------------------------------------------------------
+
+renderGrid :: BattleDia
+renderGrid  = border <> gridLines <> labels where
+  border    = rect w h # alignTL # lw 1 # lc gridColor # value []
+  gridLines = innerLines <> outerLines
+  xnums     = colNumbers nx # translate (r2 (cellSize, 0))
+  ynums     = rowNumbers ny
+  field     = vcat [cellRow y | y <- [0..nx-1]]
+  cellRow y = hcat [ posSquare (x,y) | x <- [0..ny-1]]
+  -- invisible square carrying the position in grid-coordinates
+  posSquare p = square cellSize # value [p]
+  labels    = vcat [xnums, hcat [ynums, field, ynums], xnums] # alignTL
+  w = (fromIntegral nx + 2) * cellSize
+  h = (fromIntegral ny + 2) * cellSize
+  outerOffsets n = [cellSize, (fromIntegral n + 1) * cellSize]
+  innerOffsets n = [fromIntegral i * cellSize | i <- [2..n]]
+  innerLines = (xticks (h-1) (innerOffsets nx) <> yticks (w-1) (innerOffsets ny)) # innerGridLineStyle # value []
+  outerLines = (xticks (h-1) (outerOffsets nx) <> yticks (w-1) (outerOffsets ny)) # outerGridLineStyle # value []
+  (nx, ny)   = boardSize
+
+#if MIN_VERSION_diagrams_lib(0,7,0)
+xticks, yticks :: (Monoid a, TrailLike a, V a ~ R2) 
+               => Double -> [Double] -> a
+#else
+xticks, yticks :: (Monoid a, PathLike a, V a ~ R2) 
+               => Double -> [Double] -> a
+#endif
+xticks h xs = mconcat [fromVertices [p2 (x, 0), p2 (x, -h) ] | x <- xs]
+yticks w ys = mconcat [fromVertices [p2 (0, -y), p2 (w, -y) ] | y <- ys]
+
+-------------------------------------------------------------------------------
+-- * Style Constants
+-------------------------------------------------------------------------------
+
+cellSize, halfCellSize, markerRadius, innerGridWidth :: Double
+cellSize       = 40
+halfCellSize   = cellSize / 2
+markerRadius   = cellSize / 2 - 3
+innerGridWidth = 1
+
+innerGridLineStyle, outerGridLineStyle, arrowStyle :: HasStyle c => c -> c
+innerGridLineStyle = lw innerGridWidth . lc gridColor . dashing [3, 3] 0
+outerGridLineStyle = lw innerGridWidth . lc gridColor
+arrowStyle         = lw 5 . lc gray
+
+numberStyle :: HasStyle c => c -> c
+numberStyle = fontSize 30 . font "Monospace"
+
+gridColor, fogColor, waterColor, markerHitColor, markerWaterColor, 
+  shipColor, lastShotColor, movableColor
+  :: Colour Double
+gridColor        = sRGB24 0xD2 0xF8 0x70
+fogColor         = sRGB 0.7 0.7 0.7
+waterColor       = sRGB24 0x36 0xBB 0xCE
+markerHitColor   = sRGB24 0xFE 0x3F 0x44
+markerWaterColor = sRGB24 0x00 0x00 0xFF
+shipColor        = gray
+lastShotColor    = red
+movableColor     = sRGB24 0xC4 0xF8 0x3E
diff --git a/Logic/StupidAI.hs b/Logic/StupidAI.hs
new file mode 100644
--- /dev/null
+++ b/Logic/StupidAI.hs
@@ -0,0 +1,36 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.StupidAI
+-- Stability   :  experimental
+-- Portability :  semi-portable
+--
+-- AI that randomly shoots and does not move.
+
+module Logic.StupidAI 
+  ( StupidAI
+  ) where
+
+import           Prelude
+import           Control.Monad
+import           Control.Monad.Random
+import           Data.Maybe (fromJust)
+import           Data.Serialize (Serialize(..))
+import           Logic.AIUtil
+import           Logic.Game
+import           Logic.Types
+
+data StupidAI = StupidAI
+
+instance AI StupidAI where
+  aiInit _       = do
+    ships <- liftM fromJust $ completeFleet []
+    return (StupidAI, ships)
+  aiFire         = getRandomPos boardSize
+  aiResponse _ _ = return ()
+
+instance Serialize StupidAI where
+  get = return StupidAI
+  put StupidAI = return ()
+
+getRandomPos :: MonadRandom m => (Int, Int) -> m (Int,Int)
+getRandomPos (w,h) = liftM2 (,) (getRandomR (0, w - 1)) (getRandomR (0, h - 1))
diff --git a/Logic/Types.hs b/Logic/Types.hs
new file mode 100644
--- /dev/null
+++ b/Logic/Types.hs
@@ -0,0 +1,439 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.Types
+-- Stability   :  experimental
+-- Portability :  semi-portable
+--
+-- Data structures and type classes of the battleships implementation.
+--
+module Logic.Types
+  (
+  -- * Typeclasses
+    AI (..)
+  , HasShipShape (..)
+  -- * Datatypes
+  , Action (..)
+  , GameState (..)
+  , DifficultyLevel (..)
+  , HitResponse (..)
+  , Movement (..)
+  , Orientation (..)
+  , Time (..)
+  , Player (..)
+  , PlayerState (..)
+  , Options (..)
+  , Rules (..)
+  , Ship (..)
+  , ShipShape (..)
+  , ShipMove (..)
+  , Shot (..)
+  , Turn (..)
+  -- * Type Synonyms
+  , Fleet
+  , FleetPlacement
+  , Grid
+  , Pos
+  , ShipID
+  , TrackingList
+  -- * Smart Constructors
+  , newGrid
+  -- * Serialization Helpers
+  , getPos
+  , getSmallGrid
+  , putPos
+  , putSmallGrid
+  ) where
+
+
+import           Prelude
+import           Control.Applicative
+import           Control.Monad
+import           Control.Monad.Random
+import           Control.Monad.State.Class (MonadState)
+import           Data.Aeson hiding (Array, encode, decode)
+import           Data.Array
+import           Data.Bits
+import           Data.Function (on)
+import qualified Data.Map as Map
+import           Data.Maybe (fromMaybe)
+import           Data.Monoid
+import           Data.Serialize (Serialize (..), encode, decode)
+import           Data.Serialize.Get
+import           Data.Serialize.Put
+import           Data.Word
+import           Logic.Binary
+import           Yesod (PathPiece (..))
+
+-------------------------------------------------------------------------------
+-- * AI
+-------------------------------------------------------------------------------
+
+-- | Operations an artificial intelligence has to provide for playing this game.
+class AI a where
+  -- | Initial state and fleet position
+  aiInit
+    :: MonadRandom m 
+    => Rules                 -- ^ game rules
+    -> m (a, FleetPlacement) -- ^ initial state
+
+  -- | Computes the next shot based on the current AI state
+  aiFire
+    :: (MonadRandom m, MonadState a m) 
+    => m Pos
+
+  -- | Feedback to `aiFire`
+  aiResponse
+    :: (MonadRandom m, MonadState a m) 
+    => Pos         -- ^ target position
+    -> HitResponse -- ^ result of the last shot
+    -> m ()
+
+  -- | Computes the ship movement
+  aiMove
+    :: (MonadRandom m, MonadState a m)
+    => Fleet                        -- ^ AI's fleet including IDs
+    -> TrackingList                 -- ^ enemy shots
+    -> m (Maybe (ShipID, Movement)) -- ^ ship and movement, if any
+  aiMove _ _ = return Nothing
+
+-------------------------------------------------------------------------------
+-- * Game State
+-------------------------------------------------------------------------------
+
+data Options = Options
+  { againWhenHit   :: Bool
+  , move           :: Bool
+  , noviceMode     :: Bool
+  , devMode        :: Bool
+  , difficulty     :: DifficultyLevel
+  } deriving (Show, Eq, Read)
+
+data Rules = Rules
+  { rulesAgainWhenHit   :: Bool
+  , rulesMove           :: Bool
+  , rulesDifficulty     :: DifficultyLevel
+  , rulesMaximumTurns   :: Int
+  , rulesCountdownTurns :: Int
+  }
+
+-- | Playing strength of the AI.
+data DifficultyLevel
+  = Easy
+  | Medium
+  | Hard
+  deriving (Enum, Eq, Show, Read)
+
+-- | Reponse sent to the AI after a shot.
+data HitResponse
+  = Water -- ^ the shot hit the water
+  | Hit   -- ^ the shot hit a ship
+  | Sunk  -- ^ the shot hit the last intact part of a ship
+  deriving (Eq, Enum)
+
+data Orientation 
+  = Horizontal
+  | Vertical
+  deriving (Enum, Bounded)
+
+-- | Represents the last time (turn number) that an event happened,
+-- if any, especially a ship hit in the Ship data type.
+newtype Time = Time { unwrapTime :: Maybe Int }
+
+-- | Maximum monoid.
+-- Useful because we often want to know when the last time
+-- was that something happened. (last -> maximum)
+instance Monoid Time where
+  mempty = Time Nothing
+  mappend (Time Nothing)   t = t
+  mappend (Time (Just t1)) t = Time . Just $ case t of { Time Nothing -> t1 ; Time (Just t2) -> max t1 t2 }
+
+-- | Encodes a ships state using position, size and orientation
+data ShipShape = ShipShape 
+  { shipPosition    :: Pos
+  , shipSize        :: Int
+  , shipOrientation :: Orientation
+  }
+
+-- | A ship with unique id, a shape and current damage.
+data Ship = Ship
+  { shipID     :: ShipID         -- ^ unique ID of ship
+  , shipShape  :: ShipShape      -- ^ shape of ship (including position, orientation and size)
+  , shipDamage :: Array Int Time -- ^ damage at each position
+  }
+
+instance Eq Ship where
+  (==) = (==) `on` shipID
+
+-- | Used to allow lookup functions to work with both FleetPlacement and Fleet
+class HasShipShape a where
+  getShipShape :: a -> ShipShape
+instance HasShipShape Ship where
+  getShipShape = shipShape
+instance HasShipShape ShipShape where
+  getShipShape = id
+
+-- | State of the game for both players.
+data GameState a = GameState
+  { currentPlayer  :: PlayerState -- ^ the current player's state 
+  , otherPlayer    :: PlayerState -- ^ the other player's state
+  , aiState        :: a           -- ^ state of the AI
+  , gameRules      :: Rules
+  , noviceModeOpt  :: Bool
+  , devModeOpt     :: Bool
+  , expectedAction :: Action
+  , turnNumber     :: Int
+  }
+
+-- | The state belonging to one player
+data PlayerState = PlayerState
+  { playerShots :: TrackingList -- ^ the player's shots
+  , playerFleet :: Fleet        -- ^ the player's fleet
+  , playerType  :: Player
+  , playerMoves :: [ShipMove]   -- ^ the player's moves
+  } deriving Eq
+
+-- | type to distinguish between human and AI player
+data Player
+  = HumanPlayer
+  | AIPlayer
+  deriving (Eq, Enum)
+
+-- | the next action expected from the human player
+data Action
+  = ActionFire
+  | ActionMove
+  deriving (Eq, Enum)
+
+-- | keeps track of all relevant information for a fired shot
+data Shot = Shot
+  { shotPos    :: Pos
+  , shotResult :: HitResponse
+  , shotTime   :: Int
+  } deriving Eq
+
+-- | a ship movement
+data ShipMove = ShipMove
+  { shipMoveID        :: ShipID
+  , shipMoveDirection :: Movement
+  , shipMoveTime      :: Int
+  } deriving (Eq, Show)
+
+-- | A fleet is a map of ship ID's to ships
+type Fleet = Map.Map ShipID Ship
+
+-- | A fleet placement is a list of the ship shapes
+type FleetPlacement = [ShipShape]
+
+-- | A two-dimensional position stored with zero-based indices
+type Pos = (Int,Int)
+
+-- | A grid is an array indexed by positions with zero-based indices
+type Grid a = Array Pos a
+
+-- | A list of all shots. Easier to handle, because no index lookup is needed.
+type TrackingList = [Shot]
+
+-- | Used for identifying a ship.
+type ShipID = Int
+
+-- | Result of the turn with respect to the current player
+data Turn = Over | Again | Next deriving Eq
+
+-- | A ships movement
+data Movement 
+  = Forward  -- ^ -1 for the respective coordinate
+  | Backward -- ^ +1 for the respective coordinate
+  deriving (Eq, Enum, Bounded, Show)
+
+-------------------------------------------------------------------------------
+-- * Smart Constructors
+-------------------------------------------------------------------------------
+
+-- | Creates a grid, filled with one value.
+newGrid :: (Int, Int) -> a -> Grid a
+newGrid (w, h) a
+  = array ((0, 0), (w - 1, h - 1))
+    [((x, y), a) | x <- [0 .. w - 1], y <- [0 .. h - 1]]
+
+-------------------------------------------------------------------------------
+-- * Random
+-------------------------------------------------------------------------------
+
+instance Random Orientation where
+  randomR (a, b) g = (toEnum r, g') where
+    (r, g')        = randomR (fromEnum a, fromEnum b) g
+  random           = randomR (minBound, maxBound)
+
+instance Random Movement where
+  randomR (a, b) g = (toEnum r, g') where
+    (r, g')        = randomR (fromEnum a, fromEnum b) g
+  random           = randomR (minBound, maxBound)
+
+-------------------------------------------------------------------------------
+-- * JSON
+-------------------------------------------------------------------------------
+
+instance FromJSON ShipShape where
+   parseJSON (Object v) = curry ShipShape <$>
+                          v .: "X" <*>
+                          v .: "Y" <*>
+                          v .: "Size" <*>
+                          v .: "Orientation"
+   -- A non-Object value is of the wrong type, so fail.
+   parseJSON _          = mzero
+
+instance FromJSON Orientation where
+  parseJSON (Number n) = return $ toEnum $ floor n
+  parseJSON _          = mzero
+
+instance ToJSON Orientation where
+  toJSON = Number . fromIntegral . fromEnum
+
+instance ToJSON ShipShape where
+  toJSON (ShipShape {..}) = object 
+    [ "X"           .= fst shipPosition
+    , "Y"           .= snd shipPosition
+    , "Size"        .= shipSize
+    , "Orientation" .= shipOrientation
+    ]
+
+-------------------------------------------------------------------------------
+-- * Path Pieces
+-------------------------------------------------------------------------------
+
+instance PathPiece Options where
+  fromPathPiece = impBinary >=> eitherToMaybe . decode . toStrict
+  toPathPiece   = expBinary . fromStrict . encode
+
+eitherToMaybe :: Either a b -> Maybe b
+eitherToMaybe e = case e of
+  Right x -> Just x
+  _       -> Nothing
+
+-------------------------------------------------------------------------------
+-- * Serialization
+-------------------------------------------------------------------------------
+
+instance Serialize a => Serialize (GameState a) where
+  get = GameState <$> get <*> get <*> get <*> get <*> get <*> get <*> get <*> getIntegral8
+  put GameState {..} = do
+    put currentPlayer
+    put otherPlayer
+    put aiState
+    put gameRules
+    put noviceModeOpt
+    put devModeOpt
+    put expectedAction
+    putIntegral8 turnNumber
+
+instance Serialize PlayerState where
+  get = PlayerState <$> getList8 get <*> get <*> get <*> get
+  put PlayerState{..} = do
+    putList8 put playerShots
+    put playerFleet
+    put playerType
+    put playerMoves
+
+instance Serialize Options where
+  get = Options <$> get <*> get <*> get <*> get <*> get
+  put Options {..} = do
+    put againWhenHit
+    put move
+    put noviceMode
+    put devMode
+    put difficulty
+
+instance Serialize Rules where
+  get = Rules <$> get <*> get <*> get <*> getIntegral8 <*> getIntegral8
+  put Rules {..} = do
+    put rulesAgainWhenHit
+    put rulesMove
+    put rulesDifficulty
+    putIntegral8 rulesMaximumTurns
+    putIntegral8 rulesCountdownTurns
+
+instance Serialize DifficultyLevel where
+  get = getEnum8
+  put = putEnum8
+
+instance Serialize HitResponse where
+  get = getEnum8
+  put = putEnum8
+
+instance Serialize Orientation where
+  get = getEnum8
+  put = putEnum8
+
+instance Serialize Player where
+  get = getEnum8
+  put = putEnum8
+
+instance Serialize Action where
+  get = getEnum8
+  put = putEnum8
+
+instance Serialize Movement where
+  get = getEnum8
+  put = putEnum8
+
+instance Serialize ShipShape where
+  get = ShipShape <$> getPos <*> getIntegral8 <*> get
+  put ShipShape{..} = do
+    putPos shipPosition
+    putIntegral8 shipSize
+    put shipOrientation
+
+instance Serialize Time where
+  get = mkTime <$> getIntegral8 where
+    mkTime 0xFF = Time Nothing
+    mkTime i    = Time $ Just i
+  put (Time t) = putIntegral8 $ fromMaybe 0xFF t
+
+instance Serialize Ship where
+  get = Ship <$> getIntegral8 <*> get <*> get
+  put Ship{..} = do
+    putIntegral8 shipID
+    put shipShape
+    put shipDamage
+
+instance Serialize Shot where
+  get = Shot <$> getPos <*> get <*> getIntegral8
+  put Shot{..} = do
+    putPos shotPos
+    put shotResult
+    putIntegral8 shotTime
+
+instance Serialize ShipMove where
+  get = ShipMove <$> getIntegral8 <*> get <*> getIntegral8
+  put ShipMove{..} = do
+    putIntegral8 shipMoveID
+    put shipMoveDirection
+    putIntegral8 shipMoveTime
+
+
+-------------------------------------------------------------------------------
+-- * Specific Serialization Helpers
+-------------------------------------------------------------------------------
+
+putPos :: Putter Pos
+putPos (x,y) = put (hi .|. lo :: Word8) where
+  hi = (fromIntegral x .&. 0x0F) `shiftL` 4
+  lo =  fromIntegral y .&. 0x0F
+
+getPos :: Get Pos
+getPos = fromB <$> getWord8 where
+  fromB b = ( fromIntegral $ b `shiftR` 4
+            , fromIntegral $ b .&. 0x0F   )
+
+putSmallGrid :: Putter a -> Putter (Grid a)
+putSmallGrid pel grid = do
+  let (_, upper) = bounds grid
+  putPos upper
+  mapM_ pel (elems grid)
+
+getSmallGrid :: Get a -> Get (Grid a)
+getSmallGrid gel = do
+  upper <- getPos
+  let count = rangeSize ((0,0), upper)
+  xs <- replicateM count gel
+  return $ listArray ((0,0), upper) xs
diff --git a/Logic/Util.hs b/Logic/Util.hs
new file mode 100644
--- /dev/null
+++ b/Logic/Util.hs
@@ -0,0 +1,38 @@
+----------------------------------------------------------------------------
+-- |
+-- Module      :  Logic.Util
+-- Stability   :  experimental
+-- Portability :  portable
+--
+-- Utilities.
+
+module Logic.Util
+  (
+    maximumIx
+  , buildArray
+  , traverseArray
+  ) where
+
+import           Prelude
+import           Data.Array
+import           Data.List
+import           Data.Function
+import qualified Data.Traversable (mapM)
+import           Control.Arrow
+
+--------------------------------------------------------------------------------
+-- * Array Utilities
+--------------------------------------------------------------------------------
+
+-- | Index of the maximum element in an array.
+maximumIx :: (Ix i, Ord e) => Array i e -> i
+maximumIx = fst . maximumBy (compare `on` snd) . assocs
+
+-- | Build an array by specifying bounds and a function that constructs
+-- the value for an index.
+buildArray :: Ix i => (i, i) -> (i -> a) -> Array i a
+buildArray bs f = array bs $ fmap (id &&& f) $ range bs
+
+-- | Distributive law for monad actions in arrays.
+traverseArray :: (Ix i, Monad m) => (a -> m b) -> Array i a -> m (Array i b)
+traverseArray = Data.Traversable.mapM
diff --git a/Settings.hs b/Settings.hs
new file mode 100644
--- /dev/null
+++ b/Settings.hs
@@ -0,0 +1,78 @@
+module Settings
+  ( staticDir
+  , widgetFile
+  , widgetFileSettings
+  , Extra (..)
+  , parseExtra
+  ) where
+
+import Prelude
+import Data.Default (def)
+import Yesod.Default.Util
+import Settings.Development (development)
+import Text.Hamlet
+import Data.Yaml
+import Yesod.Default.Config
+import Control.Applicative
+import Logic.Types
+
+import Language.Haskell.TH.Syntax
+-- import Text.Shakespeare.Text (st)
+-- import Yesod.Default.Config
+-- import Data.Text (Text)
+
+-- Static setting below. Changing these requires a recompile
+
+-- | The location of static files on your system. This is a file system
+-- path. The default value works properly with your scaffolded site.
+staticDir :: FilePath
+staticDir = "static"
+
+-- | The base URL for your static files. As you can see by the default
+-- value, this can simply be "static" appended to your application root.
+-- A powerful optimization can be serving static files from a separate
+-- domain name. This allows you to use a web server optimized for static
+-- files, more easily set expires and cache values, and avoid possibly
+-- costly transference of cookies on static files. For more information,
+-- please see:
+--   http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
+--
+-- If you change the resource pattern for StaticR in Foundation.hs, you will
+-- have to make a corresponding change here.
+--
+-- To see how this value is used, see urlRenderOverride in Foundation.hs
+-- staticRoot :: AppConfig DefaultEnv x -> Text
+-- staticRoot conf = [st|#{appRoot conf}/cgi-bin/battleships/static|]
+
+-- | Settings for 'widgetFile', such as which template languages to support and
+-- default Hamlet settings.
+--
+-- For more information on modifying behavior, see:
+--
+-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
+widgetFileSettings :: WidgetFileSettings
+widgetFileSettings = def
+    { wfsHamletSettings = defaultHamletSettings
+        { hamletNewlines = AlwaysNewlines
+        }
+    }
+
+widgetFile :: String -> Q Exp
+widgetFile = (if development then widgetFileReload
+                             else widgetFileNoReload)
+              widgetFileSettings
+
+data Extra = Extra
+  { extraCountdownTurns :: Int
+  , extraMaxTurns :: Int
+  , extraDataDir :: String
+  , extraStaticDir :: String
+  , extraSourceURL :: String
+  , extraAIURL :: String
+  , extraOptions :: Options
+  }
+
+parseExtra :: DefaultEnv -> Object -> Parser Extra
+parseExtra _ o = Extra <$> fmap (*2) (o .: "countdownturns") <*> fmap (*2) (o .: "maxturns") <*> o .: "datadir" <*> o .: "staticdir" <*> o .: "sourceURL" <*> o .: "aiURL"
+                       <*> (Options <$> o .: "againWhenHit" <*> o .: "move" <*> o .: "noviceMode"
+                                    <*> pure True <*> fmap read (o .: "difficulty"))
diff --git a/Settings/Development.hs b/Settings/Development.hs
new file mode 100644
--- /dev/null
+++ b/Settings/Development.hs
@@ -0,0 +1,15 @@
+{-# LANGUAGE CPP #-}
+module Settings.Development
+  ( development
+  ) where
+
+import Prelude
+
+{-# INLINE development #-}
+development :: Bool
+development =
+#if DEVELOPMENT
+  True
+#else
+  False
+#endif
diff --git a/Settings/StaticFiles.hs b/Settings/StaticFiles.hs
new file mode 100644
--- /dev/null
+++ b/Settings/StaticFiles.hs
@@ -0,0 +1,37 @@
+module Settings.StaticFiles where
+
+import Prelude (IO)
+import Yesod.Static
+import qualified Yesod.Static as Static
+import Settings (staticDir)
+import Settings.Development
+-- import Language.Haskell.TH (Q, Exp, Name)
+-- import Data.Default (def)
+
+-- | use this to create your static file serving site
+staticSite :: IO Static.Static
+staticSite = if development then Static.staticDevel staticDir
+                            else Static.static      staticDir
+
+-- | This generates easy references to files in the static directory at compile time,
+--   giving you compile-time verification that referenced files exist.
+--   Warning: any files added to your static directory during run-time can't be
+--   accessed this way. You'll have to use their FilePath or URL to access them.
+$(staticFiles staticDir)
+
+{-
+combineSettings :: CombineSettings
+combineSettings = def
+
+-- The following two functions can be used to combine multiple CSS or JS files
+-- at compile time to decrease the number of http requests.
+-- Sample usage (inside a Widget):
+--
+-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
+
+combineStylesheets :: Name -> [Route Static] -> Q Exp
+combineStylesheets = combineStylesheets' development combineSettings
+
+combineScripts :: Name -> [Route Static] -> Q Exp
+combineScripts = combineScripts' development combineSettings
+-}
diff --git a/Setup.hs b/Setup.hs
new file mode 100644
--- /dev/null
+++ b/Setup.hs
@@ -0,0 +1,3 @@
+import Distribution.Simple
+
+main = defaultMain
diff --git a/aibenchmark/Main.hs b/aibenchmark/Main.hs
new file mode 100644
--- /dev/null
+++ b/aibenchmark/Main.hs
@@ -0,0 +1,132 @@
+module Main
+  ( main
+  , playGame
+  , benchmark
+  ) where
+
+import           Prelude
+import           Control.Monad
+import           Control.Monad.IO.Class
+import           Control.Monad.Trans.State (runStateT, StateT)
+import           Data.List (sort)
+import qualified Data.Map as Map
+import           Logic.AIUtil
+import           Logic.CleverAI
+import           Logic.StupidAI
+import           Logic.Game
+import           Logic.Types
+import           System.Environment
+
+main :: IO ()
+main = do
+  putStrLn "Usage: aibenchmark (mov|immov) (Hard|Medium|Easy) numGames [--verbose]"
+  putStrLn "Example: aibenchmark immov Hard 20 --verbose"
+  a1:a2:a3:rest <- getArgs
+  let
+    moveable    = case a1 of
+      "mov"   -> True
+      "immov" -> False
+      _       -> error $ "Error: `" ++ a2 ++ "` is neither `mov` nor `immov`!"
+    difficultyLvl = read a2
+    repetitions   = read a3
+    verbose       = case rest of
+      "--verbose":_ -> True
+      _      -> False
+  benchmark
+    verbose
+    benchmarkRules { rulesMove = moveable, rulesDifficulty = difficultyLvl }
+    repetitions
+
+-- | Tests the performance of the AI, that is the average number of shots
+-- | needed to sink all the ships. This way, we can estimate how well the AI plays.
+-- | The AI plays against itself.
+benchmark :: Bool -> Rules -> Int -> IO ()
+benchmark verbose rules repetitions = do
+  shotCounts <- mapM f [1..repetitions]
+  let sorted = sort shotCounts
+  let avg = (fromIntegral $ sum shotCounts :: Double) / fromIntegral (length shotCounts)
+  let mn = minimum shotCounts
+  let mx = maximum shotCounts
+  let mdn = sorted !! (length sorted `div` 2)
+  putStrLn   "----------\n"
+  putStrLn   "SUMMARY\n"
+  putStrLn $ "Average: " ++ show avg ++ " shots."
+  putStrLn $ "Minimum: " ++ show mn ++ " shots."
+  putStrLn $ "Maximum: " ++ show mx ++ " shots."
+  putStrLn $ "Median:  " ++ show mdn ++ " shots."
+  putStrLn   "Complete list: "
+  mapM_ print sorted where
+    f :: Int -> IO Int
+    f i = do
+      putStrLn $ "\n---\n" ++ show i ++ "th run:"
+      shotCount <- playGame verbose rules
+      putStrLn $ show shotCount ++ " shots needed."
+      return shotCount
+
+-- | Returns number of shots the AI needed.
+playGame :: Bool -> Rules -> IO Int
+playGame verbose rules = do
+  (ai, fleetPlacement) <- aiInit rules
+  putStrLn $ showFleetPlacement fleetPlacement
+  let fleet = generateFleet fleetPlacement
+  (count, _newAi) <- runStateT (turn verbose rules [] fleet Map.empty 0) (ai :: CleverAI)
+  return $ count `div` 2 -- only count AI's shots, not the turn number
+
+-- | Let the AI play against itself. Returns the number of shots fired.
+turn :: AI a => Bool -> Rules -> TrackingList -> Fleet -> Fleet -> Int -> StateT a IO Int
+turn verbose rules shots fleet sunk count = do
+    when verbose . liftIO $ do
+      putStrLn "Fleet:"
+      putStrLn $ showFleet fleet
+      putStrLn "Sunk:"
+      putStrLn $ showFleet sunk
+      putStrLn "Tracking:"
+      putStrLn $ showTrackingList shots
+    -- get target position from AI
+    pos <- aiFire
+    when verbose . liftIO . putStrLn $ "AI's target: " ++ show pos
+    -- fire the AI's shot against itself
+    let
+      (response, fleet', sunk') = case shipsAt (fleet Map.\\ sunk) pos of
+        []     -> (Water, fleet, sunk)
+        [ship] ->
+          let
+            -- inflict damage to the ship
+            Just idx = shipCellIndex pos ship
+            newShip  = damageShip count idx ship
+            -- replace ship
+            newFleet = Map.insert (shipID ship) newShip fleet
+          in if isShipSunk newShip
+             then (Sunk, newFleet, Map.insert (shipID ship) newShip sunk)
+             else (Hit, newFleet, sunk)
+        _      -> error $ "Error: Multiple ships at position " ++ show pos ++ ". This shouldn't happen!"
+    -- update the tracking list
+    let shots'   = Shot pos response count:shots
+    -- notify the AI
+    aiResponse pos response
+    -- should any ships be moved?
+    fleet'' <- if rulesMove rules
+      then do
+        mMove <- aiMove fleet' shots'
+        when verbose . liftIO . putStrLn $ "AI's movement: " ++ show mMove
+        return $ case mMove of
+          Nothing -> fleet'
+          Just (sID, movement) -> case Map.lookup sID fleet' of
+            Just ship -> if not $ isDamaged ship
+              then moveShip ship movement fleet'
+              else fleet'
+            Nothing   -> fleet'
+      else return fleet'
+    -- all ships sunk now?
+    if allSunk fleet''
+      then return (count + 2)
+      else turn verbose rules shots' fleet'' sunk' (count + 2)
+
+benchmarkRules :: Rules
+benchmarkRules = Rules
+  { rulesAgainWhenHit   = False
+  , rulesMove           = undefined
+  , rulesDifficulty     = undefined
+  , rulesMaximumTurns   = 150
+  , rulesCountdownTurns = 40
+  }
diff --git a/app/main.hs b/app/main.hs
new file mode 100644
--- /dev/null
+++ b/app/main.hs
@@ -0,0 +1,23 @@
+{-# LANGUAGE CPP #-}
+import Prelude              (IO, (>>=))
+import Yesod.Default.Config (loadConfig, configSettings, DefaultEnv(..), ConfigSettings(csParseExtra))
+import Settings             (parseExtra)
+import Application          (makeApplication)
+
+#if DEVELOPMENT
+import qualified Network.Wai.Handler.Warp (run)
+
+main :: IO ()
+main =
+    loadConfig (configSettings Development) { csParseExtra = parseExtra }
+    >>= makeApplication
+    >>= Network.Wai.Handler.Warp.run 3000
+#else
+import qualified Network.Wai.Handler.FastCGI (run)
+
+main :: IO ()
+main =
+    loadConfig (configSettings Production) { csParseExtra = parseExtra }
+    >>= makeApplication
+    >>= Network.Wai.Handler.FastCGI.run
+#endif
diff --git a/battleships.cabal b/battleships.cabal
new file mode 100644
--- /dev/null
+++ b/battleships.cabal
@@ -0,0 +1,192 @@
+name:              battleships
+version:           1.0.0
+cabal-version:     >= 1.8
+build-type:        Simple
+category:          Game
+author:		   Meike Grewing, Lukas Heidemann, Fabian Thorand, Fabian Zaiser
+maintainer:        thorand@cs.uni-bonn.de
+license:           BSD3
+license-file:      LICENSE
+Bug-Reports:   	   https://github.com/zrho/afp/issues
+Homepage:      	   https://github.com/zrho/afp
+
+synopsis:    A web-based implementation of battleships including an AI opponent.
+description: This package provides a web-based implementation of the popular
+             battleships game, developed over the course of a practical functional
+             programming class at the University of Bonn (<http://www.iai.uni-bonn.de/~jv/teaching/afp13/>).
+
+             Alongside with the classical gameplay against an AI opponent, a game mode
+             is provided in which players may move their undamaged ships.
+
+Extra-Source-Files:
+                messages/*.msg
+                config/routes
+                config/settings.yml
+                config/key.aes
+                templates/*.cassius
+                templates/*.hamlet
+                templates/*.julius
+                static/.htaccess
+                static/js/*.js
+                static/img/*.svg
+                static/img/*.ico
+                static/img/*.png
+
+Flag dev
+    Description:   Turn on development settings, like auto-reload templates.
+    Default:       False
+
+Flag library-only
+    Description:   Build for use with "yesod devel"; also turns on development settings.
+    Default:       False
+
+library
+    exposed-modules: Application
+                     Foundation
+                     Import
+                     Settings
+                     Settings.Development
+                     Settings.StaticFiles
+                     Handler.About
+                     Handler.GameEnded
+                     Handler.Home
+                     Handler.PlaceShips
+                     Handler.Play
+                     Handler.Replay
+                     Handler.Rules
+                     Handler.Util
+                     Handler.SaveGame
+                     Logic.Util
+                     Logic.AIUtil
+                     Logic.Binary
+                     Logic.CleverAI
+                     Logic.Debug
+                     Logic.DefaultAI
+                     Logic.Game
+                     Logic.GameExt
+                     Logic.Random
+                     Logic.Render
+                     Logic.StupidAI
+                     Logic.Types
+
+    ghc-options:   -Wall
+
+    if flag(dev) || flag(library-only)
+        cpp-options:   -DDEVELOPMENT
+        ghc-options:   -O0
+    else
+        ghc-options:   -O2
+
+    extensions: TemplateHaskell
+                QuasiQuotes
+                OverloadedStrings
+                NoImplicitPrelude
+                RecordWildCards
+                FlexibleContexts
+
+    build-depends: base                          >= 4          && < 5
+                -- * needed for yesod
+                 , yesod                         >= 1.2        && < 1.2.5
+                 , yesod-core                    >= 1.2        && < 1.3
+                 , yesod-static                  >= 1.2        && < 1.3
+                 , yesod-routes
+                 , hamlet                        >= 1.1        && < 1.2
+                 , shakespeare-text              >= 1.0        && < 1.1
+                 , wai-extra                 
+                 , wai-logger    
+                 , cookie
+                 , hjsmin
+                -- * more monads
+                 , mtl
+                 , MonadRandom
+                -- * data types
+                 , bytestring                    >= 0.9        && < 0.11
+                 , text                          >= 0.11       && < 0.12
+                 , aeson
+                 , containers                    
+                 , array
+                -- * diagrams
+                 , blaze-svg
+                 , diagrams-svg                  
+                 , diagrams-lib                  
+                 , colour
+                -- * other
+                 , template-haskell
+                 , data-default
+                 , fast-logger                   >= 0.3.2
+                 , cereal
+                 , transformers
+                 , base64-bytestring
+                 , SimpleAES
+                 , attoparsec
+                 , word8
+                 , shakespeare-js
+                 , yaml
+                 , filepath
+
+    if flag(library-only)
+        build-depends:   warp
+                       , directory               >= 1.1        && < 1.3
+
+executable         main.fcgi
+    if flag(library-only)
+        Buildable: False
+
+    ghc-options:   -threaded -Wall
+
+    if flag(dev)
+        cpp-options:   -DDEVELOPMENT
+        ghc-options:   -O0
+        build-depends: warp
+    else
+        ghc-options:   -O2
+        build-depends: wai-handler-fastcgi       >= 1.3        && < 2.1
+
+    main-is:           main.hs
+    hs-source-dirs:    app
+    build-depends:     base
+                     , battleships
+                     , yesod
+
+executable img-gen
+    if flag(library-only)
+        Buildable: False
+
+    extensions:      FlexibleContexts
+    main-is:         Main.hs
+    hs-source-dirs:  img-gen
+    ghc-options:     -Wall
+    build-depends:   base
+                   , mtl
+                   , battleships
+                   , bytestring
+                   , blaze-svg
+                   , diagrams-svg
+                   , diagrams-lib
+                   , filepath
+
+executable aibenchmark
+    if flag(library-only)
+        Buildable: False
+
+    main-is:         Main.hs
+    hs-source-dirs:  aibenchmark
+    ghc-options:     -O2 -Wall
+    build-depends:   base
+                   , battleships
+                   , mtl
+                   , transformers
+                   , containers
+                   , MonadRandom
+
+executable key-gen
+    if flag(library-only)
+        Buildable: False
+
+    main-is:         Main.hs
+    hs-source-dirs:  key-gen
+    ghc-options:     -Wall
+    build-depends:   base
+                   , mtl
+                   , bytestring
+                   , crypto-random
diff --git a/config/key.aes b/config/key.aes
new file mode 100644
Binary files /dev/null and b/config/key.aes differ
diff --git a/config/routes b/config/routes
new file mode 100644
--- /dev/null
+++ b/config/routes
@@ -0,0 +1,11 @@
+/battleships                                        HomeR          GET
+/battleships/about                                  AboutR         GET
+/battleships/rules                                  RulesR         GET POST
+/battleships/place/#Options                         PlaceShipsR    GET POST
+/battleships/place-random                           PlaceShipsRndR POST
+/battleships/saved/#Bool/#GameStateExt              PlayR          GET
+/battleships/fired/#GameStateExt                    FireR          POST
+/battleships/moved/#GameStateExt                    MoveR          POST
+/battleships/savegame/#GameStateExt                 SaveGameR      GET
+/battleships/replay/#GameStateExt                   ReplayR        GET
+/cgi-bin/battleships/static                         StaticR        Static getStatic
diff --git a/config/settings.yml b/config/settings.yml
new file mode 100644
--- /dev/null
+++ b/config/settings.yml
@@ -0,0 +1,29 @@
+Default: &defaults
+  host: "*4" # any IPv4 host
+  port: 3000
+  approot: "http://localhost:3000"
+  datadir: "config/"
+  staticdir: "static/"
+  sourceURL: "https://github.com/zrho/afp/tree/master/battleships"
+  aiURL: "https://github.com/zrho/afp/wiki/Battleships:-AI"
+  againWhenHit: True
+  move: True
+  noviceMode: False
+  difficulty: Hard
+  maxturns: 75
+  countdownturns: 20
+
+Development:
+  <<: *defaults
+
+Testing:
+  <<: *defaults
+
+Staging:
+  <<: *defaults
+
+Production:
+  approot: "http://www-pg.iai.uni-bonn.de"
+  datadir: "/srv/www/vhosts/www-pg-data/battleships/"
+  staticdir: "/srv/www/vhosts/www-pg-data/battleships/"
+  <<: *defaults
diff --git a/img-gen/Main.hs b/img-gen/Main.hs
new file mode 100644
--- /dev/null
+++ b/img-gen/Main.hs
@@ -0,0 +1,88 @@
+{-# LANGUAGE CPP #-}
+module Main where
+
+import           Logic.Render
+import           Control.Monad
+import           Control.Monad.Reader
+import qualified Data.ByteString.Lazy as BSL
+import           Diagrams.Prelude
+import           Diagrams.Backend.SVG
+import           Text.Blaze.Svg.Renderer.Utf8 (renderSvg)
+import           System.FilePath
+import qualified Settings (staticDir)
+
+
+data ImgGenOpt = ImgGenOpt
+  { optOutputDir :: FilePath
+  } deriving (Show)
+
+defaultOptions :: ImgGenOpt
+defaultOptions = ImgGenOpt
+  { optOutputDir = Settings.staticDir </> "img"
+  }
+
+type Dia = QDiagram SVG R2 Any
+
+main :: IO ()
+main = flip runReaderT defaultOptions $ do
+  liftIO $ putStrLn "generating legend icons..."
+  forM_ [minBound..maxBound :: LegendIcon] writeImageFile
+  forM_ [0,5,10,15,20] $ writeImageFile . TLIWater
+  forM_ [0,5,10,15,20] $ writeImageFile . TLIMarker
+  writeImageFile GridBG
+
+-------------------------------------------------------------------------------
+-- * Diagram Rendering
+-------------------------------------------------------------------------------
+
+diaToSVG :: Dia -> BSL.ByteString
+diaToSVG = renderSvg
+#if MIN_VERSION_diagrams_svg(0,8,0)
+  . renderDia SVG (SVGOptions Absolute Nothing)
+#else
+  . renderDia SVG (SVGOptions Absolute)
+#endif
+
+-------------------------------------------------------------------------------
+-- * Class
+-------------------------------------------------------------------------------
+
+class ImageFile a where
+  imageName   :: a -> String
+  imageRender :: a -> Dia
+
+instance ImageFile LegendIcon where
+  imageName   = show
+  imageRender = renderLegend
+
+instance ImageFile TimedLegendIcon where
+  imageName = show
+  imageRender = renderTimedLegend
+
+-------------------------------------------------------------------------------
+-- * Grid Background
+-------------------------------------------------------------------------------
+
+data GridBG = GridBG
+
+instance ImageFile GridBG where
+  imageName _   = "grid"
+  imageRender _ = fmap (const $ Any True) renderGrid
+
+-------------------------------------------------------------------------------
+-- * Icons
+-------------------------------------------------------------------------------
+
+writeImageFile :: ImageFile a => a -> ReaderT ImgGenOpt IO ()
+writeImageFile img = do
+  fileName <- imageFileName img
+  liftIO $ do 
+    BSL.writeFile fileName (diaToSVG $ imageRender img)
+    putStrLn $ concat ["'", fileName, "' written"]
+
+imageFileName
+  :: (MonadReader ImgGenOpt m, ImageFile a)
+  => a -> m FilePath
+imageFileName img = do
+  dir <- asks optOutputDir
+  return $ dir </> (imageName img ++ ".svg")
diff --git a/key-gen/Main.hs b/key-gen/Main.hs
new file mode 100644
--- /dev/null
+++ b/key-gen/Main.hs
@@ -0,0 +1,17 @@
+module Main where
+import Crypto.Random
+import System.Environment
+import qualified Data.ByteString as BS
+import System.IO
+
+main :: IO ()
+main = do
+  args <- getArgs
+  entPool <- createEntropyPool
+  let
+    cprg    = cprgCreate entPool :: SystemRNG
+    (key,_) = cprgGenerate 32 cprg
+  withFile (head (args ++ ["config/key.aes"])) WriteMode $ \handle -> do
+    BS.hPutStr handle key
+    hFlush handle
+  putStrLn "key generated"
diff --git a/messages/de.msg b/messages/de.msg
new file mode 100644
--- /dev/null
+++ b/messages/de.msg
@@ -0,0 +1,78 @@
+GameName: Schiffe versenken
+Credits: - Präsentiert von Projektgruppe AFP
+GameDescription: 
+IEWarning: Anscheinend betrachtest du unsere Seite im IE. Wenn du dabei auf irgendwelche Probleme stößt, benutze bitte einen Browser wie z.B. Chrome oder Firefox.
+NoJavaScriptWarning: Anscheinend hast du JavaScript deaktiviert. Unsere Seite benötigt dies aber, um richtig zu funktionieren. Bitte aktiviere JavaScript!
+LinkHome: Zurück zur Startseite
+StartPlacing: Schiffe platzieren
+FireShot: Schuss abfeuern!
+Won: Du hast gewonnen!
+WonByTimeout remShipsHuman remShipsComputer: Du hast durch Timeout gewonnen! Du hast #{show remShipsHuman} ungesunkene Schiffe, der Computer nur #{show remShipsComputer}.
+Lost: Du hast verloren.
+LostByTimeout remShipsHuman remShipsComputer: Du hast durch Timeout verloren! Du hast nur #{show remShipsHuman} ungesunkene Schiffe, der Computer #{show remShipsComputer}.
+Drawn remShips: Unentschieden! Die maximale Zuganzahl wurde erreicht und ihr habt beide #{show remShips} ungesunkene Schiffe.
+PlaceShips: Platziere deine Schiffe
+AvailableShips: Verfügbare Flotte
+NoPossiblePlacement: Die Flottenbelegung konnte nicht vervollständigt werden.
+
+InputAgainWhenHit: bei Treffer erneut schießen
+InputMove: Schiffe verschiebbar
+InputNoviceMode: Zusätzlich als Hilfe unmögliche Positionen anzeigen
+InputDevMode: Entwicklermodus
+InputDifficulty: Schwierigkeitsstufe
+InputDifficultyEasy: Einfach
+InputDifficultyMedium: Mittelschwer
+InputDifficultyHard: Schwer
+AdjustRules: Die Regeln anpassen
+Rules: Regeln
+
+ShipLength: Länge
+ShipsAvailable: Verfügbar
+ShipsTotal: Total
+ResetFleet: Flotte zurücksetzen
+PlaceRandom: Zufällig
+StartPlaying: Los!
+SkipMove: Ziehen überspringen
+MoveShip: Bewege eins deiner Schiffe
+YourFleet: Deine Flotte
+OpponentsFleet: Gegnerische Flotte
+OpponentRemainingShips: Folgende Schiffe musst du noch finden:
+ShipsUnsunk: Noch nicht gesunken
+Hints: Hinweise
+RemainingTurns n: Nur noch #{show n} verbleibende Spielzüge (nach diesem)!
+LastTurn: Letzter Zug!
+
+Legend: Legende
+LegendShipWithArrow: Schiff durch Klick bewegen
+LegendShipMovable: Bewegliches Schiff
+LegendShipImmovable: Unbewegliches Schiff
+LegendShipHit: Treffer
+LegendShipSunk: Versenktes Schiff
+LegendFogOfWar: Nicht kartografierter Bereich
+LegendWater: Wasser
+LegendLastShot: Feindliche Schüsse des letzten Zugs
+LegendWaterShots: Schüsse auf Wasser
+LegendRightNow: Jetzt gerade
+LegendTurnsAgo n: Vor #{show n} Zügen
+LegendMinTurnsAgo n: Vor mindestens #{show n} Zügen
+
+PauseButtonLabel: Anhalten
+UnpauseButtonLabel: Weiter
+RestartButtonLabel: Von vorne
+WatchReplay: Replay anschauen
+SaveGame: Das Spiel speichern
+SaveGameExplanation: Um das momentane Spiel zu speichern, setze ein Lesezeichen auf folgenden Link - so kommst du immer wieder zum jetzigen Stand! Aber nicht zum Schummeln nutzen. :-)
+CurrentGame: Lesezeichen-tauglicher Link auf das aktuelle Spiel
+
+ConfirmLeave: Wirklich zurück zur Startseite?
+ConfirmReplay: Wirklich das Replay anschauen? Das beendet das aktuelle Spiel!
+About: Über das Spiel
+HowToPlay: So wird gespielt
+HowToPlaceShipsHeading: Schiffe platzieren
+HowToPlaceShipsFull: Zu Beginn des Spiels platzierst du deine Schiffe. Dafür drückst du die linke Maustaste im ersten der Felder, die dein Schiff belegen soll, und lässt sie im letzten zum Schiff gehörenden Feld wieder los. Um ein Schiff wieder zu entfernen, klicke es einfach an; dann kannst du es an einer anderen Stelle platzieren. Die Felder um platzierte Schiffe herum werden ausgegraut, da Schiffe sich nicht berühren dürfen. Es ist auch möglich, eine zufällige Platzierung generieren zu lassen (ganz oder teilweise).
+HowToPlayHeading: Schüsse feuern und Schiffe bewegen
+HowToPlayFull: Nach dem Platzieren der Schiffe sind abwechselnd du und der Computer an der Reihe. Ein Spielzug besteht aus dem Feuern (wenn entsprechend eingestellt, darfst du so lange feuern, wie du Schiffe des Gegners triffst) und -optional- dem Bewegen eines unversehrten Schiffes um ein Feld. Zum Feuern klicke einfach auf das gegnerische Feld, auf das du schießen möchtest. Die unversehrten Schiffe werden besonders hervorgehoben und die, die sich bewegen lassen (wenn also kein Hindernis den Weg blockiert) haben Pfeile an ihren Enden. Klicke auf einen Pfeil, um das zugehörige Schiff zu bewegen. Wichtig ist dabei: Gesunkene Schiffe verschwinden! Sobald ein Schiff also komplett versenkt wurde, kann man andere Schiffe darüber hinweg bewegen.
+HowToWinHeading: Spielende
+HowToWinFull maxTurns countdownTurns: Das Spiel endet, sobald ein Spieler das letzte Schiff seines Gegners versenkt. Er gewinnt das Spiel dadurch. Um langweilige, niemals endende Spiele zu vermeiden, endet das Spiel jedoch auch nach maximal #{show maxTurns} Zügen. Um dich auf das bevorstehende Ende durch Timeout aufmerksam zu machen (damit du eventuell deine Strategie anpassen kannst), siehst du während der letzten #{show countdownTurns} Züge einen Countdown. Nach Timeout gewinnt der Spieler, der am meisten Schiffe versenkt hat.
+ReallyFair: Spielt der Computer fair?
+ReallyFairFull sourceURL aiURL: Ja, tut er - Er platziert und bewegt seine Schiffe nach den selben Regeln wie du und erhält auch keine zusätzlichen Informationen über deine Schiffe. Bei unserem Spiel gibt es einen 'Mittelsmann', der das Spiel leitet. Genau wie du sucht sich der Computer in seinem Zug aus, auf welches Feld er schießen möchte und teilt dies dem Mittelsmann mit. Die einzige Information, die der dem Computer zurückgibt, ist die, ob der Schuss ein Schiff getroffen bzw. versenkt hat oder nicht. Ebenso kann der Computer nicht über seine eigenen Schiffe 'lügen', denn auch deine Schüsse werden an den Mittelsmann weitergeleitet, der genau weiß, an welchen Stellen die Schiffe des Computers momentan liegen. Am Ende des Spiels kannst du dir eine animierte Zusammenfassung des Spielablaufs zeigen lassen, um nachzuvollziehen, wann welches Schiff wo stand und wann wohin geschossen wurde. Wenn du besonders paranoid bist, kannst du dir auch den Quellcode anschauen (#{sourceURL}), um sicher zu gehen, dass der Computer nicht betrügt. Die vom Computer verwendete Strategie ist in groben Zügen auf #{aiURL} beschrieben.
diff --git a/messages/en.msg b/messages/en.msg
new file mode 100644
--- /dev/null
+++ b/messages/en.msg
@@ -0,0 +1,78 @@
+GameName: Battleships
+Credits: - Brought to you by Projektgruppe AFP
+GameDescription: 
+IEWarning: Looks like you're using IE. If you experience any problems using our site, please use a browser like Chrome or Firefox instead.
+NoJavaScriptWarning: Looks like you don't have JavaScript enabled. To use our site properly, however, JavaScript is needed. Please enable it.
+LinkHome: Go home
+StartPlacing: Start placing your fleet
+FireShot: Fire a shot!
+Won: You Won!
+WonByTimeout remShipsHuman@Int remShipsComputer@Int: You Won by timeout! You have #{show remShipsHuman} unsunk ships, the computer only has #{show remShipsComputer}.
+Lost: You Lost.
+LostByTimeout remShipsHuman@Int remShipsComputer@Int: You Lost by timeout! You have only #{show remShipsHuman} unsunk ships, the computer has #{show remShipsComputer}.
+Drawn remShips@Int: It's a draw. The game timed out and both of you have #{show remShips} unsunk ships.
+PlaceShips: Place your ships
+AvailableShips: Available ships
+NoPossiblePlacement: The fleet placement could not be completed.
+
+InputAgainWhenHit: shoot again after making a hit
+InputMove: allow ship movement
+InputNoviceMode: additionally show hints about impossible positions
+InputDevMode: enable developer mode
+InputDifficulty: difficulty level
+InputDifficultyEasy: easy
+InputDifficultyMedium: medium
+InputDifficultyHard: hard
+AdjustRules: Adjust the rules
+Rules: Rules
+
+ShipLength: Length
+ShipsAvailable: Available
+ShipsTotal: Total
+ResetFleet: Reset fleet
+PlaceRandom: Random
+StartPlaying: Ready!
+SkipMove: Skip moving
+MoveShip: Move one of your ships
+YourFleet: Your Fleet
+OpponentsFleet: Opponent's Fleet
+OpponentRemainingShips: You still have to find these ships:
+ShipsUnsunk: Not yet sunk
+Hints: Hints
+RemainingTurns n@Int: Only #{show n} turns remaining (after this one)!
+LastTurn: Last turn!
+
+Legend: Legend
+LegendShipWithArrow: click to move the ship
+LegendShipMovable: movable ship
+LegendShipImmovable: immovable ship
+LegendShipHit: hit
+LegendShipSunk: sunk ship
+LegendFogOfWar: undiscovered area
+LegendWater: water
+LegendLastShot: shot(s) of opponent's last turn
+LegendWaterShots: Shots at water
+LegendRightNow: Right now
+LegendTurnsAgo n@Int: #{show n} turns ago
+LegendMinTurnsAgo n@Int: At least #{show n} turns ago
+
+PauseButtonLabel: Pause
+UnpauseButtonLabel: Continue
+RestartButtonLabel: Restart
+WatchReplay: Watch replay
+SaveGame: Save game
+SaveGameExplanation: To save the current game state, bookmark the following link - this way you can always come back to the current game! Don't use this for cheating. :-)
+CurrentGame: Bookmarkable link to the current game
+
+ConfirmLeave: Do you really want to go home?
+ConfirmReplay: Do you really want to see the replay now? This ends the current game!
+About: About the game
+HowToPlay: How to play
+HowToPlaceShipsHeading: Placing your ships
+HowToPlaceShipsFull: Before the actual game starts, you have to choose where to put your ships. To do so, you press the left mouse button in the first square of where you want to put your ship and release it in the last one. To delete one of your placed ships, just click it; you will then be able to put it somewhere else. The squares around your placed ships will become grey, as ships are not allowed to touch each other. It is also possible to let a random placement be generated (fully or in part).
+HowToPlayHeading: Firing shots and moving ships
+HowToPlayFull: After the initial placement phase, you and the computer take turns. Each turn consists of firing shots (if the according option is set, you get to fire again as long as you are hitting your opponent's ships) and -optionally- moving one of your undamaged ships by one square. You fire by just clicking the desired square in your opponent's field. Undamaged ships are highlighted; those which are movable (i.e. there is no obstacle in the way) have arrows at their ends. Just click one of the arrows to move a ship. Important: Once a ship is sunk, it disappears. This means that as soon as a ship is sunk, the other ships are able to move across it.
+HowToWinHeading: End of the game
+HowToWinFull maxTurns@Int countdownTurns@Int: The game ends when one player sinks the last one of the opponent's ships, thus winning the game. To avoid boring never-ending games, however, the game also ends after at most #{show maxTurns} turns. To make you aware of the impending timeout (you might want to alter your strategy accordingly), you will see a timeout during the last #{show countdownTurns} turns. After timeout, the player who has sunk the most ships has won.
+ReallyFair: Does the computer play fair?
+ReallyFairFull sourceURL@String aiURL@String: Yes, it does - When placing and moving its ships, it has to abide by the same rules as you. During the game it does not get any more information than you; there is a 'middleman' who controls the game. Just like you do, the computer decides on a square to fire at and tells the middleman its decision. The only information the computer gets in return is whether it hit / sunk a ship or just hit water. Besides, the computer cannot 'lie' about its ships, because the middleman knows where the computer's ships are at all times. After the game ends, you can watch an animated recap of the course of the game to comprehend what happened when. If you are extra paranoid, you may want to look at the source code (#{sourceURL}) to convince yourself that the computer does not cheat. To get a high-level idea of the computer's strategy, see #{aiURL}.
diff --git a/static/.htaccess b/static/.htaccess
new file mode 100644
--- /dev/null
+++ b/static/.htaccess
@@ -0,0 +1,3 @@
+ExpiresActive On
+ExpiresDefault "access plus 1 years"
+Allow From All
diff --git a/static/img/LIFogOfWar.svg b/static/img/LIFogOfWar.svg
new file mode 100644
--- /dev/null
+++ b/static/img/LIFogOfWar.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g stroke="rgb(0,0,0)" stroke-opacity="1.0" fill="rgb(178,178,178)" fill-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g></g></g></svg>
diff --git a/static/img/LILastShot.svg b/static/img/LILastShot.svg
new file mode 100644
--- /dev/null
+++ b/static/img/LILastShot.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g stroke="rgb(0,0,0)" stroke-opacity="1.0" fill="rgb(0,0,0)" fill-opacity="0.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g><g fill="rgb(255,255,255)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">1</text></g><g stroke="rgb(255,0,0)" stroke-opacity="1.0" stroke-width="3.0"><path d="M 38.000000000000014,38.0 l -3.9968028886505635e-15,-36.0 h -36.0 l -3.9968028886505635e-15,36.0 h 36.000000000000014 Z" /></g></g><g><path d="M 40.000000000000014,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g></g></g></svg>
diff --git a/static/img/LIShipHit.svg b/static/img/LIShipHit.svg
new file mode 100644
--- /dev/null
+++ b/static/img/LIShipHit.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(128,128,128)" fill-opacity="1.0"><g fill="rgb(128,128,128)" fill-opacity="1.0"><g fill="rgb(128,128,128)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g stroke="rgb(254,63,68)" stroke-opacity="1.0" stroke-width="3.0"><path d="M -12.020815280171309,-12.020815280171309 l 24.041630560342618,24.041630560342618 " /><path d="M -12.020815280171309,12.020815280171309 l 24.041630560342618,-24.041630560342618 " /></g></g></g></g></g></svg>
diff --git a/static/img/LIShipImmovable.svg b/static/img/LIShipImmovable.svg
new file mode 100644
--- /dev/null
+++ b/static/img/LIShipImmovable.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g stroke="rgb(0,0,0)" stroke-opacity="1.0" fill="rgb(128,128,128)" fill-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g></g></g></svg>
diff --git a/static/img/LIShipMovable.svg b/static/img/LIShipMovable.svg
new file mode 100644
--- /dev/null
+++ b/static/img/LIShipMovable.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g stroke="rgb(0,0,0)" stroke-opacity="1.0" fill="rgb(196,248,62)" fill-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g></g></g></svg>
diff --git a/static/img/LIShipSunk.svg b/static/img/LIShipSunk.svg
new file mode 100644
--- /dev/null
+++ b/static/img/LIShipSunk.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="85.00000000000003" height="45.0" font-size="1" viewBox="0 0 85 45"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,42.50000000000002,22.5)"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 42.50000000000001,22.5 l -9.43689570931383e-15,-45.0 h -85.0 l -9.43689570931383e-15,45.0 Z" /></g></g></g><g><g stroke="rgb(128,128,128)" stroke-opacity="1.0" stroke-width="5.0"><path d="M 40.00000000000001,10.0 v -20.0 c 0.0,-5.522847498307934 -4.477152501692064,-10.0 -9.999999999999998 -10.0h -60.0 c -5.522847498307934,-3.38176875549089e-16 -10.0,4.477152501692064 -10.0 9.999999999999996v 20.0 c -6.76353751098178e-16,5.522847498307934 4.477152501692063,10.0 9.999999999999996 10.000000000000002h 60.0 c 5.522847498307934,1.0145306266472668e-15 10.0,-4.477152501692062 10.0 -9.999999999999996Z" /></g><g stroke="rgb(210,248,112)" stroke-opacity="1.0" stroke-width="1.0" stroke-dasharray="3.0,3.0" stroke-dashoffset="0.0"><path d="M 7.105427357601002e-15,-20.0 v 40.0 " /></g><g stroke="rgb(210,248,112)" stroke-opacity="1.0" stroke-width="1.0" stroke-dasharray="3.0,3.0" stroke-dashoffset="0.0"><path d="M 40.000000000000014,20.0 l -8.881784197001252e-15,-40.0 h -80.0 l -8.881784197001252e-15,40.0 Z" /></g></g></g></g></g></g></svg>
diff --git a/static/img/LIShipWithArrow.svg b/static/img/LIShipWithArrow.svg
new file mode 100644
--- /dev/null
+++ b/static/img/LIShipWithArrow.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g stroke="rgb(0,0,0)" stroke-opacity="1.0" fill-opacity="0.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(196,248,62)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g stroke="rgb(128,128,128)" stroke-opacity="1.0" fill-opacity="0.0" stroke-width="3.0"><path d="M 0.0,16.0 l 16.0,-16.0 l -16.0,-16.0 " /></g></g></g></g></svg>
diff --git a/static/img/LIWater.svg b/static/img/LIWater.svg
new file mode 100644
--- /dev/null
+++ b/static/img/LIWater.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g stroke="rgb(0,0,0)" stroke-opacity="1.0" fill="rgb(54,187,206)" fill-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g></g></g></svg>
diff --git a/static/img/TLIMarker 0.svg b/static/img/TLIMarker 0.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIMarker 0.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g stroke="rgb(0,0,255)" stroke-opacity="1.0" stroke-width="3.0" opacity="1.0"><path d="M -12.020815280171309,-12.020815280171309 l 24.041630560342618,24.041630560342618 " /><path d="M -12.020815280171309,12.020815280171309 l 24.041630560342618,-24.041630560342618 " /></g></g></g></g></g></svg>
diff --git a/static/img/TLIMarker 10.svg b/static/img/TLIMarker 10.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIMarker 10.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g stroke="rgb(0,0,255)" stroke-opacity="1.0" stroke-width="3.0" opacity="0.4502495587381822"><path d="M -12.020815280171309,-12.020815280171309 l 24.041630560342618,24.041630560342618 " /><path d="M -12.020815280171309,12.020815280171309 l 24.041630560342618,-24.041630560342618 " /></g></g></g></g></g></svg>
diff --git a/static/img/TLIMarker 15.svg b/static/img/TLIMarker 15.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIMarker 15.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g stroke="rgb(0,0,255)" stroke-opacity="1.0" stroke-width="3.0" opacity="0.3356026853132662"><path d="M -12.020815280171309,-12.020815280171309 l 24.041630560342618,24.041630560342618 " /><path d="M -12.020815280171309,12.020815280171309 l 24.041630560342618,-24.041630560342618 " /></g></g></g></g></g></svg>
diff --git a/static/img/TLIMarker 20.svg b/static/img/TLIMarker 20.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIMarker 20.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g stroke="rgb(0,0,255)" stroke-opacity="1.0" stroke-width="3.0" opacity="0.25"><path d="M -12.020815280171309,-12.020815280171309 l 24.041630560342618,24.041630560342618 " /><path d="M -12.020815280171309,12.020815280171309 l 24.041630560342618,-24.041630560342618 " /></g></g></g></g></g></svg>
diff --git a/static/img/TLIMarker 5.svg b/static/img/TLIMarker 5.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIMarker 5.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g stroke="rgb(0,0,255)" stroke-opacity="1.0" stroke-width="3.0" opacity="0.6244244525677107"><path d="M -12.020815280171309,-12.020815280171309 l 24.041630560342618,24.041630560342618 " /><path d="M -12.020815280171309,12.020815280171309 l 24.041630560342618,-24.041630560342618 " /></g></g></g></g></g></svg>
diff --git a/static/img/TLIWater 0.svg b/static/img/TLIWater 0.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIWater 0.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g fill="rgb(54,187,206)" fill-opacity="1.0" opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g></g></g></g></g></svg>
diff --git a/static/img/TLIWater 10.svg b/static/img/TLIWater 10.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIWater 10.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g fill="rgb(54,187,206)" fill-opacity="1.0" opacity="0.4502495587381822"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g></g></g></g></g></svg>
diff --git a/static/img/TLIWater 15.svg b/static/img/TLIWater 15.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIWater 15.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g fill="rgb(54,187,206)" fill-opacity="1.0" opacity="0.3356026853132662"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g></g></g></g></g></svg>
diff --git a/static/img/TLIWater 20.svg b/static/img/TLIWater 20.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIWater 20.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g fill="rgb(54,187,206)" fill-opacity="1.0" opacity="0.25"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g></g></g></g></g></svg>
diff --git a/static/img/TLIWater 5.svg b/static/img/TLIWater 5.svg
new file mode 100644
--- /dev/null
+++ b/static/img/TLIWater 5.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="40.000000000000014" height="40.0" font-size="1" viewBox="0 0 40 40"><g><g fill="rgb(0,0,0)" fill-opacity="0.0"><g stroke="rgb(0,0,0)" stroke-opacity="1.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g transform="matrix(1.0,0.0,0.0,1.0,20.00000000000001,20.0)"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><g fill="rgb(178,178,178)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g><g fill="rgb(54,187,206)" fill-opacity="1.0" opacity="0.6244244525677107"><g fill="rgb(54,187,206)" fill-opacity="1.0"><g fill="rgb(54,187,206)" fill-opacity="1.0"><path d="M 20.000000000000004,20.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 Z" /></g></g></g></g></g></g></g></svg>
diff --git a/static/img/dreadnought.png b/static/img/dreadnought.png
new file mode 100644
Binary files /dev/null and b/static/img/dreadnought.png differ
diff --git a/static/img/favicon.ico b/static/img/favicon.ico
new file mode 100644
Binary files /dev/null and b/static/img/favicon.ico differ
diff --git a/static/img/favicon.svg b/static/img/favicon.svg
new file mode 100644
--- /dev/null
+++ b/static/img/favicon.svg
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+ 
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events"
+     version="1.1" baseProfile="full"
+     width="16px" height="16px">
+
+  	<rect x="0" y="8" width="16" height="8" fill="blue" />
+
+ 	<circle cx="8" cy="8" r="6" stroke="green" stroke-width="1" fill="none" />
+ 	<circle cx="8" cy="8" r="3" stroke="green" stroke-width="1" fill="none"/>
+ 
+  	<line x1="8" y1="0" x2="8" y2="16" stroke="green" stroke-width="1" />
+  	<line x1="0" y1="8" x2="16" y2="8" stroke="green" stroke-width="1" />
+</svg>
diff --git a/static/img/grid.svg b/static/img/grid.svg
new file mode 100644
--- /dev/null
+++ b/static/img/grid.svg
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="480.0000000000001" height="480.0" font-size="1" viewBox="0 0 480 480"><g><g stroke="rgb(0,0,0)" stroke-opacity="1.0" fill="rgb(0,0,0)" fill-opacity="0.0" stroke-width="1.0e-2" stroke-linecap="butt" stroke-linejoin="miter" font-size="1.0em" stroke-miterlimit="10.0"><g><g><g><g><path d="M 440.0000000000001,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,420.0000000000001,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">J</text></g></g><path d="M 400.0000000000001,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,380.0000000000001,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">I</text></g></g><g><g><g><path d="M 360.0000000000001,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,340.0000000000001,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">H</text></g></g><path d="M 320.0000000000001,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,300.0000000000001,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">G</text></g></g><g><path d="M 280.00000000000006,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,260.00000000000006,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">F</text></g></g><path d="M 240.00000000000006,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,220.00000000000006,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">E</text></g></g><g><g><path d="M 200.00000000000006,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,180.00000000000006,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">D</text></g></g><path d="M 160.00000000000003,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,140.00000000000003,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">C</text></g></g><g><path d="M 120.00000000000001,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,100.00000000000001,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">B</text></g></g><path d="M 80.0,480.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,60.0,460.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">A</text></g></g><g><g><g><g><path d="M 480.0000000000001,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,420.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">10</text></g></g><path d="M 480.0000000000001,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,380.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">9</text></g></g><g><g><g><path d="M 480.0000000000001,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,340.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">8</text></g></g><path d="M 480.0000000000001,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,300.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">7</text></g></g><g><path d="M 480.0000000000001,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,260.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">6</text></g></g><path d="M 480.0000000000001,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,220.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">5</text></g></g><g><g><path d="M 480.0000000000001,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,180.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">4</text></g></g><path d="M 480.0000000000001,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,140.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">3</text></g></g><g><path d="M 480.0000000000001,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,100.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">2</text></g></g><path d="M 480.0000000000001,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,460.0000000000001,60.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">1</text></g></g><g><g><g><g><g><path d="M 440.0000000000001,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 440.0000000000001,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><g><g><path d="M 440.0000000000001,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 440.0000000000001,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 440.0000000000001,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 440.0000000000001,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><g><path d="M 440.0000000000001,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 440.0000000000001,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 440.0000000000001,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 440.0000000000001,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 400.0000000000001,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><g><path d="M 360.0000000000001,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 320.0000000000001,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 280.00000000000006,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 240.00000000000006,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 200.00000000000006,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 160.00000000000006,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><path d="M 120.00000000000003,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><path d="M 80.00000000000001,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /></g><g><g><path d="M 40.0,440.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,420.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">10</text></g></g><path d="M 40.0,400.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,380.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">9</text></g></g><g><g><g><path d="M 40.0,360.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,340.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">8</text></g></g><path d="M 40.0,320.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,300.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">7</text></g></g><g><path d="M 40.0,280.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,260.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">6</text></g></g><path d="M 40.0,240.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,220.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">5</text></g></g><g><g><path d="M 40.0,200.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,180.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">4</text></g></g><path d="M 40.0,160.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,140.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">3</text></g></g><g><path d="M 40.0,120.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,100.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">2</text></g></g><path d="M 40.0,80.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,20.0,60.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">1</text></g></g><g><g><g><path d="M 440.0000000000001,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,420.0000000000001,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">J</text></g></g><path d="M 400.0000000000001,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,380.0000000000001,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">I</text></g></g><g><g><g><path d="M 360.0000000000001,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,340.0000000000001,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">H</text></g></g><path d="M 320.0000000000001,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,300.0000000000001,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">G</text></g></g><g><path d="M 280.00000000000006,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,260.00000000000006,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">F</text></g></g><path d="M 240.00000000000006,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,220.00000000000006,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">E</text></g></g><g><g><path d="M 200.00000000000006,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,180.00000000000006,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">D</text></g></g><path d="M 160.00000000000003,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,140.00000000000003,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">C</text></g></g><g><path d="M 120.00000000000001,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,100.00000000000001,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">B</text></g></g><path d="M 80.0,40.0 l -4.440892098500626e-15,-40.0 h -40.0 l -4.440892098500626e-15,40.0 h 40.000000000000014 Z" /><g fill="rgb(210,248,112)" fill-opacity="1.0" font-size="30.0em" font-family="Monospace"><text transform="matrix(1.0,0.0,0.0,1.0,60.0,20.0)" dominant-baseline="middle" text-anchor="middle" stroke="none">A</text></g></g></g><g stroke="rgb(210,248,112)" stroke-opacity="1.0" fill-opacity="0.0" stroke-width="1.0"><path d="M 0.0,440.0 h 479.0 " /><path d="M 0.0,40.0 h 479.0 " /><path d="M 440.0,0.0 v 479.0 " /><path d="M 40.0,0.0 v 479.0 " /></g><g stroke="rgb(210,248,112)" stroke-opacity="1.0" fill-opacity="0.0" stroke-width="1.0" stroke-dasharray="3.0,3.0" stroke-dashoffset="0.0"><path d="M 0.0,400.0 h 479.0 " /><path d="M 0.0,360.0 h 479.0 " /><path d="M 0.0,320.0 h 479.0 " /><path d="M 0.0,280.0 h 479.0 " /><path d="M 0.0,240.0 h 479.0 " /><path d="M 0.0,200.0 h 479.0 " /><path d="M 0.0,160.0 h 479.0 " /><path d="M 0.0,120.0 h 479.0 " /><path d="M 0.0,80.0 h 479.0 " /><path d="M 400.0,0.0 v 479.0 " /><path d="M 360.0,0.0 v 479.0 " /><path d="M 320.0,0.0 v 479.0 " /><path d="M 280.0,0.0 v 479.0 " /><path d="M 240.0,0.0 v 479.0 " /><path d="M 200.0,0.0 v 479.0 " /><path d="M 160.0,0.0 v 479.0 " /><path d="M 120.0,0.0 v 479.0 " /><path d="M 80.0,0.0 v 479.0 " /></g><g stroke="rgb(210,248,112)" stroke-opacity="1.0" stroke-width="1.0"><path d="M 480.0000000000001,480.0 l -5.3290705182007514e-14,-480.0 h -480.0 l -5.3290705182007514e-14,480.0 h 480.0000000000001 Z" /></g></g></g></svg>
diff --git a/static/js/jquery.js b/static/js/jquery.js
new file mode 100644
--- /dev/null
+++ b/static/js/jquery.js
@@ -0,0 +1,9789 @@
+/*!
+ * jQuery JavaScript Library v1.10.2
+ * http://jquery.com/
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ *
+ * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2013-07-03T13:48Z
+ */
+(function( window, undefined ) {
+
+// Can't do this because several apps including ASP.NET trace
+// the stack via arguments.caller.callee and Firefox dies if
+// you try to trace through "use strict" call chains. (#13335)
+// Support: Firefox 18+
+//"use strict";
+var
+	// The deferred used on DOM ready
+	readyList,
+
+	// A central reference to the root jQuery(document)
+	rootjQuery,
+
+	// Support: IE<10
+	// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
+	core_strundefined = typeof undefined,
+
+	// Use the correct document accordingly with window argument (sandbox)
+	location = window.location,
+	document = window.document,
+	docElem = document.documentElement,
+
+	// Map over jQuery in case of overwrite
+	_jQuery = window.jQuery,
+
+	// Map over the $ in case of overwrite
+	_$ = window.$,
+
+	// [[Class]] -> type pairs
+	class2type = {},
+
+	// List of deleted data cache ids, so we can reuse them
+	core_deletedIds = [],
+
+	core_version = "1.10.2",
+
+	// Save a reference to some core methods
+	core_concat = core_deletedIds.concat,
+	core_push = core_deletedIds.push,
+	core_slice = core_deletedIds.slice,
+	core_indexOf = core_deletedIds.indexOf,
+	core_toString = class2type.toString,
+	core_hasOwn = class2type.hasOwnProperty,
+	core_trim = core_version.trim,
+
+	// Define a local copy of jQuery
+	jQuery = function( selector, context ) {
+		// The jQuery object is actually just the init constructor 'enhanced'
+		return new jQuery.fn.init( selector, context, rootjQuery );
+	},
+
+	// Used for matching numbers
+	core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
+
+	// Used for splitting on whitespace
+	core_rnotwhite = /\S+/g,
+
+	// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
+	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
+
+	// A simple way to check for HTML strings
+	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
+	// Strict HTML recognition (#11290: must start with <)
+	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
+
+	// Match a standalone tag
+	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
+
+	// JSON RegExp
+	rvalidchars = /^[\],:{}\s]*$/,
+	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
+	rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
+	rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
+
+	// Matches dashed string for camelizing
+	rmsPrefix = /^-ms-/,
+	rdashAlpha = /-([\da-z])/gi,
+
+	// Used by jQuery.camelCase as callback to replace()
+	fcamelCase = function( all, letter ) {
+		return letter.toUpperCase();
+	},
+
+	// The ready event handler
+	completed = function( event ) {
+
+		// readyState === "complete" is good enough for us to call the dom ready in oldIE
+		if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
+			detach();
+			jQuery.ready();
+		}
+	},
+	// Clean-up method for dom ready events
+	detach = function() {
+		if ( document.addEventListener ) {
+			document.removeEventListener( "DOMContentLoaded", completed, false );
+			window.removeEventListener( "load", completed, false );
+
+		} else {
+			document.detachEvent( "onreadystatechange", completed );
+			window.detachEvent( "onload", completed );
+		}
+	};
+
+jQuery.fn = jQuery.prototype = {
+	// The current version of jQuery being used
+	jquery: core_version,
+
+	constructor: jQuery,
+	init: function( selector, context, rootjQuery ) {
+		var match, elem;
+
+		// HANDLE: $(""), $(null), $(undefined), $(false)
+		if ( !selector ) {
+			return this;
+		}
+
+		// Handle HTML strings
+		if ( typeof selector === "string" ) {
+			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
+				// Assume that strings that start and end with <> are HTML and skip the regex check
+				match = [ null, selector, null ];
+
+			} else {
+				match = rquickExpr.exec( selector );
+			}
+
+			// Match html or make sure no context is specified for #id
+			if ( match && (match[1] || !context) ) {
+
+				// HANDLE: $(html) -> $(array)
+				if ( match[1] ) {
+					context = context instanceof jQuery ? context[0] : context;
+
+					// scripts is true for back-compat
+					jQuery.merge( this, jQuery.parseHTML(
+						match[1],
+						context && context.nodeType ? context.ownerDocument || context : document,
+						true
+					) );
+
+					// HANDLE: $(html, props)
+					if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
+						for ( match in context ) {
+							// Properties of context are called as methods if possible
+							if ( jQuery.isFunction( this[ match ] ) ) {
+								this[ match ]( context[ match ] );
+
+							// ...and otherwise set as attributes
+							} else {
+								this.attr( match, context[ match ] );
+							}
+						}
+					}
+
+					return this;
+
+				// HANDLE: $(#id)
+				} else {
+					elem = document.getElementById( match[2] );
+
+					// Check parentNode to catch when Blackberry 4.6 returns
+					// nodes that are no longer in the document #6963
+					if ( elem && elem.parentNode ) {
+						// Handle the case where IE and Opera return items
+						// by name instead of ID
+						if ( elem.id !== match[2] ) {
+							return rootjQuery.find( selector );
+						}
+
+						// Otherwise, we inject the element directly into the jQuery object
+						this.length = 1;
+						this[0] = elem;
+					}
+
+					this.context = document;
+					this.selector = selector;
+					return this;
+				}
+
+			// HANDLE: $(expr, $(...))
+			} else if ( !context || context.jquery ) {
+				return ( context || rootjQuery ).find( selector );
+
+			// HANDLE: $(expr, context)
+			// (which is just equivalent to: $(context).find(expr)
+			} else {
+				return this.constructor( context ).find( selector );
+			}
+
+		// HANDLE: $(DOMElement)
+		} else if ( selector.nodeType ) {
+			this.context = this[0] = selector;
+			this.length = 1;
+			return this;
+
+		// HANDLE: $(function)
+		// Shortcut for document ready
+		} else if ( jQuery.isFunction( selector ) ) {
+			return rootjQuery.ready( selector );
+		}
+
+		if ( selector.selector !== undefined ) {
+			this.selector = selector.selector;
+			this.context = selector.context;
+		}
+
+		return jQuery.makeArray( selector, this );
+	},
+
+	// Start with an empty selector
+	selector: "",
+
+	// The default length of a jQuery object is 0
+	length: 0,
+
+	toArray: function() {
+		return core_slice.call( this );
+	},
+
+	// Get the Nth element in the matched element set OR
+	// Get the whole matched element set as a clean array
+	get: function( num ) {
+		return num == null ?
+
+			// Return a 'clean' array
+			this.toArray() :
+
+			// Return just the object
+			( num < 0 ? this[ this.length + num ] : this[ num ] );
+	},
+
+	// Take an array of elements and push it onto the stack
+	// (returning the new matched element set)
+	pushStack: function( elems ) {
+
+		// Build a new jQuery matched element set
+		var ret = jQuery.merge( this.constructor(), elems );
+
+		// Add the old object onto the stack (as a reference)
+		ret.prevObject = this;
+		ret.context = this.context;
+
+		// Return the newly-formed element set
+		return ret;
+	},
+
+	// Execute a callback for every element in the matched set.
+	// (You can seed the arguments with an array of args, but this is
+	// only used internally.)
+	each: function( callback, args ) {
+		return jQuery.each( this, callback, args );
+	},
+
+	ready: function( fn ) {
+		// Add the callback
+		jQuery.ready.promise().done( fn );
+
+		return this;
+	},
+
+	slice: function() {
+		return this.pushStack( core_slice.apply( this, arguments ) );
+	},
+
+	first: function() {
+		return this.eq( 0 );
+	},
+
+	last: function() {
+		return this.eq( -1 );
+	},
+
+	eq: function( i ) {
+		var len = this.length,
+			j = +i + ( i < 0 ? len : 0 );
+		return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
+	},
+
+	map: function( callback ) {
+		return this.pushStack( jQuery.map(this, function( elem, i ) {
+			return callback.call( elem, i, elem );
+		}));
+	},
+
+	end: function() {
+		return this.prevObject || this.constructor(null);
+	},
+
+	// For internal use only.
+	// Behaves like an Array's method, not like a jQuery method.
+	push: core_push,
+	sort: [].sort,
+	splice: [].splice
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+jQuery.extend = jQuery.fn.extend = function() {
+	var src, copyIsArray, copy, name, options, clone,
+		target = arguments[0] || {},
+		i = 1,
+		length = arguments.length,
+		deep = false;
+
+	// Handle a deep copy situation
+	if ( typeof target === "boolean" ) {
+		deep = target;
+		target = arguments[1] || {};
+		// skip the boolean and the target
+		i = 2;
+	}
+
+	// Handle case when target is a string or something (possible in deep copy)
+	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+		target = {};
+	}
+
+	// extend jQuery itself if only one argument is passed
+	if ( length === i ) {
+		target = this;
+		--i;
+	}
+
+	for ( ; i < length; i++ ) {
+		// Only deal with non-null/undefined values
+		if ( (options = arguments[ i ]) != null ) {
+			// Extend the base object
+			for ( name in options ) {
+				src = target[ name ];
+				copy = options[ name ];
+
+				// Prevent never-ending loop
+				if ( target === copy ) {
+					continue;
+				}
+
+				// Recurse if we're merging plain objects or arrays
+				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
+					if ( copyIsArray ) {
+						copyIsArray = false;
+						clone = src && jQuery.isArray(src) ? src : [];
+
+					} else {
+						clone = src && jQuery.isPlainObject(src) ? src : {};
+					}
+
+					// Never move original objects, clone them
+					target[ name ] = jQuery.extend( deep, clone, copy );
+
+				// Don't bring in undefined values
+				} else if ( copy !== undefined ) {
+					target[ name ] = copy;
+				}
+			}
+		}
+	}
+
+	// Return the modified object
+	return target;
+};
+
+jQuery.extend({
+	// Unique for each copy of jQuery on the page
+	// Non-digits removed to match rinlinejQuery
+	expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
+
+	noConflict: function( deep ) {
+		if ( window.$ === jQuery ) {
+			window.$ = _$;
+		}
+
+		if ( deep && window.jQuery === jQuery ) {
+			window.jQuery = _jQuery;
+		}
+
+		return jQuery;
+	},
+
+	// Is the DOM ready to be used? Set to true once it occurs.
+	isReady: false,
+
+	// A counter to track how many items to wait for before
+	// the ready event fires. See #6781
+	readyWait: 1,
+
+	// Hold (or release) the ready event
+	holdReady: function( hold ) {
+		if ( hold ) {
+			jQuery.readyWait++;
+		} else {
+			jQuery.ready( true );
+		}
+	},
+
+	// Handle when the DOM is ready
+	ready: function( wait ) {
+
+		// Abort if there are pending holds or we're already ready
+		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
+			return;
+		}
+
+		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+		if ( !document.body ) {
+			return setTimeout( jQuery.ready );
+		}
+
+		// Remember that the DOM is ready
+		jQuery.isReady = true;
+
+		// If a normal DOM Ready event fired, decrement, and wait if need be
+		if ( wait !== true && --jQuery.readyWait > 0 ) {
+			return;
+		}
+
+		// If there are functions bound, to execute
+		readyList.resolveWith( document, [ jQuery ] );
+
+		// Trigger any bound ready events
+		if ( jQuery.fn.trigger ) {
+			jQuery( document ).trigger("ready").off("ready");
+		}
+	},
+
+	// See test/unit/core.js for details concerning isFunction.
+	// Since version 1.3, DOM methods and functions like alert
+	// aren't supported. They return false on IE (#2968).
+	isFunction: function( obj ) {
+		return jQuery.type(obj) === "function";
+	},
+
+	isArray: Array.isArray || function( obj ) {
+		return jQuery.type(obj) === "array";
+	},
+
+	isWindow: function( obj ) {
+		/* jshint eqeqeq: false */
+		return obj != null && obj == obj.window;
+	},
+
+	isNumeric: function( obj ) {
+		return !isNaN( parseFloat(obj) ) && isFinite( obj );
+	},
+
+	type: function( obj ) {
+		if ( obj == null ) {
+			return String( obj );
+		}
+		return typeof obj === "object" || typeof obj === "function" ?
+			class2type[ core_toString.call(obj) ] || "object" :
+			typeof obj;
+	},
+
+	isPlainObject: function( obj ) {
+		var key;
+
+		// Must be an Object.
+		// Because of IE, we also have to check the presence of the constructor property.
+		// Make sure that DOM nodes and window objects don't pass through, as well
+		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+			return false;
+		}
+
+		try {
+			// Not own constructor property must be Object
+			if ( obj.constructor &&
+				!core_hasOwn.call(obj, "constructor") &&
+				!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
+				return false;
+			}
+		} catch ( e ) {
+			// IE8,9 Will throw exceptions on certain host objects #9897
+			return false;
+		}
+
+		// Support: IE<9
+		// Handle iteration over inherited properties before own properties.
+		if ( jQuery.support.ownLast ) {
+			for ( key in obj ) {
+				return core_hasOwn.call( obj, key );
+			}
+		}
+
+		// Own properties are enumerated firstly, so to speed up,
+		// if last one is own, then all properties are own.
+		for ( key in obj ) {}
+
+		return key === undefined || core_hasOwn.call( obj, key );
+	},
+
+	isEmptyObject: function( obj ) {
+		var name;
+		for ( name in obj ) {
+			return false;
+		}
+		return true;
+	},
+
+	error: function( msg ) {
+		throw new Error( msg );
+	},
+
+	// data: string of html
+	// context (optional): If specified, the fragment will be created in this context, defaults to document
+	// keepScripts (optional): If true, will include scripts passed in the html string
+	parseHTML: function( data, context, keepScripts ) {
+		if ( !data || typeof data !== "string" ) {
+			return null;
+		}
+		if ( typeof context === "boolean" ) {
+			keepScripts = context;
+			context = false;
+		}
+		context = context || document;
+
+		var parsed = rsingleTag.exec( data ),
+			scripts = !keepScripts && [];
+
+		// Single tag
+		if ( parsed ) {
+			return [ context.createElement( parsed[1] ) ];
+		}
+
+		parsed = jQuery.buildFragment( [ data ], context, scripts );
+		if ( scripts ) {
+			jQuery( scripts ).remove();
+		}
+		return jQuery.merge( [], parsed.childNodes );
+	},
+
+	parseJSON: function( data ) {
+		// Attempt to parse using the native JSON parser first
+		if ( window.JSON && window.JSON.parse ) {
+			return window.JSON.parse( data );
+		}
+
+		if ( data === null ) {
+			return data;
+		}
+
+		if ( typeof data === "string" ) {
+
+			// Make sure leading/trailing whitespace is removed (IE can't handle it)
+			data = jQuery.trim( data );
+
+			if ( data ) {
+				// Make sure the incoming data is actual JSON
+				// Logic borrowed from http://json.org/json2.js
+				if ( rvalidchars.test( data.replace( rvalidescape, "@" )
+					.replace( rvalidtokens, "]" )
+					.replace( rvalidbraces, "")) ) {
+
+					return ( new Function( "return " + data ) )();
+				}
+			}
+		}
+
+		jQuery.error( "Invalid JSON: " + data );
+	},
+
+	// Cross-browser xml parsing
+	parseXML: function( data ) {
+		var xml, tmp;
+		if ( !data || typeof data !== "string" ) {
+			return null;
+		}
+		try {
+			if ( window.DOMParser ) { // Standard
+				tmp = new DOMParser();
+				xml = tmp.parseFromString( data , "text/xml" );
+			} else { // IE
+				xml = new ActiveXObject( "Microsoft.XMLDOM" );
+				xml.async = "false";
+				xml.loadXML( data );
+			}
+		} catch( e ) {
+			xml = undefined;
+		}
+		if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
+			jQuery.error( "Invalid XML: " + data );
+		}
+		return xml;
+	},
+
+	noop: function() {},
+
+	// Evaluates a script in a global context
+	// Workarounds based on findings by Jim Driscoll
+	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
+	globalEval: function( data ) {
+		if ( data && jQuery.trim( data ) ) {
+			// We use execScript on Internet Explorer
+			// We use an anonymous function so that context is window
+			// rather than jQuery in Firefox
+			( window.execScript || function( data ) {
+				window[ "eval" ].call( window, data );
+			} )( data );
+		}
+	},
+
+	// Convert dashed to camelCase; used by the css and data modules
+	// Microsoft forgot to hump their vendor prefix (#9572)
+	camelCase: function( string ) {
+		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+	},
+
+	nodeName: function( elem, name ) {
+		return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
+	},
+
+	// args is for internal usage only
+	each: function( obj, callback, args ) {
+		var value,
+			i = 0,
+			length = obj.length,
+			isArray = isArraylike( obj );
+
+		if ( args ) {
+			if ( isArray ) {
+				for ( ; i < length; i++ ) {
+					value = callback.apply( obj[ i ], args );
+
+					if ( value === false ) {
+						break;
+					}
+				}
+			} else {
+				for ( i in obj ) {
+					value = callback.apply( obj[ i ], args );
+
+					if ( value === false ) {
+						break;
+					}
+				}
+			}
+
+		// A special, fast, case for the most common use of each
+		} else {
+			if ( isArray ) {
+				for ( ; i < length; i++ ) {
+					value = callback.call( obj[ i ], i, obj[ i ] );
+
+					if ( value === false ) {
+						break;
+					}
+				}
+			} else {
+				for ( i in obj ) {
+					value = callback.call( obj[ i ], i, obj[ i ] );
+
+					if ( value === false ) {
+						break;
+					}
+				}
+			}
+		}
+
+		return obj;
+	},
+
+	// Use native String.trim function wherever possible
+	trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
+		function( text ) {
+			return text == null ?
+				"" :
+				core_trim.call( text );
+		} :
+
+		// Otherwise use our own trimming functionality
+		function( text ) {
+			return text == null ?
+				"" :
+				( text + "" ).replace( rtrim, "" );
+		},
+
+	// results is for internal usage only
+	makeArray: function( arr, results ) {
+		var ret = results || [];
+
+		if ( arr != null ) {
+			if ( isArraylike( Object(arr) ) ) {
+				jQuery.merge( ret,
+					typeof arr === "string" ?
+					[ arr ] : arr
+				);
+			} else {
+				core_push.call( ret, arr );
+			}
+		}
+
+		return ret;
+	},
+
+	inArray: function( elem, arr, i ) {
+		var len;
+
+		if ( arr ) {
+			if ( core_indexOf ) {
+				return core_indexOf.call( arr, elem, i );
+			}
+
+			len = arr.length;
+			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
+
+			for ( ; i < len; i++ ) {
+				// Skip accessing in sparse arrays
+				if ( i in arr && arr[ i ] === elem ) {
+					return i;
+				}
+			}
+		}
+
+		return -1;
+	},
+
+	merge: function( first, second ) {
+		var l = second.length,
+			i = first.length,
+			j = 0;
+
+		if ( typeof l === "number" ) {
+			for ( ; j < l; j++ ) {
+				first[ i++ ] = second[ j ];
+			}
+		} else {
+			while ( second[j] !== undefined ) {
+				first[ i++ ] = second[ j++ ];
+			}
+		}
+
+		first.length = i;
+
+		return first;
+	},
+
+	grep: function( elems, callback, inv ) {
+		var retVal,
+			ret = [],
+			i = 0,
+			length = elems.length;
+		inv = !!inv;
+
+		// Go through the array, only saving the items
+		// that pass the validator function
+		for ( ; i < length; i++ ) {
+			retVal = !!callback( elems[ i ], i );
+			if ( inv !== retVal ) {
+				ret.push( elems[ i ] );
+			}
+		}
+
+		return ret;
+	},
+
+	// arg is for internal usage only
+	map: function( elems, callback, arg ) {
+		var value,
+			i = 0,
+			length = elems.length,
+			isArray = isArraylike( elems ),
+			ret = [];
+
+		// Go through the array, translating each of the items to their
+		if ( isArray ) {
+			for ( ; i < length; i++ ) {
+				value = callback( elems[ i ], i, arg );
+
+				if ( value != null ) {
+					ret[ ret.length ] = value;
+				}
+			}
+
+		// Go through every key on the object,
+		} else {
+			for ( i in elems ) {
+				value = callback( elems[ i ], i, arg );
+
+				if ( value != null ) {
+					ret[ ret.length ] = value;
+				}
+			}
+		}
+
+		// Flatten any nested arrays
+		return core_concat.apply( [], ret );
+	},
+
+	// A global GUID counter for objects
+	guid: 1,
+
+	// Bind a function to a context, optionally partially applying any
+	// arguments.
+	proxy: function( fn, context ) {
+		var args, proxy, tmp;
+
+		if ( typeof context === "string" ) {
+			tmp = fn[ context ];
+			context = fn;
+			fn = tmp;
+		}
+
+		// Quick check to determine if target is callable, in the spec
+		// this throws a TypeError, but we will just return undefined.
+		if ( !jQuery.isFunction( fn ) ) {
+			return undefined;
+		}
+
+		// Simulated bind
+		args = core_slice.call( arguments, 2 );
+		proxy = function() {
+			return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
+		};
+
+		// Set the guid of unique handler to the same of original handler, so it can be removed
+		proxy.guid = fn.guid = fn.guid || jQuery.guid++;
+
+		return proxy;
+	},
+
+	// Multifunctional method to get and set values of a collection
+	// The value/s can optionally be executed if it's a function
+	access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
+		var i = 0,
+			length = elems.length,
+			bulk = key == null;
+
+		// Sets many values
+		if ( jQuery.type( key ) === "object" ) {
+			chainable = true;
+			for ( i in key ) {
+				jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
+			}
+
+		// Sets one value
+		} else if ( value !== undefined ) {
+			chainable = true;
+
+			if ( !jQuery.isFunction( value ) ) {
+				raw = true;
+			}
+
+			if ( bulk ) {
+				// Bulk operations run against the entire set
+				if ( raw ) {
+					fn.call( elems, value );
+					fn = null;
+
+				// ...except when executing function values
+				} else {
+					bulk = fn;
+					fn = function( elem, key, value ) {
+						return bulk.call( jQuery( elem ), value );
+					};
+				}
+			}
+
+			if ( fn ) {
+				for ( ; i < length; i++ ) {
+					fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
+				}
+			}
+		}
+
+		return chainable ?
+			elems :
+
+			// Gets
+			bulk ?
+				fn.call( elems ) :
+				length ? fn( elems[0], key ) : emptyGet;
+	},
+
+	now: function() {
+		return ( new Date() ).getTime();
+	},
+
+	// A method for quickly swapping in/out CSS properties to get correct calculations.
+	// Note: this method belongs to the css module but it's needed here for the support module.
+	// If support gets modularized, this method should be moved back to the css module.
+	swap: function( elem, options, callback, args ) {
+		var ret, name,
+			old = {};
+
+		// Remember the old values, and insert the new ones
+		for ( name in options ) {
+			old[ name ] = elem.style[ name ];
+			elem.style[ name ] = options[ name ];
+		}
+
+		ret = callback.apply( elem, args || [] );
+
+		// Revert the old values
+		for ( name in options ) {
+			elem.style[ name ] = old[ name ];
+		}
+
+		return ret;
+	}
+});
+
+jQuery.ready.promise = function( obj ) {
+	if ( !readyList ) {
+
+		readyList = jQuery.Deferred();
+
+		// Catch cases where $(document).ready() is called after the browser event has already occurred.
+		// we once tried to use readyState "interactive" here, but it caused issues like the one
+		// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
+		if ( document.readyState === "complete" ) {
+			// Handle it asynchronously to allow scripts the opportunity to delay ready
+			setTimeout( jQuery.ready );
+
+		// Standards-based browsers support DOMContentLoaded
+		} else if ( document.addEventListener ) {
+			// Use the handy event callback
+			document.addEventListener( "DOMContentLoaded", completed, false );
+
+			// A fallback to window.onload, that will always work
+			window.addEventListener( "load", completed, false );
+
+		// If IE event model is used
+		} else {
+			// Ensure firing before onload, maybe late but safe also for iframes
+			document.attachEvent( "onreadystatechange", completed );
+
+			// A fallback to window.onload, that will always work
+			window.attachEvent( "onload", completed );
+
+			// If IE and not a frame
+			// continually check to see if the document is ready
+			var top = false;
+
+			try {
+				top = window.frameElement == null && document.documentElement;
+			} catch(e) {}
+
+			if ( top && top.doScroll ) {
+				(function doScrollCheck() {
+					if ( !jQuery.isReady ) {
+
+						try {
+							// Use the trick by Diego Perini
+							// http://javascript.nwbox.com/IEContentLoaded/
+							top.doScroll("left");
+						} catch(e) {
+							return setTimeout( doScrollCheck, 50 );
+						}
+
+						// detach all dom ready events
+						detach();
+
+						// and execute any waiting functions
+						jQuery.ready();
+					}
+				})();
+			}
+		}
+	}
+	return readyList.promise( obj );
+};
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
+	class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+function isArraylike( obj ) {
+	var length = obj.length,
+		type = jQuery.type( obj );
+
+	if ( jQuery.isWindow( obj ) ) {
+		return false;
+	}
+
+	if ( obj.nodeType === 1 && length ) {
+		return true;
+	}
+
+	return type === "array" || type !== "function" &&
+		( length === 0 ||
+		typeof length === "number" && length > 0 && ( length - 1 ) in obj );
+}
+
+// All jQuery objects should point back to these
+rootjQuery = jQuery(document);
+/*!
+ * Sizzle CSS Selector Engine v1.10.2
+ * http://sizzlejs.com/
+ *
+ * Copyright 2013 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2013-07-03
+ */
+(function( window, undefined ) {
+
+var i,
+	support,
+	cachedruns,
+	Expr,
+	getText,
+	isXML,
+	compile,
+	outermostContext,
+	sortInput,
+
+	// Local document vars
+	setDocument,
+	document,
+	docElem,
+	documentIsHTML,
+	rbuggyQSA,
+	rbuggyMatches,
+	matches,
+	contains,
+
+	// Instance-specific data
+	expando = "sizzle" + -(new Date()),
+	preferredDoc = window.document,
+	dirruns = 0,
+	done = 0,
+	classCache = createCache(),
+	tokenCache = createCache(),
+	compilerCache = createCache(),
+	hasDuplicate = false,
+	sortOrder = function( a, b ) {
+		if ( a === b ) {
+			hasDuplicate = true;
+			return 0;
+		}
+		return 0;
+	},
+
+	// General-purpose constants
+	strundefined = typeof undefined,
+	MAX_NEGATIVE = 1 << 31,
+
+	// Instance methods
+	hasOwn = ({}).hasOwnProperty,
+	arr = [],
+	pop = arr.pop,
+	push_native = arr.push,
+	push = arr.push,
+	slice = arr.slice,
+	// Use a stripped-down indexOf if we can't use a native one
+	indexOf = arr.indexOf || function( elem ) {
+		var i = 0,
+			len = this.length;
+		for ( ; i < len; i++ ) {
+			if ( this[i] === elem ) {
+				return i;
+			}
+		}
+		return -1;
+	},
+
+	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
+
+	// Regular expressions
+
+	// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
+	whitespace = "[\\x20\\t\\r\\n\\f]",
+	// http://www.w3.org/TR/css3-syntax/#characters
+	characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
+
+	// Loosely modeled on CSS identifier characters
+	// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
+	// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
+	identifier = characterEncoding.replace( "w", "w#" ),
+
+	// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
+	attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
+		"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
+
+	// Prefer arguments quoted,
+	//   then not containing pseudos/brackets,
+	//   then attribute selectors/non-parenthetical expressions,
+	//   then anything else
+	// These preferences are here to reduce the number of selectors
+	//   needing tokenize in the PSEUDO preFilter
+	pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
+
+	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
+	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
+
+	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
+	rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
+
+	rsibling = new RegExp( whitespace + "*[+~]" ),
+	rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
+
+	rpseudo = new RegExp( pseudos ),
+	ridentifier = new RegExp( "^" + identifier + "$" ),
+
+	matchExpr = {
+		"ID": new RegExp( "^#(" + characterEncoding + ")" ),
+		"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
+		"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
+		"ATTR": new RegExp( "^" + attributes ),
+		"PSEUDO": new RegExp( "^" + pseudos ),
+		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
+			"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
+			"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
+		"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
+		// For use in libraries implementing .is()
+		// We use this for POS matching in `select`
+		"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
+			whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
+	},
+
+	rnative = /^[^{]+\{\s*\[native \w/,
+
+	// Easily-parseable/retrievable ID or TAG or CLASS selectors
+	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
+
+	rinputs = /^(?:input|select|textarea|button)$/i,
+	rheader = /^h\d$/i,
+
+	rescape = /'|\\/g,
+
+	// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
+	runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
+	funescape = function( _, escaped, escapedWhitespace ) {
+		var high = "0x" + escaped - 0x10000;
+		// NaN means non-codepoint
+		// Support: Firefox
+		// Workaround erroneous numeric interpretation of +"0x"
+		return high !== high || escapedWhitespace ?
+			escaped :
+			// BMP codepoint
+			high < 0 ?
+				String.fromCharCode( high + 0x10000 ) :
+				// Supplemental Plane codepoint (surrogate pair)
+				String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
+	};
+
+// Optimize for push.apply( _, NodeList )
+try {
+	push.apply(
+		(arr = slice.call( preferredDoc.childNodes )),
+		preferredDoc.childNodes
+	);
+	// Support: Android<4.0
+	// Detect silently failing push.apply
+	arr[ preferredDoc.childNodes.length ].nodeType;
+} catch ( e ) {
+	push = { apply: arr.length ?
+
+		// Leverage slice if possible
+		function( target, els ) {
+			push_native.apply( target, slice.call(els) );
+		} :
+
+		// Support: IE<9
+		// Otherwise append directly
+		function( target, els ) {
+			var j = target.length,
+				i = 0;
+			// Can't trust NodeList.length
+			while ( (target[j++] = els[i++]) ) {}
+			target.length = j - 1;
+		}
+	};
+}
+
+function Sizzle( selector, context, results, seed ) {
+	var match, elem, m, nodeType,
+		// QSA vars
+		i, groups, old, nid, newContext, newSelector;
+
+	if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
+		setDocument( context );
+	}
+
+	context = context || document;
+	results = results || [];
+
+	if ( !selector || typeof selector !== "string" ) {
+		return results;
+	}
+
+	if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
+		return [];
+	}
+
+	if ( documentIsHTML && !seed ) {
+
+		// Shortcuts
+		if ( (match = rquickExpr.exec( selector )) ) {
+			// Speed-up: Sizzle("#ID")
+			if ( (m = match[1]) ) {
+				if ( nodeType === 9 ) {
+					elem = context.getElementById( m );
+					// Check parentNode to catch when Blackberry 4.6 returns
+					// nodes that are no longer in the document #6963
+					if ( elem && elem.parentNode ) {
+						// Handle the case where IE, Opera, and Webkit return items
+						// by name instead of ID
+						if ( elem.id === m ) {
+							results.push( elem );
+							return results;
+						}
+					} else {
+						return results;
+					}
+				} else {
+					// Context is not a document
+					if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
+						contains( context, elem ) && elem.id === m ) {
+						results.push( elem );
+						return results;
+					}
+				}
+
+			// Speed-up: Sizzle("TAG")
+			} else if ( match[2] ) {
+				push.apply( results, context.getElementsByTagName( selector ) );
+				return results;
+
+			// Speed-up: Sizzle(".CLASS")
+			} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
+				push.apply( results, context.getElementsByClassName( m ) );
+				return results;
+			}
+		}
+
+		// QSA path
+		if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
+			nid = old = expando;
+			newContext = context;
+			newSelector = nodeType === 9 && selector;
+
+			// qSA works strangely on Element-rooted queries
+			// We can work around this by specifying an extra ID on the root
+			// and working up from there (Thanks to Andrew Dupont for the technique)
+			// IE 8 doesn't work on object elements
+			if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+				groups = tokenize( selector );
+
+				if ( (old = context.getAttribute("id")) ) {
+					nid = old.replace( rescape, "\\$&" );
+				} else {
+					context.setAttribute( "id", nid );
+				}
+				nid = "[id='" + nid + "'] ";
+
+				i = groups.length;
+				while ( i-- ) {
+					groups[i] = nid + toSelector( groups[i] );
+				}
+				newContext = rsibling.test( selector ) && context.parentNode || context;
+				newSelector = groups.join(",");
+			}
+
+			if ( newSelector ) {
+				try {
+					push.apply( results,
+						newContext.querySelectorAll( newSelector )
+					);
+					return results;
+				} catch(qsaError) {
+				} finally {
+					if ( !old ) {
+						context.removeAttribute("id");
+					}
+				}
+			}
+		}
+	}
+
+	// All others
+	return select( selector.replace( rtrim, "$1" ), context, results, seed );
+}
+
+/**
+ * Create key-value caches of limited size
+ * @returns {Function(string, Object)} Returns the Object data after storing it on itself with
+ *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
+ *	deleting the oldest entry
+ */
+function createCache() {
+	var keys = [];
+
+	function cache( key, value ) {
+		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
+		if ( keys.push( key += " " ) > Expr.cacheLength ) {
+			// Only keep the most recent entries
+			delete cache[ keys.shift() ];
+		}
+		return (cache[ key ] = value);
+	}
+	return cache;
+}
+
+/**
+ * Mark a function for special use by Sizzle
+ * @param {Function} fn The function to mark
+ */
+function markFunction( fn ) {
+	fn[ expando ] = true;
+	return fn;
+}
+
+/**
+ * Support testing using an element
+ * @param {Function} fn Passed the created div and expects a boolean result
+ */
+function assert( fn ) {
+	var div = document.createElement("div");
+
+	try {
+		return !!fn( div );
+	} catch (e) {
+		return false;
+	} finally {
+		// Remove from its parent by default
+		if ( div.parentNode ) {
+			div.parentNode.removeChild( div );
+		}
+		// release memory in IE
+		div = null;
+	}
+}
+
+/**
+ * Adds the same handler for all of the specified attrs
+ * @param {String} attrs Pipe-separated list of attributes
+ * @param {Function} handler The method that will be applied
+ */
+function addHandle( attrs, handler ) {
+	var arr = attrs.split("|"),
+		i = attrs.length;
+
+	while ( i-- ) {
+		Expr.attrHandle[ arr[i] ] = handler;
+	}
+}
+
+/**
+ * Checks document order of two siblings
+ * @param {Element} a
+ * @param {Element} b
+ * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
+ */
+function siblingCheck( a, b ) {
+	var cur = b && a,
+		diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
+			( ~b.sourceIndex || MAX_NEGATIVE ) -
+			( ~a.sourceIndex || MAX_NEGATIVE );
+
+	// Use IE sourceIndex if available on both nodes
+	if ( diff ) {
+		return diff;
+	}
+
+	// Check if b follows a
+	if ( cur ) {
+		while ( (cur = cur.nextSibling) ) {
+			if ( cur === b ) {
+				return -1;
+			}
+		}
+	}
+
+	return a ? 1 : -1;
+}
+
+/**
+ * Returns a function to use in pseudos for input types
+ * @param {String} type
+ */
+function createInputPseudo( type ) {
+	return function( elem ) {
+		var name = elem.nodeName.toLowerCase();
+		return name === "input" && elem.type === type;
+	};
+}
+
+/**
+ * Returns a function to use in pseudos for buttons
+ * @param {String} type
+ */
+function createButtonPseudo( type ) {
+	return function( elem ) {
+		var name = elem.nodeName.toLowerCase();
+		return (name === "input" || name === "button") && elem.type === type;
+	};
+}
+
+/**
+ * Returns a function to use in pseudos for positionals
+ * @param {Function} fn
+ */
+function createPositionalPseudo( fn ) {
+	return markFunction(function( argument ) {
+		argument = +argument;
+		return markFunction(function( seed, matches ) {
+			var j,
+				matchIndexes = fn( [], seed.length, argument ),
+				i = matchIndexes.length;
+
+			// Match elements found at the specified indexes
+			while ( i-- ) {
+				if ( seed[ (j = matchIndexes[i]) ] ) {
+					seed[j] = !(matches[j] = seed[j]);
+				}
+			}
+		});
+	});
+}
+
+/**
+ * Detect xml
+ * @param {Element|Object} elem An element or a document
+ */
+isXML = Sizzle.isXML = function( elem ) {
+	// documentElement is verified for cases where it doesn't yet exist
+	// (such as loading iframes in IE - #4833)
+	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
+	return documentElement ? documentElement.nodeName !== "HTML" : false;
+};
+
+// Expose support vars for convenience
+support = Sizzle.support = {};
+
+/**
+ * Sets document-related variables once based on the current document
+ * @param {Element|Object} [doc] An element or document object to use to set the document
+ * @returns {Object} Returns the current document
+ */
+setDocument = Sizzle.setDocument = function( node ) {
+	var doc = node ? node.ownerDocument || node : preferredDoc,
+		parent = doc.defaultView;
+
+	// If no document and documentElement is available, return
+	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
+		return document;
+	}
+
+	// Set our document
+	document = doc;
+	docElem = doc.documentElement;
+
+	// Support tests
+	documentIsHTML = !isXML( doc );
+
+	// Support: IE>8
+	// If iframe document is assigned to "document" variable and if iframe has been reloaded,
+	// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
+	// IE6-8 do not support the defaultView property so parent will be undefined
+	if ( parent && parent.attachEvent && parent !== parent.top ) {
+		parent.attachEvent( "onbeforeunload", function() {
+			setDocument();
+		});
+	}
+
+	/* Attributes
+	---------------------------------------------------------------------- */
+
+	// Support: IE<8
+	// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
+	support.attributes = assert(function( div ) {
+		div.className = "i";
+		return !div.getAttribute("className");
+	});
+
+	/* getElement(s)By*
+	---------------------------------------------------------------------- */
+
+	// Check if getElementsByTagName("*") returns only elements
+	support.getElementsByTagName = assert(function( div ) {
+		div.appendChild( doc.createComment("") );
+		return !div.getElementsByTagName("*").length;
+	});
+
+	// Check if getElementsByClassName can be trusted
+	support.getElementsByClassName = assert(function( div ) {
+		div.innerHTML = "<div class='a'></div><div class='a i'></div>";
+
+		// Support: Safari<4
+		// Catch class over-caching
+		div.firstChild.className = "i";
+		// Support: Opera<10
+		// Catch gEBCN failure to find non-leading classes
+		return div.getElementsByClassName("i").length === 2;
+	});
+
+	// Support: IE<10
+	// Check if getElementById returns elements by name
+	// The broken getElementById methods don't pick up programatically-set names,
+	// so use a roundabout getElementsByName test
+	support.getById = assert(function( div ) {
+		docElem.appendChild( div ).id = expando;
+		return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
+	});
+
+	// ID find and filter
+	if ( support.getById ) {
+		Expr.find["ID"] = function( id, context ) {
+			if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
+				var m = context.getElementById( id );
+				// Check parentNode to catch when Blackberry 4.6 returns
+				// nodes that are no longer in the document #6963
+				return m && m.parentNode ? [m] : [];
+			}
+		};
+		Expr.filter["ID"] = function( id ) {
+			var attrId = id.replace( runescape, funescape );
+			return function( elem ) {
+				return elem.getAttribute("id") === attrId;
+			};
+		};
+	} else {
+		// Support: IE6/7
+		// getElementById is not reliable as a find shortcut
+		delete Expr.find["ID"];
+
+		Expr.filter["ID"] =  function( id ) {
+			var attrId = id.replace( runescape, funescape );
+			return function( elem ) {
+				var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
+				return node && node.value === attrId;
+			};
+		};
+	}
+
+	// Tag
+	Expr.find["TAG"] = support.getElementsByTagName ?
+		function( tag, context ) {
+			if ( typeof context.getElementsByTagName !== strundefined ) {
+				return context.getElementsByTagName( tag );
+			}
+		} :
+		function( tag, context ) {
+			var elem,
+				tmp = [],
+				i = 0,
+				results = context.getElementsByTagName( tag );
+
+			// Filter out possible comments
+			if ( tag === "*" ) {
+				while ( (elem = results[i++]) ) {
+					if ( elem.nodeType === 1 ) {
+						tmp.push( elem );
+					}
+				}
+
+				return tmp;
+			}
+			return results;
+		};
+
+	// Class
+	Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
+		if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
+			return context.getElementsByClassName( className );
+		}
+	};
+
+	/* QSA/matchesSelector
+	---------------------------------------------------------------------- */
+
+	// QSA and matchesSelector support
+
+	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
+	rbuggyMatches = [];
+
+	// qSa(:focus) reports false when true (Chrome 21)
+	// We allow this because of a bug in IE8/9 that throws an error
+	// whenever `document.activeElement` is accessed on an iframe
+	// So, we allow :focus to pass through QSA all the time to avoid the IE error
+	// See http://bugs.jquery.com/ticket/13378
+	rbuggyQSA = [];
+
+	if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
+		// Build QSA regex
+		// Regex strategy adopted from Diego Perini
+		assert(function( div ) {
+			// Select is set to empty string on purpose
+			// This is to test IE's treatment of not explicitly
+			// setting a boolean content attribute,
+			// since its presence should be enough
+			// http://bugs.jquery.com/ticket/12359
+			div.innerHTML = "<select><option selected=''></option></select>";
+
+			// Support: IE8
+			// Boolean attributes and "value" are not treated correctly
+			if ( !div.querySelectorAll("[selected]").length ) {
+				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
+			}
+
+			// Webkit/Opera - :checked should return selected option elements
+			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+			// IE8 throws error here and will not see later tests
+			if ( !div.querySelectorAll(":checked").length ) {
+				rbuggyQSA.push(":checked");
+			}
+		});
+
+		assert(function( div ) {
+
+			// Support: Opera 10-12/IE8
+			// ^= $= *= and empty values
+			// Should not select anything
+			// Support: Windows 8 Native Apps
+			// The type attribute is restricted during .innerHTML assignment
+			var input = doc.createElement("input");
+			input.setAttribute( "type", "hidden" );
+			div.appendChild( input ).setAttribute( "t", "" );
+
+			if ( div.querySelectorAll("[t^='']").length ) {
+				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
+			}
+
+			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
+			// IE8 throws error here and will not see later tests
+			if ( !div.querySelectorAll(":enabled").length ) {
+				rbuggyQSA.push( ":enabled", ":disabled" );
+			}
+
+			// Opera 10-11 does not throw on post-comma invalid pseudos
+			div.querySelectorAll("*,:x");
+			rbuggyQSA.push(",.*:");
+		});
+	}
+
+	if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector ||
+		docElem.mozMatchesSelector ||
+		docElem.oMatchesSelector ||
+		docElem.msMatchesSelector) )) ) {
+
+		assert(function( div ) {
+			// Check to see if it's possible to do matchesSelector
+			// on a disconnected node (IE 9)
+			support.disconnectedMatch = matches.call( div, "div" );
+
+			// This should fail with an exception
+			// Gecko does not error, returns false instead
+			matches.call( div, "[s!='']:x" );
+			rbuggyMatches.push( "!=", pseudos );
+		});
+	}
+
+	rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
+	rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
+
+	/* Contains
+	---------------------------------------------------------------------- */
+
+	// Element contains another
+	// Purposefully does not implement inclusive descendent
+	// As in, an element does not contain itself
+	contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ?
+		function( a, b ) {
+			var adown = a.nodeType === 9 ? a.documentElement : a,
+				bup = b && b.parentNode;
+			return a === bup || !!( bup && bup.nodeType === 1 && (
+				adown.contains ?
+					adown.contains( bup ) :
+					a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
+			));
+		} :
+		function( a, b ) {
+			if ( b ) {
+				while ( (b = b.parentNode) ) {
+					if ( b === a ) {
+						return true;
+					}
+				}
+			}
+			return false;
+		};
+
+	/* Sorting
+	---------------------------------------------------------------------- */
+
+	// Document order sorting
+	sortOrder = docElem.compareDocumentPosition ?
+	function( a, b ) {
+
+		// Flag for duplicate removal
+		if ( a === b ) {
+			hasDuplicate = true;
+			return 0;
+		}
+
+		var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
+
+		if ( compare ) {
+			// Disconnected nodes
+			if ( compare & 1 ||
+				(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
+
+				// Choose the first element that is related to our preferred document
+				if ( a === doc || contains(preferredDoc, a) ) {
+					return -1;
+				}
+				if ( b === doc || contains(preferredDoc, b) ) {
+					return 1;
+				}
+
+				// Maintain original order
+				return sortInput ?
+					( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
+					0;
+			}
+
+			return compare & 4 ? -1 : 1;
+		}
+
+		// Not directly comparable, sort on existence of method
+		return a.compareDocumentPosition ? -1 : 1;
+	} :
+	function( a, b ) {
+		var cur,
+			i = 0,
+			aup = a.parentNode,
+			bup = b.parentNode,
+			ap = [ a ],
+			bp = [ b ];
+
+		// Exit early if the nodes are identical
+		if ( a === b ) {
+			hasDuplicate = true;
+			return 0;
+
+		// Parentless nodes are either documents or disconnected
+		} else if ( !aup || !bup ) {
+			return a === doc ? -1 :
+				b === doc ? 1 :
+				aup ? -1 :
+				bup ? 1 :
+				sortInput ?
+				( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
+				0;
+
+		// If the nodes are siblings, we can do a quick check
+		} else if ( aup === bup ) {
+			return siblingCheck( a, b );
+		}
+
+		// Otherwise we need full lists of their ancestors for comparison
+		cur = a;
+		while ( (cur = cur.parentNode) ) {
+			ap.unshift( cur );
+		}
+		cur = b;
+		while ( (cur = cur.parentNode) ) {
+			bp.unshift( cur );
+		}
+
+		// Walk down the tree looking for a discrepancy
+		while ( ap[i] === bp[i] ) {
+			i++;
+		}
+
+		return i ?
+			// Do a sibling check if the nodes have a common ancestor
+			siblingCheck( ap[i], bp[i] ) :
+
+			// Otherwise nodes in our document sort first
+			ap[i] === preferredDoc ? -1 :
+			bp[i] === preferredDoc ? 1 :
+			0;
+	};
+
+	return doc;
+};
+
+Sizzle.matches = function( expr, elements ) {
+	return Sizzle( expr, null, null, elements );
+};
+
+Sizzle.matchesSelector = function( elem, expr ) {
+	// Set document vars if needed
+	if ( ( elem.ownerDocument || elem ) !== document ) {
+		setDocument( elem );
+	}
+
+	// Make sure that attribute selectors are quoted
+	expr = expr.replace( rattributeQuotes, "='$1']" );
+
+	if ( support.matchesSelector && documentIsHTML &&
+		( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
+		( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {
+
+		try {
+			var ret = matches.call( elem, expr );
+
+			// IE 9's matchesSelector returns false on disconnected nodes
+			if ( ret || support.disconnectedMatch ||
+					// As well, disconnected nodes are said to be in a document
+					// fragment in IE 9
+					elem.document && elem.document.nodeType !== 11 ) {
+				return ret;
+			}
+		} catch(e) {}
+	}
+
+	return Sizzle( expr, document, null, [elem] ).length > 0;
+};
+
+Sizzle.contains = function( context, elem ) {
+	// Set document vars if needed
+	if ( ( context.ownerDocument || context ) !== document ) {
+		setDocument( context );
+	}
+	return contains( context, elem );
+};
+
+Sizzle.attr = function( elem, name ) {
+	// Set document vars if needed
+	if ( ( elem.ownerDocument || elem ) !== document ) {
+		setDocument( elem );
+	}
+
+	var fn = Expr.attrHandle[ name.toLowerCase() ],
+		// Don't get fooled by Object.prototype properties (jQuery #13807)
+		val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
+			fn( elem, name, !documentIsHTML ) :
+			undefined;
+
+	return val === undefined ?
+		support.attributes || !documentIsHTML ?
+			elem.getAttribute( name ) :
+			(val = elem.getAttributeNode(name)) && val.specified ?
+				val.value :
+				null :
+		val;
+};
+
+Sizzle.error = function( msg ) {
+	throw new Error( "Syntax error, unrecognized expression: " + msg );
+};
+
+/**
+ * Document sorting and removing duplicates
+ * @param {ArrayLike} results
+ */
+Sizzle.uniqueSort = function( results ) {
+	var elem,
+		duplicates = [],
+		j = 0,
+		i = 0;
+
+	// Unless we *know* we can detect duplicates, assume their presence
+	hasDuplicate = !support.detectDuplicates;
+	sortInput = !support.sortStable && results.slice( 0 );
+	results.sort( sortOrder );
+
+	if ( hasDuplicate ) {
+		while ( (elem = results[i++]) ) {
+			if ( elem === results[ i ] ) {
+				j = duplicates.push( i );
+			}
+		}
+		while ( j-- ) {
+			results.splice( duplicates[ j ], 1 );
+		}
+	}
+
+	return results;
+};
+
+/**
+ * Utility function for retrieving the text value of an array of DOM nodes
+ * @param {Array|Element} elem
+ */
+getText = Sizzle.getText = function( elem ) {
+	var node,
+		ret = "",
+		i = 0,
+		nodeType = elem.nodeType;
+
+	if ( !nodeType ) {
+		// If no nodeType, this is expected to be an array
+		for ( ; (node = elem[i]); i++ ) {
+			// Do not traverse comment nodes
+			ret += getText( node );
+		}
+	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
+		// Use textContent for elements
+		// innerText usage removed for consistency of new lines (see #11153)
+		if ( typeof elem.textContent === "string" ) {
+			return elem.textContent;
+		} else {
+			// Traverse its children
+			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+				ret += getText( elem );
+			}
+		}
+	} else if ( nodeType === 3 || nodeType === 4 ) {
+		return elem.nodeValue;
+	}
+	// Do not include comment or processing instruction nodes
+
+	return ret;
+};
+
+Expr = Sizzle.selectors = {
+
+	// Can be adjusted by the user
+	cacheLength: 50,
+
+	createPseudo: markFunction,
+
+	match: matchExpr,
+
+	attrHandle: {},
+
+	find: {},
+
+	relative: {
+		">": { dir: "parentNode", first: true },
+		" ": { dir: "parentNode" },
+		"+": { dir: "previousSibling", first: true },
+		"~": { dir: "previousSibling" }
+	},
+
+	preFilter: {
+		"ATTR": function( match ) {
+			match[1] = match[1].replace( runescape, funescape );
+
+			// Move the given value to match[3] whether quoted or unquoted
+			match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
+
+			if ( match[2] === "~=" ) {
+				match[3] = " " + match[3] + " ";
+			}
+
+			return match.slice( 0, 4 );
+		},
+
+		"CHILD": function( match ) {
+			/* matches from matchExpr["CHILD"]
+				1 type (only|nth|...)
+				2 what (child|of-type)
+				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
+				4 xn-component of xn+y argument ([+-]?\d*n|)
+				5 sign of xn-component
+				6 x of xn-component
+				7 sign of y-component
+				8 y of y-component
+			*/
+			match[1] = match[1].toLowerCase();
+
+			if ( match[1].slice( 0, 3 ) === "nth" ) {
+				// nth-* requires argument
+				if ( !match[3] ) {
+					Sizzle.error( match[0] );
+				}
+
+				// numeric x and y parameters for Expr.filter.CHILD
+				// remember that false/true cast respectively to 0/1
+				match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
+				match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
+
+			// other types prohibit arguments
+			} else if ( match[3] ) {
+				Sizzle.error( match[0] );
+			}
+
+			return match;
+		},
+
+		"PSEUDO": function( match ) {
+			var excess,
+				unquoted = !match[5] && match[2];
+
+			if ( matchExpr["CHILD"].test( match[0] ) ) {
+				return null;
+			}
+
+			// Accept quoted arguments as-is
+			if ( match[3] && match[4] !== undefined ) {
+				match[2] = match[4];
+
+			// Strip excess characters from unquoted arguments
+			} else if ( unquoted && rpseudo.test( unquoted ) &&
+				// Get excess from tokenize (recursively)
+				(excess = tokenize( unquoted, true )) &&
+				// advance to the next closing parenthesis
+				(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
+
+				// excess is a negative index
+				match[0] = match[0].slice( 0, excess );
+				match[2] = unquoted.slice( 0, excess );
+			}
+
+			// Return only captures needed by the pseudo filter method (type and argument)
+			return match.slice( 0, 3 );
+		}
+	},
+
+	filter: {
+
+		"TAG": function( nodeNameSelector ) {
+			var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
+			return nodeNameSelector === "*" ?
+				function() { return true; } :
+				function( elem ) {
+					return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
+				};
+		},
+
+		"CLASS": function( className ) {
+			var pattern = classCache[ className + " " ];
+
+			return pattern ||
+				(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
+				classCache( className, function( elem ) {
+					return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
+				});
+		},
+
+		"ATTR": function( name, operator, check ) {
+			return function( elem ) {
+				var result = Sizzle.attr( elem, name );
+
+				if ( result == null ) {
+					return operator === "!=";
+				}
+				if ( !operator ) {
+					return true;
+				}
+
+				result += "";
+
+				return operator === "=" ? result === check :
+					operator === "!=" ? result !== check :
+					operator === "^=" ? check && result.indexOf( check ) === 0 :
+					operator === "*=" ? check && result.indexOf( check ) > -1 :
+					operator === "$=" ? check && result.slice( -check.length ) === check :
+					operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
+					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
+					false;
+			};
+		},
+
+		"CHILD": function( type, what, argument, first, last ) {
+			var simple = type.slice( 0, 3 ) !== "nth",
+				forward = type.slice( -4 ) !== "last",
+				ofType = what === "of-type";
+
+			return first === 1 && last === 0 ?
+
+				// Shortcut for :nth-*(n)
+				function( elem ) {
+					return !!elem.parentNode;
+				} :
+
+				function( elem, context, xml ) {
+					var cache, outerCache, node, diff, nodeIndex, start,
+						dir = simple !== forward ? "nextSibling" : "previousSibling",
+						parent = elem.parentNode,
+						name = ofType && elem.nodeName.toLowerCase(),
+						useCache = !xml && !ofType;
+
+					if ( parent ) {
+
+						// :(first|last|only)-(child|of-type)
+						if ( simple ) {
+							while ( dir ) {
+								node = elem;
+								while ( (node = node[ dir ]) ) {
+									if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
+										return false;
+									}
+								}
+								// Reverse direction for :only-* (if we haven't yet done so)
+								start = dir = type === "only" && !start && "nextSibling";
+							}
+							return true;
+						}
+
+						start = [ forward ? parent.firstChild : parent.lastChild ];
+
+						// non-xml :nth-child(...) stores cache data on `parent`
+						if ( forward && useCache ) {
+							// Seek `elem` from a previously-cached index
+							outerCache = parent[ expando ] || (parent[ expando ] = {});
+							cache = outerCache[ type ] || [];
+							nodeIndex = cache[0] === dirruns && cache[1];
+							diff = cache[0] === dirruns && cache[2];
+							node = nodeIndex && parent.childNodes[ nodeIndex ];
+
+							while ( (node = ++nodeIndex && node && node[ dir ] ||
+
+								// Fallback to seeking `elem` from the start
+								(diff = nodeIndex = 0) || start.pop()) ) {
+
+								// When found, cache indexes on `parent` and break
+								if ( node.nodeType === 1 && ++diff && node === elem ) {
+									outerCache[ type ] = [ dirruns, nodeIndex, diff ];
+									break;
+								}
+							}
+
+						// Use previously-cached element index if available
+						} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
+							diff = cache[1];
+
+						// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
+						} else {
+							// Use the same loop as above to seek `elem` from the start
+							while ( (node = ++nodeIndex && node && node[ dir ] ||
+								(diff = nodeIndex = 0) || start.pop()) ) {
+
+								if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
+									// Cache the index of each encountered element
+									if ( useCache ) {
+										(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
+									}
+
+									if ( node === elem ) {
+										break;
+									}
+								}
+							}
+						}
+
+						// Incorporate the offset, then check against cycle size
+						diff -= last;
+						return diff === first || ( diff % first === 0 && diff / first >= 0 );
+					}
+				};
+		},
+
+		"PSEUDO": function( pseudo, argument ) {
+			// pseudo-class names are case-insensitive
+			// http://www.w3.org/TR/selectors/#pseudo-classes
+			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
+			// Remember that setFilters inherits from pseudos
+			var args,
+				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
+					Sizzle.error( "unsupported pseudo: " + pseudo );
+
+			// The user may use createPseudo to indicate that
+			// arguments are needed to create the filter function
+			// just as Sizzle does
+			if ( fn[ expando ] ) {
+				return fn( argument );
+			}
+
+			// But maintain support for old signatures
+			if ( fn.length > 1 ) {
+				args = [ pseudo, pseudo, "", argument ];
+				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
+					markFunction(function( seed, matches ) {
+						var idx,
+							matched = fn( seed, argument ),
+							i = matched.length;
+						while ( i-- ) {
+							idx = indexOf.call( seed, matched[i] );
+							seed[ idx ] = !( matches[ idx ] = matched[i] );
+						}
+					}) :
+					function( elem ) {
+						return fn( elem, 0, args );
+					};
+			}
+
+			return fn;
+		}
+	},
+
+	pseudos: {
+		// Potentially complex pseudos
+		"not": markFunction(function( selector ) {
+			// Trim the selector passed to compile
+			// to avoid treating leading and trailing
+			// spaces as combinators
+			var input = [],
+				results = [],
+				matcher = compile( selector.replace( rtrim, "$1" ) );
+
+			return matcher[ expando ] ?
+				markFunction(function( seed, matches, context, xml ) {
+					var elem,
+						unmatched = matcher( seed, null, xml, [] ),
+						i = seed.length;
+
+					// Match elements unmatched by `matcher`
+					while ( i-- ) {
+						if ( (elem = unmatched[i]) ) {
+							seed[i] = !(matches[i] = elem);
+						}
+					}
+				}) :
+				function( elem, context, xml ) {
+					input[0] = elem;
+					matcher( input, null, xml, results );
+					return !results.pop();
+				};
+		}),
+
+		"has": markFunction(function( selector ) {
+			return function( elem ) {
+				return Sizzle( selector, elem ).length > 0;
+			};
+		}),
+
+		"contains": markFunction(function( text ) {
+			return function( elem ) {
+				return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
+			};
+		}),
+
+		// "Whether an element is represented by a :lang() selector
+		// is based solely on the element's language value
+		// being equal to the identifier C,
+		// or beginning with the identifier C immediately followed by "-".
+		// The matching of C against the element's language value is performed case-insensitively.
+		// The identifier C does not have to be a valid language name."
+		// http://www.w3.org/TR/selectors/#lang-pseudo
+		"lang": markFunction( function( lang ) {
+			// lang value must be a valid identifier
+			if ( !ridentifier.test(lang || "") ) {
+				Sizzle.error( "unsupported lang: " + lang );
+			}
+			lang = lang.replace( runescape, funescape ).toLowerCase();
+			return function( elem ) {
+				var elemLang;
+				do {
+					if ( (elemLang = documentIsHTML ?
+						elem.lang :
+						elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
+
+						elemLang = elemLang.toLowerCase();
+						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
+					}
+				} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
+				return false;
+			};
+		}),
+
+		// Miscellaneous
+		"target": function( elem ) {
+			var hash = window.location && window.location.hash;
+			return hash && hash.slice( 1 ) === elem.id;
+		},
+
+		"root": function( elem ) {
+			return elem === docElem;
+		},
+
+		"focus": function( elem ) {
+			return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
+		},
+
+		// Boolean properties
+		"enabled": function( elem ) {
+			return elem.disabled === false;
+		},
+
+		"disabled": function( elem ) {
+			return elem.disabled === true;
+		},
+
+		"checked": function( elem ) {
+			// In CSS3, :checked should return both checked and selected elements
+			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+			var nodeName = elem.nodeName.toLowerCase();
+			return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
+		},
+
+		"selected": function( elem ) {
+			// Accessing this property makes selected-by-default
+			// options in Safari work properly
+			if ( elem.parentNode ) {
+				elem.parentNode.selectedIndex;
+			}
+
+			return elem.selected === true;
+		},
+
+		// Contents
+		"empty": function( elem ) {
+			// http://www.w3.org/TR/selectors/#empty-pseudo
+			// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
+			//   not comment, processing instructions, or others
+			// Thanks to Diego Perini for the nodeName shortcut
+			//   Greater than "@" means alpha characters (specifically not starting with "#" or "?")
+			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+				if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
+					return false;
+				}
+			}
+			return true;
+		},
+
+		"parent": function( elem ) {
+			return !Expr.pseudos["empty"]( elem );
+		},
+
+		// Element/input types
+		"header": function( elem ) {
+			return rheader.test( elem.nodeName );
+		},
+
+		"input": function( elem ) {
+			return rinputs.test( elem.nodeName );
+		},
+
+		"button": function( elem ) {
+			var name = elem.nodeName.toLowerCase();
+			return name === "input" && elem.type === "button" || name === "button";
+		},
+
+		"text": function( elem ) {
+			var attr;
+			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
+			// use getAttribute instead to test this case
+			return elem.nodeName.toLowerCase() === "input" &&
+				elem.type === "text" &&
+				( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
+		},
+
+		// Position-in-collection
+		"first": createPositionalPseudo(function() {
+			return [ 0 ];
+		}),
+
+		"last": createPositionalPseudo(function( matchIndexes, length ) {
+			return [ length - 1 ];
+		}),
+
+		"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
+			return [ argument < 0 ? argument + length : argument ];
+		}),
+
+		"even": createPositionalPseudo(function( matchIndexes, length ) {
+			var i = 0;
+			for ( ; i < length; i += 2 ) {
+				matchIndexes.push( i );
+			}
+			return matchIndexes;
+		}),
+
+		"odd": createPositionalPseudo(function( matchIndexes, length ) {
+			var i = 1;
+			for ( ; i < length; i += 2 ) {
+				matchIndexes.push( i );
+			}
+			return matchIndexes;
+		}),
+
+		"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
+			var i = argument < 0 ? argument + length : argument;
+			for ( ; --i >= 0; ) {
+				matchIndexes.push( i );
+			}
+			return matchIndexes;
+		}),
+
+		"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
+			var i = argument < 0 ? argument + length : argument;
+			for ( ; ++i < length; ) {
+				matchIndexes.push( i );
+			}
+			return matchIndexes;
+		})
+	}
+};
+
+Expr.pseudos["nth"] = Expr.pseudos["eq"];
+
+// Add button/input type pseudos
+for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
+	Expr.pseudos[ i ] = createInputPseudo( i );
+}
+for ( i in { submit: true, reset: true } ) {
+	Expr.pseudos[ i ] = createButtonPseudo( i );
+}
+
+// Easy API for creating new setFilters
+function setFilters() {}
+setFilters.prototype = Expr.filters = Expr.pseudos;
+Expr.setFilters = new setFilters();
+
+function tokenize( selector, parseOnly ) {
+	var matched, match, tokens, type,
+		soFar, groups, preFilters,
+		cached = tokenCache[ selector + " " ];
+
+	if ( cached ) {
+		return parseOnly ? 0 : cached.slice( 0 );
+	}
+
+	soFar = selector;
+	groups = [];
+	preFilters = Expr.preFilter;
+
+	while ( soFar ) {
+
+		// Comma and first run
+		if ( !matched || (match = rcomma.exec( soFar )) ) {
+			if ( match ) {
+				// Don't consume trailing commas as valid
+				soFar = soFar.slice( match[0].length ) || soFar;
+			}
+			groups.push( tokens = [] );
+		}
+
+		matched = false;
+
+		// Combinators
+		if ( (match = rcombinators.exec( soFar )) ) {
+			matched = match.shift();
+			tokens.push({
+				value: matched,
+				// Cast descendant combinators to space
+				type: match[0].replace( rtrim, " " )
+			});
+			soFar = soFar.slice( matched.length );
+		}
+
+		// Filters
+		for ( type in Expr.filter ) {
+			if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
+				(match = preFilters[ type ]( match ))) ) {
+				matched = match.shift();
+				tokens.push({
+					value: matched,
+					type: type,
+					matches: match
+				});
+				soFar = soFar.slice( matched.length );
+			}
+		}
+
+		if ( !matched ) {
+			break;
+		}
+	}
+
+	// Return the length of the invalid excess
+	// if we're just parsing
+	// Otherwise, throw an error or return tokens
+	return parseOnly ?
+		soFar.length :
+		soFar ?
+			Sizzle.error( selector ) :
+			// Cache the tokens
+			tokenCache( selector, groups ).slice( 0 );
+}
+
+function toSelector( tokens ) {
+	var i = 0,
+		len = tokens.length,
+		selector = "";
+	for ( ; i < len; i++ ) {
+		selector += tokens[i].value;
+	}
+	return selector;
+}
+
+function addCombinator( matcher, combinator, base ) {
+	var dir = combinator.dir,
+		checkNonElements = base && dir === "parentNode",
+		doneName = done++;
+
+	return combinator.first ?
+		// Check against closest ancestor/preceding element
+		function( elem, context, xml ) {
+			while ( (elem = elem[ dir ]) ) {
+				if ( elem.nodeType === 1 || checkNonElements ) {
+					return matcher( elem, context, xml );
+				}
+			}
+		} :
+
+		// Check against all ancestor/preceding elements
+		function( elem, context, xml ) {
+			var data, cache, outerCache,
+				dirkey = dirruns + " " + doneName;
+
+			// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
+			if ( xml ) {
+				while ( (elem = elem[ dir ]) ) {
+					if ( elem.nodeType === 1 || checkNonElements ) {
+						if ( matcher( elem, context, xml ) ) {
+							return true;
+						}
+					}
+				}
+			} else {
+				while ( (elem = elem[ dir ]) ) {
+					if ( elem.nodeType === 1 || checkNonElements ) {
+						outerCache = elem[ expando ] || (elem[ expando ] = {});
+						if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
+							if ( (data = cache[1]) === true || data === cachedruns ) {
+								return data === true;
+							}
+						} else {
+							cache = outerCache[ dir ] = [ dirkey ];
+							cache[1] = matcher( elem, context, xml ) || cachedruns;
+							if ( cache[1] === true ) {
+								return true;
+							}
+						}
+					}
+				}
+			}
+		};
+}
+
+function elementMatcher( matchers ) {
+	return matchers.length > 1 ?
+		function( elem, context, xml ) {
+			var i = matchers.length;
+			while ( i-- ) {
+				if ( !matchers[i]( elem, context, xml ) ) {
+					return false;
+				}
+			}
+			return true;
+		} :
+		matchers[0];
+}
+
+function condense( unmatched, map, filter, context, xml ) {
+	var elem,
+		newUnmatched = [],
+		i = 0,
+		len = unmatched.length,
+		mapped = map != null;
+
+	for ( ; i < len; i++ ) {
+		if ( (elem = unmatched[i]) ) {
+			if ( !filter || filter( elem, context, xml ) ) {
+				newUnmatched.push( elem );
+				if ( mapped ) {
+					map.push( i );
+				}
+			}
+		}
+	}
+
+	return newUnmatched;
+}
+
+function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
+	if ( postFilter && !postFilter[ expando ] ) {
+		postFilter = setMatcher( postFilter );
+	}
+	if ( postFinder && !postFinder[ expando ] ) {
+		postFinder = setMatcher( postFinder, postSelector );
+	}
+	return markFunction(function( seed, results, context, xml ) {
+		var temp, i, elem,
+			preMap = [],
+			postMap = [],
+			preexisting = results.length,
+
+			// Get initial elements from seed or context
+			elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
+
+			// Prefilter to get matcher input, preserving a map for seed-results synchronization
+			matcherIn = preFilter && ( seed || !selector ) ?
+				condense( elems, preMap, preFilter, context, xml ) :
+				elems,
+
+			matcherOut = matcher ?
+				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
+				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
+
+					// ...intermediate processing is necessary
+					[] :
+
+					// ...otherwise use results directly
+					results :
+				matcherIn;
+
+		// Find primary matches
+		if ( matcher ) {
+			matcher( matcherIn, matcherOut, context, xml );
+		}
+
+		// Apply postFilter
+		if ( postFilter ) {
+			temp = condense( matcherOut, postMap );
+			postFilter( temp, [], context, xml );
+
+			// Un-match failing elements by moving them back to matcherIn
+			i = temp.length;
+			while ( i-- ) {
+				if ( (elem = temp[i]) ) {
+					matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
+				}
+			}
+		}
+
+		if ( seed ) {
+			if ( postFinder || preFilter ) {
+				if ( postFinder ) {
+					// Get the final matcherOut by condensing this intermediate into postFinder contexts
+					temp = [];
+					i = matcherOut.length;
+					while ( i-- ) {
+						if ( (elem = matcherOut[i]) ) {
+							// Restore matcherIn since elem is not yet a final match
+							temp.push( (matcherIn[i] = elem) );
+						}
+					}
+					postFinder( null, (matcherOut = []), temp, xml );
+				}
+
+				// Move matched elements from seed to results to keep them synchronized
+				i = matcherOut.length;
+				while ( i-- ) {
+					if ( (elem = matcherOut[i]) &&
+						(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
+
+						seed[temp] = !(results[temp] = elem);
+					}
+				}
+			}
+
+		// Add elements to results, through postFinder if defined
+		} else {
+			matcherOut = condense(
+				matcherOut === results ?
+					matcherOut.splice( preexisting, matcherOut.length ) :
+					matcherOut
+			);
+			if ( postFinder ) {
+				postFinder( null, results, matcherOut, xml );
+			} else {
+				push.apply( results, matcherOut );
+			}
+		}
+	});
+}
+
+function matcherFromTokens( tokens ) {
+	var checkContext, matcher, j,
+		len = tokens.length,
+		leadingRelative = Expr.relative[ tokens[0].type ],
+		implicitRelative = leadingRelative || Expr.relative[" "],
+		i = leadingRelative ? 1 : 0,
+
+		// The foundational matcher ensures that elements are reachable from top-level context(s)
+		matchContext = addCombinator( function( elem ) {
+			return elem === checkContext;
+		}, implicitRelative, true ),
+		matchAnyContext = addCombinator( function( elem ) {
+			return indexOf.call( checkContext, elem ) > -1;
+		}, implicitRelative, true ),
+		matchers = [ function( elem, context, xml ) {
+			return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
+				(checkContext = context).nodeType ?
+					matchContext( elem, context, xml ) :
+					matchAnyContext( elem, context, xml ) );
+		} ];
+
+	for ( ; i < len; i++ ) {
+		if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
+			matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
+		} else {
+			matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
+
+			// Return special upon seeing a positional matcher
+			if ( matcher[ expando ] ) {
+				// Find the next relative operator (if any) for proper handling
+				j = ++i;
+				for ( ; j < len; j++ ) {
+					if ( Expr.relative[ tokens[j].type ] ) {
+						break;
+					}
+				}
+				return setMatcher(
+					i > 1 && elementMatcher( matchers ),
+					i > 1 && toSelector(
+						// If the preceding token was a descendant combinator, insert an implicit any-element `*`
+						tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
+					).replace( rtrim, "$1" ),
+					matcher,
+					i < j && matcherFromTokens( tokens.slice( i, j ) ),
+					j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
+					j < len && toSelector( tokens )
+				);
+			}
+			matchers.push( matcher );
+		}
+	}
+
+	return elementMatcher( matchers );
+}
+
+function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
+	// A counter to specify which element is currently being matched
+	var matcherCachedRuns = 0,
+		bySet = setMatchers.length > 0,
+		byElement = elementMatchers.length > 0,
+		superMatcher = function( seed, context, xml, results, expandContext ) {
+			var elem, j, matcher,
+				setMatched = [],
+				matchedCount = 0,
+				i = "0",
+				unmatched = seed && [],
+				outermost = expandContext != null,
+				contextBackup = outermostContext,
+				// We must always have either seed elements or context
+				elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
+				// Use integer dirruns iff this is the outermost matcher
+				dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
+
+			if ( outermost ) {
+				outermostContext = context !== document && context;
+				cachedruns = matcherCachedRuns;
+			}
+
+			// Add elements passing elementMatchers directly to results
+			// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
+			for ( ; (elem = elems[i]) != null; i++ ) {
+				if ( byElement && elem ) {
+					j = 0;
+					while ( (matcher = elementMatchers[j++]) ) {
+						if ( matcher( elem, context, xml ) ) {
+							results.push( elem );
+							break;
+						}
+					}
+					if ( outermost ) {
+						dirruns = dirrunsUnique;
+						cachedruns = ++matcherCachedRuns;
+					}
+				}
+
+				// Track unmatched elements for set filters
+				if ( bySet ) {
+					// They will have gone through all possible matchers
+					if ( (elem = !matcher && elem) ) {
+						matchedCount--;
+					}
+
+					// Lengthen the array for every element, matched or not
+					if ( seed ) {
+						unmatched.push( elem );
+					}
+				}
+			}
+
+			// Apply set filters to unmatched elements
+			matchedCount += i;
+			if ( bySet && i !== matchedCount ) {
+				j = 0;
+				while ( (matcher = setMatchers[j++]) ) {
+					matcher( unmatched, setMatched, context, xml );
+				}
+
+				if ( seed ) {
+					// Reintegrate element matches to eliminate the need for sorting
+					if ( matchedCount > 0 ) {
+						while ( i-- ) {
+							if ( !(unmatched[i] || setMatched[i]) ) {
+								setMatched[i] = pop.call( results );
+							}
+						}
+					}
+
+					// Discard index placeholder values to get only actual matches
+					setMatched = condense( setMatched );
+				}
+
+				// Add matches to results
+				push.apply( results, setMatched );
+
+				// Seedless set matches succeeding multiple successful matchers stipulate sorting
+				if ( outermost && !seed && setMatched.length > 0 &&
+					( matchedCount + setMatchers.length ) > 1 ) {
+
+					Sizzle.uniqueSort( results );
+				}
+			}
+
+			// Override manipulation of globals by nested matchers
+			if ( outermost ) {
+				dirruns = dirrunsUnique;
+				outermostContext = contextBackup;
+			}
+
+			return unmatched;
+		};
+
+	return bySet ?
+		markFunction( superMatcher ) :
+		superMatcher;
+}
+
+compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
+	var i,
+		setMatchers = [],
+		elementMatchers = [],
+		cached = compilerCache[ selector + " " ];
+
+	if ( !cached ) {
+		// Generate a function of recursive functions that can be used to check each element
+		if ( !group ) {
+			group = tokenize( selector );
+		}
+		i = group.length;
+		while ( i-- ) {
+			cached = matcherFromTokens( group[i] );
+			if ( cached[ expando ] ) {
+				setMatchers.push( cached );
+			} else {
+				elementMatchers.push( cached );
+			}
+		}
+
+		// Cache the compiled function
+		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
+	}
+	return cached;
+};
+
+function multipleContexts( selector, contexts, results ) {
+	var i = 0,
+		len = contexts.length;
+	for ( ; i < len; i++ ) {
+		Sizzle( selector, contexts[i], results );
+	}
+	return results;
+}
+
+function select( selector, context, results, seed ) {
+	var i, tokens, token, type, find,
+		match = tokenize( selector );
+
+	if ( !seed ) {
+		// Try to minimize operations if there is only one group
+		if ( match.length === 1 ) {
+
+			// Take a shortcut and set the context if the root selector is an ID
+			tokens = match[0] = match[0].slice( 0 );
+			if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
+					support.getById && context.nodeType === 9 && documentIsHTML &&
+					Expr.relative[ tokens[1].type ] ) {
+
+				context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
+				if ( !context ) {
+					return results;
+				}
+				selector = selector.slice( tokens.shift().value.length );
+			}
+
+			// Fetch a seed set for right-to-left matching
+			i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
+			while ( i-- ) {
+				token = tokens[i];
+
+				// Abort if we hit a combinator
+				if ( Expr.relative[ (type = token.type) ] ) {
+					break;
+				}
+				if ( (find = Expr.find[ type ]) ) {
+					// Search, expanding context for leading sibling combinators
+					if ( (seed = find(
+						token.matches[0].replace( runescape, funescape ),
+						rsibling.test( tokens[0].type ) && context.parentNode || context
+					)) ) {
+
+						// If seed is empty or no tokens remain, we can return early
+						tokens.splice( i, 1 );
+						selector = seed.length && toSelector( tokens );
+						if ( !selector ) {
+							push.apply( results, seed );
+							return results;
+						}
+
+						break;
+					}
+				}
+			}
+		}
+	}
+
+	// Compile and execute a filtering function
+	// Provide `match` to avoid retokenization if we modified the selector above
+	compile( selector, match )(
+		seed,
+		context,
+		!documentIsHTML,
+		results,
+		rsibling.test( selector )
+	);
+	return results;
+}
+
+// One-time assignments
+
+// Sort stability
+support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
+
+// Support: Chrome<14
+// Always assume duplicates if they aren't passed to the comparison function
+support.detectDuplicates = hasDuplicate;
+
+// Initialize against the default document
+setDocument();
+
+// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
+// Detached nodes confoundingly follow *each other*
+support.sortDetached = assert(function( div1 ) {
+	// Should return 1, but returns 4 (following)
+	return div1.compareDocumentPosition( document.createElement("div") ) & 1;
+});
+
+// Support: IE<8
+// Prevent attribute/property "interpolation"
+// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
+if ( !assert(function( div ) {
+	div.innerHTML = "<a href='#'></a>";
+	return div.firstChild.getAttribute("href") === "#" ;
+}) ) {
+	addHandle( "type|href|height|width", function( elem, name, isXML ) {
+		if ( !isXML ) {
+			return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
+		}
+	});
+}
+
+// Support: IE<9
+// Use defaultValue in place of getAttribute("value")
+if ( !support.attributes || !assert(function( div ) {
+	div.innerHTML = "<input/>";
+	div.firstChild.setAttribute( "value", "" );
+	return div.firstChild.getAttribute( "value" ) === "";
+}) ) {
+	addHandle( "value", function( elem, name, isXML ) {
+		if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
+			return elem.defaultValue;
+		}
+	});
+}
+
+// Support: IE<9
+// Use getAttributeNode to fetch booleans when getAttribute lies
+if ( !assert(function( div ) {
+	return div.getAttribute("disabled") == null;
+}) ) {
+	addHandle( booleans, function( elem, name, isXML ) {
+		var val;
+		if ( !isXML ) {
+			return (val = elem.getAttributeNode( name )) && val.specified ?
+				val.value :
+				elem[ name ] === true ? name.toLowerCase() : null;
+		}
+	});
+}
+
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.pseudos;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+})( window );
+// String to Object options format cache
+var optionsCache = {};
+
+// Convert String-formatted options into Object-formatted ones and store in cache
+function createOptions( options ) {
+	var object = optionsCache[ options ] = {};
+	jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
+		object[ flag ] = true;
+	});
+	return object;
+}
+
+/*
+ * Create a callback list using the following parameters:
+ *
+ *	options: an optional list of space-separated options that will change how
+ *			the callback list behaves or a more traditional option object
+ *
+ * By default a callback list will act like an event callback list and can be
+ * "fired" multiple times.
+ *
+ * Possible options:
+ *
+ *	once:			will ensure the callback list can only be fired once (like a Deferred)
+ *
+ *	memory:			will keep track of previous values and will call any callback added
+ *					after the list has been fired right away with the latest "memorized"
+ *					values (like a Deferred)
+ *
+ *	unique:			will ensure a callback can only be added once (no duplicate in the list)
+ *
+ *	stopOnFalse:	interrupt callings when a callback returns false
+ *
+ */
+jQuery.Callbacks = function( options ) {
+
+	// Convert options from String-formatted to Object-formatted if needed
+	// (we check in cache first)
+	options = typeof options === "string" ?
+		( optionsCache[ options ] || createOptions( options ) ) :
+		jQuery.extend( {}, options );
+
+	var // Flag to know if list is currently firing
+		firing,
+		// Last fire value (for non-forgettable lists)
+		memory,
+		// Flag to know if list was already fired
+		fired,
+		// End of the loop when firing
+		firingLength,
+		// Index of currently firing callback (modified by remove if needed)
+		firingIndex,
+		// First callback to fire (used internally by add and fireWith)
+		firingStart,
+		// Actual callback list
+		list = [],
+		// Stack of fire calls for repeatable lists
+		stack = !options.once && [],
+		// Fire callbacks
+		fire = function( data ) {
+			memory = options.memory && data;
+			fired = true;
+			firingIndex = firingStart || 0;
+			firingStart = 0;
+			firingLength = list.length;
+			firing = true;
+			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
+				if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
+					memory = false; // To prevent further calls using add
+					break;
+				}
+			}
+			firing = false;
+			if ( list ) {
+				if ( stack ) {
+					if ( stack.length ) {
+						fire( stack.shift() );
+					}
+				} else if ( memory ) {
+					list = [];
+				} else {
+					self.disable();
+				}
+			}
+		},
+		// Actual Callbacks object
+		self = {
+			// Add a callback or a collection of callbacks to the list
+			add: function() {
+				if ( list ) {
+					// First, we save the current length
+					var start = list.length;
+					(function add( args ) {
+						jQuery.each( args, function( _, arg ) {
+							var type = jQuery.type( arg );
+							if ( type === "function" ) {
+								if ( !options.unique || !self.has( arg ) ) {
+									list.push( arg );
+								}
+							} else if ( arg && arg.length && type !== "string" ) {
+								// Inspect recursively
+								add( arg );
+							}
+						});
+					})( arguments );
+					// Do we need to add the callbacks to the
+					// current firing batch?
+					if ( firing ) {
+						firingLength = list.length;
+					// With memory, if we're not firing then
+					// we should call right away
+					} else if ( memory ) {
+						firingStart = start;
+						fire( memory );
+					}
+				}
+				return this;
+			},
+			// Remove a callback from the list
+			remove: function() {
+				if ( list ) {
+					jQuery.each( arguments, function( _, arg ) {
+						var index;
+						while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
+							list.splice( index, 1 );
+							// Handle firing indexes
+							if ( firing ) {
+								if ( index <= firingLength ) {
+									firingLength--;
+								}
+								if ( index <= firingIndex ) {
+									firingIndex--;
+								}
+							}
+						}
+					});
+				}
+				return this;
+			},
+			// Check if a given callback is in the list.
+			// If no argument is given, return whether or not list has callbacks attached.
+			has: function( fn ) {
+				return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
+			},
+			// Remove all callbacks from the list
+			empty: function() {
+				list = [];
+				firingLength = 0;
+				return this;
+			},
+			// Have the list do nothing anymore
+			disable: function() {
+				list = stack = memory = undefined;
+				return this;
+			},
+			// Is it disabled?
+			disabled: function() {
+				return !list;
+			},
+			// Lock the list in its current state
+			lock: function() {
+				stack = undefined;
+				if ( !memory ) {
+					self.disable();
+				}
+				return this;
+			},
+			// Is it locked?
+			locked: function() {
+				return !stack;
+			},
+			// Call all callbacks with the given context and arguments
+			fireWith: function( context, args ) {
+				if ( list && ( !fired || stack ) ) {
+					args = args || [];
+					args = [ context, args.slice ? args.slice() : args ];
+					if ( firing ) {
+						stack.push( args );
+					} else {
+						fire( args );
+					}
+				}
+				return this;
+			},
+			// Call all the callbacks with the given arguments
+			fire: function() {
+				self.fireWith( this, arguments );
+				return this;
+			},
+			// To know if the callbacks have already been called at least once
+			fired: function() {
+				return !!fired;
+			}
+		};
+
+	return self;
+};
+jQuery.extend({
+
+	Deferred: function( func ) {
+		var tuples = [
+				// action, add listener, listener list, final state
+				[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
+				[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
+				[ "notify", "progress", jQuery.Callbacks("memory") ]
+			],
+			state = "pending",
+			promise = {
+				state: function() {
+					return state;
+				},
+				always: function() {
+					deferred.done( arguments ).fail( arguments );
+					return this;
+				},
+				then: function( /* fnDone, fnFail, fnProgress */ ) {
+					var fns = arguments;
+					return jQuery.Deferred(function( newDefer ) {
+						jQuery.each( tuples, function( i, tuple ) {
+							var action = tuple[ 0 ],
+								fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
+							// deferred[ done | fail | progress ] for forwarding actions to newDefer
+							deferred[ tuple[1] ](function() {
+								var returned = fn && fn.apply( this, arguments );
+								if ( returned && jQuery.isFunction( returned.promise ) ) {
+									returned.promise()
+										.done( newDefer.resolve )
+										.fail( newDefer.reject )
+										.progress( newDefer.notify );
+								} else {
+									newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
+								}
+							});
+						});
+						fns = null;
+					}).promise();
+				},
+				// Get a promise for this deferred
+				// If obj is provided, the promise aspect is added to the object
+				promise: function( obj ) {
+					return obj != null ? jQuery.extend( obj, promise ) : promise;
+				}
+			},
+			deferred = {};
+
+		// Keep pipe for back-compat
+		promise.pipe = promise.then;
+
+		// Add list-specific methods
+		jQuery.each( tuples, function( i, tuple ) {
+			var list = tuple[ 2 ],
+				stateString = tuple[ 3 ];
+
+			// promise[ done | fail | progress ] = list.add
+			promise[ tuple[1] ] = list.add;
+
+			// Handle state
+			if ( stateString ) {
+				list.add(function() {
+					// state = [ resolved | rejected ]
+					state = stateString;
+
+				// [ reject_list | resolve_list ].disable; progress_list.lock
+				}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
+			}
+
+			// deferred[ resolve | reject | notify ]
+			deferred[ tuple[0] ] = function() {
+				deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
+				return this;
+			};
+			deferred[ tuple[0] + "With" ] = list.fireWith;
+		});
+
+		// Make the deferred a promise
+		promise.promise( deferred );
+
+		// Call given func if any
+		if ( func ) {
+			func.call( deferred, deferred );
+		}
+
+		// All done!
+		return deferred;
+	},
+
+	// Deferred helper
+	when: function( subordinate /* , ..., subordinateN */ ) {
+		var i = 0,
+			resolveValues = core_slice.call( arguments ),
+			length = resolveValues.length,
+
+			// the count of uncompleted subordinates
+			remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
+
+			// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
+			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
+
+			// Update function for both resolve and progress values
+			updateFunc = function( i, contexts, values ) {
+				return function( value ) {
+					contexts[ i ] = this;
+					values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
+					if( values === progressValues ) {
+						deferred.notifyWith( contexts, values );
+					} else if ( !( --remaining ) ) {
+						deferred.resolveWith( contexts, values );
+					}
+				};
+			},
+
+			progressValues, progressContexts, resolveContexts;
+
+		// add listeners to Deferred subordinates; treat others as resolved
+		if ( length > 1 ) {
+			progressValues = new Array( length );
+			progressContexts = new Array( length );
+			resolveContexts = new Array( length );
+			for ( ; i < length; i++ ) {
+				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
+					resolveValues[ i ].promise()
+						.done( updateFunc( i, resolveContexts, resolveValues ) )
+						.fail( deferred.reject )
+						.progress( updateFunc( i, progressContexts, progressValues ) );
+				} else {
+					--remaining;
+				}
+			}
+		}
+
+		// if we're not waiting on anything, resolve the master
+		if ( !remaining ) {
+			deferred.resolveWith( resolveContexts, resolveValues );
+		}
+
+		return deferred.promise();
+	}
+});
+jQuery.support = (function( support ) {
+
+	var all, a, input, select, fragment, opt, eventName, isSupported, i,
+		div = document.createElement("div");
+
+	// Setup
+	div.setAttribute( "className", "t" );
+	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
+
+	// Finish early in limited (non-browser) environments
+	all = div.getElementsByTagName("*") || [];
+	a = div.getElementsByTagName("a")[ 0 ];
+	if ( !a || !a.style || !all.length ) {
+		return support;
+	}
+
+	// First batch of tests
+	select = document.createElement("select");
+	opt = select.appendChild( document.createElement("option") );
+	input = div.getElementsByTagName("input")[ 0 ];
+
+	a.style.cssText = "top:1px;float:left;opacity:.5";
+
+	// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
+	support.getSetAttribute = div.className !== "t";
+
+	// IE strips leading whitespace when .innerHTML is used
+	support.leadingWhitespace = div.firstChild.nodeType === 3;
+
+	// Make sure that tbody elements aren't automatically inserted
+	// IE will insert them into empty tables
+	support.tbody = !div.getElementsByTagName("tbody").length;
+
+	// Make sure that link elements get serialized correctly by innerHTML
+	// This requires a wrapper element in IE
+	support.htmlSerialize = !!div.getElementsByTagName("link").length;
+
+	// Get the style information from getAttribute
+	// (IE uses .cssText instead)
+	support.style = /top/.test( a.getAttribute("style") );
+
+	// Make sure that URLs aren't manipulated
+	// (IE normalizes it by default)
+	support.hrefNormalized = a.getAttribute("href") === "/a";
+
+	// Make sure that element opacity exists
+	// (IE uses filter instead)
+	// Use a regex to work around a WebKit issue. See #5145
+	support.opacity = /^0.5/.test( a.style.opacity );
+
+	// Verify style float existence
+	// (IE uses styleFloat instead of cssFloat)
+	support.cssFloat = !!a.style.cssFloat;
+
+	// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
+	support.checkOn = !!input.value;
+
+	// Make sure that a selected-by-default option has a working selected property.
+	// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
+	support.optSelected = opt.selected;
+
+	// Tests for enctype support on a form (#6743)
+	support.enctype = !!document.createElement("form").enctype;
+
+	// Makes sure cloning an html5 element does not cause problems
+	// Where outerHTML is undefined, this still works
+	support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
+
+	// Will be defined later
+	support.inlineBlockNeedsLayout = false;
+	support.shrinkWrapBlocks = false;
+	support.pixelPosition = false;
+	support.deleteExpando = true;
+	support.noCloneEvent = true;
+	support.reliableMarginRight = true;
+	support.boxSizingReliable = true;
+
+	// Make sure checked status is properly cloned
+	input.checked = true;
+	support.noCloneChecked = input.cloneNode( true ).checked;
+
+	// Make sure that the options inside disabled selects aren't marked as disabled
+	// (WebKit marks them as disabled)
+	select.disabled = true;
+	support.optDisabled = !opt.disabled;
+
+	// Support: IE<9
+	try {
+		delete div.test;
+	} catch( e ) {
+		support.deleteExpando = false;
+	}
+
+	// Check if we can trust getAttribute("value")
+	input = document.createElement("input");
+	input.setAttribute( "value", "" );
+	support.input = input.getAttribute( "value" ) === "";
+
+	// Check if an input maintains its value after becoming a radio
+	input.value = "t";
+	input.setAttribute( "type", "radio" );
+	support.radioValue = input.value === "t";
+
+	// #11217 - WebKit loses check when the name is after the checked attribute
+	input.setAttribute( "checked", "t" );
+	input.setAttribute( "name", "t" );
+
+	fragment = document.createDocumentFragment();
+	fragment.appendChild( input );
+
+	// Check if a disconnected checkbox will retain its checked
+	// value of true after appended to the DOM (IE6/7)
+	support.appendChecked = input.checked;
+
+	// WebKit doesn't clone checked state correctly in fragments
+	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+	// Support: IE<9
+	// Opera does not clone events (and typeof div.attachEvent === undefined).
+	// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
+	if ( div.attachEvent ) {
+		div.attachEvent( "onclick", function() {
+			support.noCloneEvent = false;
+		});
+
+		div.cloneNode( true ).click();
+	}
+
+	// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
+	// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
+	for ( i in { submit: true, change: true, focusin: true }) {
+		div.setAttribute( eventName = "on" + i, "t" );
+
+		support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
+	}
+
+	div.style.backgroundClip = "content-box";
+	div.cloneNode( true ).style.backgroundClip = "";
+	support.clearCloneStyle = div.style.backgroundClip === "content-box";
+
+	// Support: IE<9
+	// Iteration over object's inherited properties before its own.
+	for ( i in jQuery( support ) ) {
+		break;
+	}
+	support.ownLast = i !== "0";
+
+	// Run tests that need a body at doc ready
+	jQuery(function() {
+		var container, marginDiv, tds,
+			divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
+			body = document.getElementsByTagName("body")[0];
+
+		if ( !body ) {
+			// Return for frameset docs that don't have a body
+			return;
+		}
+
+		container = document.createElement("div");
+		container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
+
+		body.appendChild( container ).appendChild( div );
+
+		// Support: IE8
+		// Check if table cells still have offsetWidth/Height when they are set
+		// to display:none and there are still other visible table cells in a
+		// table row; if so, offsetWidth/Height are not reliable for use when
+		// determining if an element has been hidden directly using
+		// display:none (it is still safe to use offsets if a parent element is
+		// hidden; don safety goggles and see bug #4512 for more information).
+		div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
+		tds = div.getElementsByTagName("td");
+		tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
+		isSupported = ( tds[ 0 ].offsetHeight === 0 );
+
+		tds[ 0 ].style.display = "";
+		tds[ 1 ].style.display = "none";
+
+		// Support: IE8
+		// Check if empty table cells still have offsetWidth/Height
+		support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
+
+		// Check box-sizing and margin behavior.
+		div.innerHTML = "";
+		div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
+
+		// Workaround failing boxSizing test due to offsetWidth returning wrong value
+		// with some non-1 values of body zoom, ticket #13543
+		jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
+			support.boxSizing = div.offsetWidth === 4;
+		});
+
+		// Use window.getComputedStyle because jsdom on node.js will break without it.
+		if ( window.getComputedStyle ) {
+			support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
+			support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
+
+			// Check if div with explicit width and no margin-right incorrectly
+			// gets computed margin-right based on width of container. (#3333)
+			// Fails in WebKit before Feb 2011 nightlies
+			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+			marginDiv = div.appendChild( document.createElement("div") );
+			marginDiv.style.cssText = div.style.cssText = divReset;
+			marginDiv.style.marginRight = marginDiv.style.width = "0";
+			div.style.width = "1px";
+
+			support.reliableMarginRight =
+				!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
+		}
+
+		if ( typeof div.style.zoom !== core_strundefined ) {
+			// Support: IE<8
+			// Check if natively block-level elements act like inline-block
+			// elements when setting their display to 'inline' and giving
+			// them layout
+			div.innerHTML = "";
+			div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
+			support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
+
+			// Support: IE6
+			// Check if elements with layout shrink-wrap their children
+			div.style.display = "block";
+			div.innerHTML = "<div></div>";
+			div.firstChild.style.width = "5px";
+			support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
+
+			if ( support.inlineBlockNeedsLayout ) {
+				// Prevent IE 6 from affecting layout for positioned elements #11048
+				// Prevent IE from shrinking the body in IE 7 mode #12869
+				// Support: IE<8
+				body.style.zoom = 1;
+			}
+		}
+
+		body.removeChild( container );
+
+		// Null elements to avoid leaks in IE
+		container = div = tds = marginDiv = null;
+	});
+
+	// Null elements to avoid leaks in IE
+	all = select = fragment = opt = a = input = null;
+
+	return support;
+})({});
+
+var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
+	rmultiDash = /([A-Z])/g;
+
+function internalData( elem, name, data, pvt /* Internal Use Only */ ){
+	if ( !jQuery.acceptData( elem ) ) {
+		return;
+	}
+
+	var ret, thisCache,
+		internalKey = jQuery.expando,
+
+		// We have to handle DOM nodes and JS objects differently because IE6-7
+		// can't GC object references properly across the DOM-JS boundary
+		isNode = elem.nodeType,
+
+		// Only DOM nodes need the global jQuery cache; JS object data is
+		// attached directly to the object so GC can occur automatically
+		cache = isNode ? jQuery.cache : elem,
+
+		// Only defining an ID for JS objects if its cache already exists allows
+		// the code to shortcut on the same path as a DOM node with no cache
+		id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
+
+	// Avoid doing any more work than we need to when trying to get data on an
+	// object that has no data at all
+	if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
+		return;
+	}
+
+	if ( !id ) {
+		// Only DOM nodes need a new unique ID for each element since their data
+		// ends up in the global cache
+		if ( isNode ) {
+			id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
+		} else {
+			id = internalKey;
+		}
+	}
+
+	if ( !cache[ id ] ) {
+		// Avoid exposing jQuery metadata on plain JS objects when the object
+		// is serialized using JSON.stringify
+		cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
+	}
+
+	// An object can be passed to jQuery.data instead of a key/value pair; this gets
+	// shallow copied over onto the existing cache
+	if ( typeof name === "object" || typeof name === "function" ) {
+		if ( pvt ) {
+			cache[ id ] = jQuery.extend( cache[ id ], name );
+		} else {
+			cache[ id ].data = jQuery.extend( cache[ id ].data, name );
+		}
+	}
+
+	thisCache = cache[ id ];
+
+	// jQuery data() is stored in a separate object inside the object's internal data
+	// cache in order to avoid key collisions between internal data and user-defined
+	// data.
+	if ( !pvt ) {
+		if ( !thisCache.data ) {
+			thisCache.data = {};
+		}
+
+		thisCache = thisCache.data;
+	}
+
+	if ( data !== undefined ) {
+		thisCache[ jQuery.camelCase( name ) ] = data;
+	}
+
+	// Check for both converted-to-camel and non-converted data property names
+	// If a data property was specified
+	if ( typeof name === "string" ) {
+
+		// First Try to find as-is property data
+		ret = thisCache[ name ];
+
+		// Test for null|undefined property data
+		if ( ret == null ) {
+
+			// Try to find the camelCased property
+			ret = thisCache[ jQuery.camelCase( name ) ];
+		}
+	} else {
+		ret = thisCache;
+	}
+
+	return ret;
+}
+
+function internalRemoveData( elem, name, pvt ) {
+	if ( !jQuery.acceptData( elem ) ) {
+		return;
+	}
+
+	var thisCache, i,
+		isNode = elem.nodeType,
+
+		// See jQuery.data for more information
+		cache = isNode ? jQuery.cache : elem,
+		id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
+
+	// If there is already no cache entry for this object, there is no
+	// purpose in continuing
+	if ( !cache[ id ] ) {
+		return;
+	}
+
+	if ( name ) {
+
+		thisCache = pvt ? cache[ id ] : cache[ id ].data;
+
+		if ( thisCache ) {
+
+			// Support array or space separated string names for data keys
+			if ( !jQuery.isArray( name ) ) {
+
+				// try the string as a key before any manipulation
+				if ( name in thisCache ) {
+					name = [ name ];
+				} else {
+
+					// split the camel cased version by spaces unless a key with the spaces exists
+					name = jQuery.camelCase( name );
+					if ( name in thisCache ) {
+						name = [ name ];
+					} else {
+						name = name.split(" ");
+					}
+				}
+			} else {
+				// If "name" is an array of keys...
+				// When data is initially created, via ("key", "val") signature,
+				// keys will be converted to camelCase.
+				// Since there is no way to tell _how_ a key was added, remove
+				// both plain key and camelCase key. #12786
+				// This will only penalize the array argument path.
+				name = name.concat( jQuery.map( name, jQuery.camelCase ) );
+			}
+
+			i = name.length;
+			while ( i-- ) {
+				delete thisCache[ name[i] ];
+			}
+
+			// If there is no data left in the cache, we want to continue
+			// and let the cache object itself get destroyed
+			if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
+				return;
+			}
+		}
+	}
+
+	// See jQuery.data for more information
+	if ( !pvt ) {
+		delete cache[ id ].data;
+
+		// Don't destroy the parent cache unless the internal data object
+		// had been the only thing left in it
+		if ( !isEmptyDataObject( cache[ id ] ) ) {
+			return;
+		}
+	}
+
+	// Destroy the cache
+	if ( isNode ) {
+		jQuery.cleanData( [ elem ], true );
+
+	// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
+	/* jshint eqeqeq: false */
+	} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
+		/* jshint eqeqeq: true */
+		delete cache[ id ];
+
+	// When all else fails, null
+	} else {
+		cache[ id ] = null;
+	}
+}
+
+jQuery.extend({
+	cache: {},
+
+	// The following elements throw uncatchable exceptions if you
+	// attempt to add expando properties to them.
+	noData: {
+		"applet": true,
+		"embed": true,
+		// Ban all objects except for Flash (which handle expandos)
+		"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
+	},
+
+	hasData: function( elem ) {
+		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+		return !!elem && !isEmptyDataObject( elem );
+	},
+
+	data: function( elem, name, data ) {
+		return internalData( elem, name, data );
+	},
+
+	removeData: function( elem, name ) {
+		return internalRemoveData( elem, name );
+	},
+
+	// For internal use only.
+	_data: function( elem, name, data ) {
+		return internalData( elem, name, data, true );
+	},
+
+	_removeData: function( elem, name ) {
+		return internalRemoveData( elem, name, true );
+	},
+
+	// A method for determining if a DOM node can handle the data expando
+	acceptData: function( elem ) {
+		// Do not set data on non-element because it will not be cleared (#8335).
+		if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
+			return false;
+		}
+
+		var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
+
+		// nodes accept data unless otherwise specified; rejection can be conditional
+		return !noData || noData !== true && elem.getAttribute("classid") === noData;
+	}
+});
+
+jQuery.fn.extend({
+	data: function( key, value ) {
+		var attrs, name,
+			data = null,
+			i = 0,
+			elem = this[0];
+
+		// Special expections of .data basically thwart jQuery.access,
+		// so implement the relevant behavior ourselves
+
+		// Gets all values
+		if ( key === undefined ) {
+			if ( this.length ) {
+				data = jQuery.data( elem );
+
+				if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
+					attrs = elem.attributes;
+					for ( ; i < attrs.length; i++ ) {
+						name = attrs[i].name;
+
+						if ( name.indexOf("data-") === 0 ) {
+							name = jQuery.camelCase( name.slice(5) );
+
+							dataAttr( elem, name, data[ name ] );
+						}
+					}
+					jQuery._data( elem, "parsedAttrs", true );
+				}
+			}
+
+			return data;
+		}
+
+		// Sets multiple values
+		if ( typeof key === "object" ) {
+			return this.each(function() {
+				jQuery.data( this, key );
+			});
+		}
+
+		return arguments.length > 1 ?
+
+			// Sets one value
+			this.each(function() {
+				jQuery.data( this, key, value );
+			}) :
+
+			// Gets one value
+			// Try to fetch any internally stored data first
+			elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
+	},
+
+	removeData: function( key ) {
+		return this.each(function() {
+			jQuery.removeData( this, key );
+		});
+	}
+});
+
+function dataAttr( elem, key, data ) {
+	// If nothing was found internally, try to fetch any
+	// data from the HTML5 data-* attribute
+	if ( data === undefined && elem.nodeType === 1 ) {
+
+		var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
+
+		data = elem.getAttribute( name );
+
+		if ( typeof data === "string" ) {
+			try {
+				data = data === "true" ? true :
+					data === "false" ? false :
+					data === "null" ? null :
+					// Only convert to a number if it doesn't change the string
+					+data + "" === data ? +data :
+					rbrace.test( data ) ? jQuery.parseJSON( data ) :
+						data;
+			} catch( e ) {}
+
+			// Make sure we set the data so it isn't changed later
+			jQuery.data( elem, key, data );
+
+		} else {
+			data = undefined;
+		}
+	}
+
+	return data;
+}
+
+// checks a cache object for emptiness
+function isEmptyDataObject( obj ) {
+	var name;
+	for ( name in obj ) {
+
+		// if the public data object is empty, the private is still empty
+		if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
+			continue;
+		}
+		if ( name !== "toJSON" ) {
+			return false;
+		}
+	}
+
+	return true;
+}
+jQuery.extend({
+	queue: function( elem, type, data ) {
+		var queue;
+
+		if ( elem ) {
+			type = ( type || "fx" ) + "queue";
+			queue = jQuery._data( elem, type );
+
+			// Speed up dequeue by getting out quickly if this is just a lookup
+			if ( data ) {
+				if ( !queue || jQuery.isArray(data) ) {
+					queue = jQuery._data( elem, type, jQuery.makeArray(data) );
+				} else {
+					queue.push( data );
+				}
+			}
+			return queue || [];
+		}
+	},
+
+	dequeue: function( elem, type ) {
+		type = type || "fx";
+
+		var queue = jQuery.queue( elem, type ),
+			startLength = queue.length,
+			fn = queue.shift(),
+			hooks = jQuery._queueHooks( elem, type ),
+			next = function() {
+				jQuery.dequeue( elem, type );
+			};
+
+		// If the fx queue is dequeued, always remove the progress sentinel
+		if ( fn === "inprogress" ) {
+			fn = queue.shift();
+			startLength--;
+		}
+
+		if ( fn ) {
+
+			// Add a progress sentinel to prevent the fx queue from being
+			// automatically dequeued
+			if ( type === "fx" ) {
+				queue.unshift( "inprogress" );
+			}
+
+			// clear up the last queue stop function
+			delete hooks.stop;
+			fn.call( elem, next, hooks );
+		}
+
+		if ( !startLength && hooks ) {
+			hooks.empty.fire();
+		}
+	},
+
+	// not intended for public consumption - generates a queueHooks object, or returns the current one
+	_queueHooks: function( elem, type ) {
+		var key = type + "queueHooks";
+		return jQuery._data( elem, key ) || jQuery._data( elem, key, {
+			empty: jQuery.Callbacks("once memory").add(function() {
+				jQuery._removeData( elem, type + "queue" );
+				jQuery._removeData( elem, key );
+			})
+		});
+	}
+});
+
+jQuery.fn.extend({
+	queue: function( type, data ) {
+		var setter = 2;
+
+		if ( typeof type !== "string" ) {
+			data = type;
+			type = "fx";
+			setter--;
+		}
+
+		if ( arguments.length < setter ) {
+			return jQuery.queue( this[0], type );
+		}
+
+		return data === undefined ?
+			this :
+			this.each(function() {
+				var queue = jQuery.queue( this, type, data );
+
+				// ensure a hooks for this queue
+				jQuery._queueHooks( this, type );
+
+				if ( type === "fx" && queue[0] !== "inprogress" ) {
+					jQuery.dequeue( this, type );
+				}
+			});
+	},
+	dequeue: function( type ) {
+		return this.each(function() {
+			jQuery.dequeue( this, type );
+		});
+	},
+	// Based off of the plugin by Clint Helfers, with permission.
+	// http://blindsignals.com/index.php/2009/07/jquery-delay/
+	delay: function( time, type ) {
+		time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
+		type = type || "fx";
+
+		return this.queue( type, function( next, hooks ) {
+			var timeout = setTimeout( next, time );
+			hooks.stop = function() {
+				clearTimeout( timeout );
+			};
+		});
+	},
+	clearQueue: function( type ) {
+		return this.queue( type || "fx", [] );
+	},
+	// Get a promise resolved when queues of a certain type
+	// are emptied (fx is the type by default)
+	promise: function( type, obj ) {
+		var tmp,
+			count = 1,
+			defer = jQuery.Deferred(),
+			elements = this,
+			i = this.length,
+			resolve = function() {
+				if ( !( --count ) ) {
+					defer.resolveWith( elements, [ elements ] );
+				}
+			};
+
+		if ( typeof type !== "string" ) {
+			obj = type;
+			type = undefined;
+		}
+		type = type || "fx";
+
+		while( i-- ) {
+			tmp = jQuery._data( elements[ i ], type + "queueHooks" );
+			if ( tmp && tmp.empty ) {
+				count++;
+				tmp.empty.add( resolve );
+			}
+		}
+		resolve();
+		return defer.promise( obj );
+	}
+});
+var nodeHook, boolHook,
+	rclass = /[\t\r\n\f]/g,
+	rreturn = /\r/g,
+	rfocusable = /^(?:input|select|textarea|button|object)$/i,
+	rclickable = /^(?:a|area)$/i,
+	ruseDefault = /^(?:checked|selected)$/i,
+	getSetAttribute = jQuery.support.getSetAttribute,
+	getSetInput = jQuery.support.input;
+
+jQuery.fn.extend({
+	attr: function( name, value ) {
+		return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
+	},
+
+	removeAttr: function( name ) {
+		return this.each(function() {
+			jQuery.removeAttr( this, name );
+		});
+	},
+
+	prop: function( name, value ) {
+		return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
+	},
+
+	removeProp: function( name ) {
+		name = jQuery.propFix[ name ] || name;
+		return this.each(function() {
+			// try/catch handles cases where IE balks (such as removing a property on window)
+			try {
+				this[ name ] = undefined;
+				delete this[ name ];
+			} catch( e ) {}
+		});
+	},
+
+	addClass: function( value ) {
+		var classes, elem, cur, clazz, j,
+			i = 0,
+			len = this.length,
+			proceed = typeof value === "string" && value;
+
+		if ( jQuery.isFunction( value ) ) {
+			return this.each(function( j ) {
+				jQuery( this ).addClass( value.call( this, j, this.className ) );
+			});
+		}
+
+		if ( proceed ) {
+			// The disjunction here is for better compressibility (see removeClass)
+			classes = ( value || "" ).match( core_rnotwhite ) || [];
+
+			for ( ; i < len; i++ ) {
+				elem = this[ i ];
+				cur = elem.nodeType === 1 && ( elem.className ?
+					( " " + elem.className + " " ).replace( rclass, " " ) :
+					" "
+				);
+
+				if ( cur ) {
+					j = 0;
+					while ( (clazz = classes[j++]) ) {
+						if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
+							cur += clazz + " ";
+						}
+					}
+					elem.className = jQuery.trim( cur );
+
+				}
+			}
+		}
+
+		return this;
+	},
+
+	removeClass: function( value ) {
+		var classes, elem, cur, clazz, j,
+			i = 0,
+			len = this.length,
+			proceed = arguments.length === 0 || typeof value === "string" && value;
+
+		if ( jQuery.isFunction( value ) ) {
+			return this.each(function( j ) {
+				jQuery( this ).removeClass( value.call( this, j, this.className ) );
+			});
+		}
+		if ( proceed ) {
+			classes = ( value || "" ).match( core_rnotwhite ) || [];
+
+			for ( ; i < len; i++ ) {
+				elem = this[ i ];
+				// This expression is here for better compressibility (see addClass)
+				cur = elem.nodeType === 1 && ( elem.className ?
+					( " " + elem.className + " " ).replace( rclass, " " ) :
+					""
+				);
+
+				if ( cur ) {
+					j = 0;
+					while ( (clazz = classes[j++]) ) {
+						// Remove *all* instances
+						while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
+							cur = cur.replace( " " + clazz + " ", " " );
+						}
+					}
+					elem.className = value ? jQuery.trim( cur ) : "";
+				}
+			}
+		}
+
+		return this;
+	},
+
+	toggleClass: function( value, stateVal ) {
+		var type = typeof value;
+
+		if ( typeof stateVal === "boolean" && type === "string" ) {
+			return stateVal ? this.addClass( value ) : this.removeClass( value );
+		}
+
+		if ( jQuery.isFunction( value ) ) {
+			return this.each(function( i ) {
+				jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
+			});
+		}
+
+		return this.each(function() {
+			if ( type === "string" ) {
+				// toggle individual class names
+				var className,
+					i = 0,
+					self = jQuery( this ),
+					classNames = value.match( core_rnotwhite ) || [];
+
+				while ( (className = classNames[ i++ ]) ) {
+					// check each className given, space separated list
+					if ( self.hasClass( className ) ) {
+						self.removeClass( className );
+					} else {
+						self.addClass( className );
+					}
+				}
+
+			// Toggle whole class name
+			} else if ( type === core_strundefined || type === "boolean" ) {
+				if ( this.className ) {
+					// store className if set
+					jQuery._data( this, "__className__", this.className );
+				}
+
+				// If the element has a class name or if we're passed "false",
+				// then remove the whole classname (if there was one, the above saved it).
+				// Otherwise bring back whatever was previously saved (if anything),
+				// falling back to the empty string if nothing was stored.
+				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
+			}
+		});
+	},
+
+	hasClass: function( selector ) {
+		var className = " " + selector + " ",
+			i = 0,
+			l = this.length;
+		for ( ; i < l; i++ ) {
+			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
+				return true;
+			}
+		}
+
+		return false;
+	},
+
+	val: function( value ) {
+		var ret, hooks, isFunction,
+			elem = this[0];
+
+		if ( !arguments.length ) {
+			if ( elem ) {
+				hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
+
+				if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
+					return ret;
+				}
+
+				ret = elem.value;
+
+				return typeof ret === "string" ?
+					// handle most common string cases
+					ret.replace(rreturn, "") :
+					// handle cases where value is null/undef or number
+					ret == null ? "" : ret;
+			}
+
+			return;
+		}
+
+		isFunction = jQuery.isFunction( value );
+
+		return this.each(function( i ) {
+			var val;
+
+			if ( this.nodeType !== 1 ) {
+				return;
+			}
+
+			if ( isFunction ) {
+				val = value.call( this, i, jQuery( this ).val() );
+			} else {
+				val = value;
+			}
+
+			// Treat null/undefined as ""; convert numbers to string
+			if ( val == null ) {
+				val = "";
+			} else if ( typeof val === "number" ) {
+				val += "";
+			} else if ( jQuery.isArray( val ) ) {
+				val = jQuery.map(val, function ( value ) {
+					return value == null ? "" : value + "";
+				});
+			}
+
+			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
+
+			// If set returns undefined, fall back to normal setting
+			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
+				this.value = val;
+			}
+		});
+	}
+});
+
+jQuery.extend({
+	valHooks: {
+		option: {
+			get: function( elem ) {
+				// Use proper attribute retrieval(#6932, #12072)
+				var val = jQuery.find.attr( elem, "value" );
+				return val != null ?
+					val :
+					elem.text;
+			}
+		},
+		select: {
+			get: function( elem ) {
+				var value, option,
+					options = elem.options,
+					index = elem.selectedIndex,
+					one = elem.type === "select-one" || index < 0,
+					values = one ? null : [],
+					max = one ? index + 1 : options.length,
+					i = index < 0 ?
+						max :
+						one ? index : 0;
+
+				// Loop through all the selected options
+				for ( ; i < max; i++ ) {
+					option = options[ i ];
+
+					// oldIE doesn't update selected after form reset (#2551)
+					if ( ( option.selected || i === index ) &&
+							// Don't return options that are disabled or in a disabled optgroup
+							( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
+							( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
+
+						// Get the specific value for the option
+						value = jQuery( option ).val();
+
+						// We don't need an array for one selects
+						if ( one ) {
+							return value;
+						}
+
+						// Multi-Selects return an array
+						values.push( value );
+					}
+				}
+
+				return values;
+			},
+
+			set: function( elem, value ) {
+				var optionSet, option,
+					options = elem.options,
+					values = jQuery.makeArray( value ),
+					i = options.length;
+
+				while ( i-- ) {
+					option = options[ i ];
+					if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
+						optionSet = true;
+					}
+				}
+
+				// force browsers to behave consistently when non-matching value is set
+				if ( !optionSet ) {
+					elem.selectedIndex = -1;
+				}
+				return values;
+			}
+		}
+	},
+
+	attr: function( elem, name, value ) {
+		var hooks, ret,
+			nType = elem.nodeType;
+
+		// don't get/set attributes on text, comment and attribute nodes
+		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+			return;
+		}
+
+		// Fallback to prop when attributes are not supported
+		if ( typeof elem.getAttribute === core_strundefined ) {
+			return jQuery.prop( elem, name, value );
+		}
+
+		// All attributes are lowercase
+		// Grab necessary hook if one is defined
+		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
+			name = name.toLowerCase();
+			hooks = jQuery.attrHooks[ name ] ||
+				( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
+		}
+
+		if ( value !== undefined ) {
+
+			if ( value === null ) {
+				jQuery.removeAttr( elem, name );
+
+			} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
+				return ret;
+
+			} else {
+				elem.setAttribute( name, value + "" );
+				return value;
+			}
+
+		} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
+			return ret;
+
+		} else {
+			ret = jQuery.find.attr( elem, name );
+
+			// Non-existent attributes return null, we normalize to undefined
+			return ret == null ?
+				undefined :
+				ret;
+		}
+	},
+
+	removeAttr: function( elem, value ) {
+		var name, propName,
+			i = 0,
+			attrNames = value && value.match( core_rnotwhite );
+
+		if ( attrNames && elem.nodeType === 1 ) {
+			while ( (name = attrNames[i++]) ) {
+				propName = jQuery.propFix[ name ] || name;
+
+				// Boolean attributes get special treatment (#10870)
+				if ( jQuery.expr.match.bool.test( name ) ) {
+					// Set corresponding property to false
+					if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
+						elem[ propName ] = false;
+					// Support: IE<9
+					// Also clear defaultChecked/defaultSelected (if appropriate)
+					} else {
+						elem[ jQuery.camelCase( "default-" + name ) ] =
+							elem[ propName ] = false;
+					}
+
+				// See #9699 for explanation of this approach (setting first, then removal)
+				} else {
+					jQuery.attr( elem, name, "" );
+				}
+
+				elem.removeAttribute( getSetAttribute ? name : propName );
+			}
+		}
+	},
+
+	attrHooks: {
+		type: {
+			set: function( elem, value ) {
+				if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
+					// Setting the type on a radio button after the value resets the value in IE6-9
+					// Reset value to default in case type is set after value during creation
+					var val = elem.value;
+					elem.setAttribute( "type", value );
+					if ( val ) {
+						elem.value = val;
+					}
+					return value;
+				}
+			}
+		}
+	},
+
+	propFix: {
+		"for": "htmlFor",
+		"class": "className"
+	},
+
+	prop: function( elem, name, value ) {
+		var ret, hooks, notxml,
+			nType = elem.nodeType;
+
+		// don't get/set properties on text, comment and attribute nodes
+		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+			return;
+		}
+
+		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+		if ( notxml ) {
+			// Fix name and attach hooks
+			name = jQuery.propFix[ name ] || name;
+			hooks = jQuery.propHooks[ name ];
+		}
+
+		if ( value !== undefined ) {
+			return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
+				ret :
+				( elem[ name ] = value );
+
+		} else {
+			return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
+				ret :
+				elem[ name ];
+		}
+	},
+
+	propHooks: {
+		tabIndex: {
+			get: function( elem ) {
+				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+				// Use proper attribute retrieval(#12072)
+				var tabindex = jQuery.find.attr( elem, "tabindex" );
+
+				return tabindex ?
+					parseInt( tabindex, 10 ) :
+					rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+						0 :
+						-1;
+			}
+		}
+	}
+});
+
+// Hooks for boolean attributes
+boolHook = {
+	set: function( elem, value, name ) {
+		if ( value === false ) {
+			// Remove boolean attributes when set to false
+			jQuery.removeAttr( elem, name );
+		} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
+			// IE<8 needs the *property* name
+			elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
+
+		// Use defaultChecked and defaultSelected for oldIE
+		} else {
+			elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
+		}
+
+		return name;
+	}
+};
+jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
+	var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
+
+	jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
+		function( elem, name, isXML ) {
+			var fn = jQuery.expr.attrHandle[ name ],
+				ret = isXML ?
+					undefined :
+					/* jshint eqeqeq: false */
+					(jQuery.expr.attrHandle[ name ] = undefined) !=
+						getter( elem, name, isXML ) ?
+
+						name.toLowerCase() :
+						null;
+			jQuery.expr.attrHandle[ name ] = fn;
+			return ret;
+		} :
+		function( elem, name, isXML ) {
+			return isXML ?
+				undefined :
+				elem[ jQuery.camelCase( "default-" + name ) ] ?
+					name.toLowerCase() :
+					null;
+		};
+});
+
+// fix oldIE attroperties
+if ( !getSetInput || !getSetAttribute ) {
+	jQuery.attrHooks.value = {
+		set: function( elem, value, name ) {
+			if ( jQuery.nodeName( elem, "input" ) ) {
+				// Does not return so that setAttribute is also used
+				elem.defaultValue = value;
+			} else {
+				// Use nodeHook if defined (#1954); otherwise setAttribute is fine
+				return nodeHook && nodeHook.set( elem, value, name );
+			}
+		}
+	};
+}
+
+// IE6/7 do not support getting/setting some attributes with get/setAttribute
+if ( !getSetAttribute ) {
+
+	// Use this for any attribute in IE6/7
+	// This fixes almost every IE6/7 issue
+	nodeHook = {
+		set: function( elem, value, name ) {
+			// Set the existing or create a new attribute node
+			var ret = elem.getAttributeNode( name );
+			if ( !ret ) {
+				elem.setAttributeNode(
+					(ret = elem.ownerDocument.createAttribute( name ))
+				);
+			}
+
+			ret.value = value += "";
+
+			// Break association with cloned elements by also using setAttribute (#9646)
+			return name === "value" || value === elem.getAttribute( name ) ?
+				value :
+				undefined;
+		}
+	};
+	jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
+		// Some attributes are constructed with empty-string values when not defined
+		function( elem, name, isXML ) {
+			var ret;
+			return isXML ?
+				undefined :
+				(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
+					ret.value :
+					null;
+		};
+	jQuery.valHooks.button = {
+		get: function( elem, name ) {
+			var ret = elem.getAttributeNode( name );
+			return ret && ret.specified ?
+				ret.value :
+				undefined;
+		},
+		set: nodeHook.set
+	};
+
+	// Set contenteditable to false on removals(#10429)
+	// Setting to empty string throws an error as an invalid value
+	jQuery.attrHooks.contenteditable = {
+		set: function( elem, value, name ) {
+			nodeHook.set( elem, value === "" ? false : value, name );
+		}
+	};
+
+	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
+	// This is for removals
+	jQuery.each([ "width", "height" ], function( i, name ) {
+		jQuery.attrHooks[ name ] = {
+			set: function( elem, value ) {
+				if ( value === "" ) {
+					elem.setAttribute( name, "auto" );
+					return value;
+				}
+			}
+		};
+	});
+}
+
+
+// Some attributes require a special call on IE
+// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
+if ( !jQuery.support.hrefNormalized ) {
+	// href/src property should get the full normalized URL (#10299/#12915)
+	jQuery.each([ "href", "src" ], function( i, name ) {
+		jQuery.propHooks[ name ] = {
+			get: function( elem ) {
+				return elem.getAttribute( name, 4 );
+			}
+		};
+	});
+}
+
+if ( !jQuery.support.style ) {
+	jQuery.attrHooks.style = {
+		get: function( elem ) {
+			// Return undefined in the case of empty string
+			// Note: IE uppercases css property names, but if we were to .toLowerCase()
+			// .cssText, that would destroy case senstitivity in URL's, like in "background"
+			return elem.style.cssText || undefined;
+		},
+		set: function( elem, value ) {
+			return ( elem.style.cssText = value + "" );
+		}
+	};
+}
+
+// Safari mis-reports the default selected property of an option
+// Accessing the parent's selectedIndex property fixes it
+if ( !jQuery.support.optSelected ) {
+	jQuery.propHooks.selected = {
+		get: function( elem ) {
+			var parent = elem.parentNode;
+
+			if ( parent ) {
+				parent.selectedIndex;
+
+				// Make sure that it also works with optgroups, see #5701
+				if ( parent.parentNode ) {
+					parent.parentNode.selectedIndex;
+				}
+			}
+			return null;
+		}
+	};
+}
+
+jQuery.each([
+	"tabIndex",
+	"readOnly",
+	"maxLength",
+	"cellSpacing",
+	"cellPadding",
+	"rowSpan",
+	"colSpan",
+	"useMap",
+	"frameBorder",
+	"contentEditable"
+], function() {
+	jQuery.propFix[ this.toLowerCase() ] = this;
+});
+
+// IE6/7 call enctype encoding
+if ( !jQuery.support.enctype ) {
+	jQuery.propFix.enctype = "encoding";
+}
+
+// Radios and checkboxes getter/setter
+jQuery.each([ "radio", "checkbox" ], function() {
+	jQuery.valHooks[ this ] = {
+		set: function( elem, value ) {
+			if ( jQuery.isArray( value ) ) {
+				return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
+			}
+		}
+	};
+	if ( !jQuery.support.checkOn ) {
+		jQuery.valHooks[ this ].get = function( elem ) {
+			// Support: Webkit
+			// "" is returned instead of "on" if a value isn't specified
+			return elem.getAttribute("value") === null ? "on" : elem.value;
+		};
+	}
+});
+var rformElems = /^(?:input|select|textarea)$/i,
+	rkeyEvent = /^key/,
+	rmouseEvent = /^(?:mouse|contextmenu)|click/,
+	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
+	rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
+
+function returnTrue() {
+	return true;
+}
+
+function returnFalse() {
+	return false;
+}
+
+function safeActiveElement() {
+	try {
+		return document.activeElement;
+	} catch ( err ) { }
+}
+
+/*
+ * Helper functions for managing events -- not part of the public interface.
+ * Props to Dean Edwards' addEvent library for many of the ideas.
+ */
+jQuery.event = {
+
+	global: {},
+
+	add: function( elem, types, handler, data, selector ) {
+		var tmp, events, t, handleObjIn,
+			special, eventHandle, handleObj,
+			handlers, type, namespaces, origType,
+			elemData = jQuery._data( elem );
+
+		// Don't attach events to noData or text/comment nodes (but allow plain objects)
+		if ( !elemData ) {
+			return;
+		}
+
+		// Caller can pass in an object of custom data in lieu of the handler
+		if ( handler.handler ) {
+			handleObjIn = handler;
+			handler = handleObjIn.handler;
+			selector = handleObjIn.selector;
+		}
+
+		// Make sure that the handler has a unique ID, used to find/remove it later
+		if ( !handler.guid ) {
+			handler.guid = jQuery.guid++;
+		}
+
+		// Init the element's event structure and main handler, if this is the first
+		if ( !(events = elemData.events) ) {
+			events = elemData.events = {};
+		}
+		if ( !(eventHandle = elemData.handle) ) {
+			eventHandle = elemData.handle = function( e ) {
+				// Discard the second event of a jQuery.event.trigger() and
+				// when an event is called after a page has unloaded
+				return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
+					jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
+					undefined;
+			};
+			// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
+			eventHandle.elem = elem;
+		}
+
+		// Handle multiple events separated by a space
+		types = ( types || "" ).match( core_rnotwhite ) || [""];
+		t = types.length;
+		while ( t-- ) {
+			tmp = rtypenamespace.exec( types[t] ) || [];
+			type = origType = tmp[1];
+			namespaces = ( tmp[2] || "" ).split( "." ).sort();
+
+			// There *must* be a type, no attaching namespace-only handlers
+			if ( !type ) {
+				continue;
+			}
+
+			// If event changes its type, use the special event handlers for the changed type
+			special = jQuery.event.special[ type ] || {};
+
+			// If selector defined, determine special event api type, otherwise given type
+			type = ( selector ? special.delegateType : special.bindType ) || type;
+
+			// Update special based on newly reset type
+			special = jQuery.event.special[ type ] || {};
+
+			// handleObj is passed to all event handlers
+			handleObj = jQuery.extend({
+				type: type,
+				origType: origType,
+				data: data,
+				handler: handler,
+				guid: handler.guid,
+				selector: selector,
+				needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
+				namespace: namespaces.join(".")
+			}, handleObjIn );
+
+			// Init the event handler queue if we're the first
+			if ( !(handlers = events[ type ]) ) {
+				handlers = events[ type ] = [];
+				handlers.delegateCount = 0;
+
+				// Only use addEventListener/attachEvent if the special events handler returns false
+				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+					// Bind the global event handler to the element
+					if ( elem.addEventListener ) {
+						elem.addEventListener( type, eventHandle, false );
+
+					} else if ( elem.attachEvent ) {
+						elem.attachEvent( "on" + type, eventHandle );
+					}
+				}
+			}
+
+			if ( special.add ) {
+				special.add.call( elem, handleObj );
+
+				if ( !handleObj.handler.guid ) {
+					handleObj.handler.guid = handler.guid;
+				}
+			}
+
+			// Add to the element's handler list, delegates in front
+			if ( selector ) {
+				handlers.splice( handlers.delegateCount++, 0, handleObj );
+			} else {
+				handlers.push( handleObj );
+			}
+
+			// Keep track of which events have ever been used, for event optimization
+			jQuery.event.global[ type ] = true;
+		}
+
+		// Nullify elem to prevent memory leaks in IE
+		elem = null;
+	},
+
+	// Detach an event or set of events from an element
+	remove: function( elem, types, handler, selector, mappedTypes ) {
+		var j, handleObj, tmp,
+			origCount, t, events,
+			special, handlers, type,
+			namespaces, origType,
+			elemData = jQuery.hasData( elem ) && jQuery._data( elem );
+
+		if ( !elemData || !(events = elemData.events) ) {
+			return;
+		}
+
+		// Once for each type.namespace in types; type may be omitted
+		types = ( types || "" ).match( core_rnotwhite ) || [""];
+		t = types.length;
+		while ( t-- ) {
+			tmp = rtypenamespace.exec( types[t] ) || [];
+			type = origType = tmp[1];
+			namespaces = ( tmp[2] || "" ).split( "." ).sort();
+
+			// Unbind all events (on this namespace, if provided) for the element
+			if ( !type ) {
+				for ( type in events ) {
+					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
+				}
+				continue;
+			}
+
+			special = jQuery.event.special[ type ] || {};
+			type = ( selector ? special.delegateType : special.bindType ) || type;
+			handlers = events[ type ] || [];
+			tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
+
+			// Remove matching events
+			origCount = j = handlers.length;
+			while ( j-- ) {
+				handleObj = handlers[ j ];
+
+				if ( ( mappedTypes || origType === handleObj.origType ) &&
+					( !handler || handler.guid === handleObj.guid ) &&
+					( !tmp || tmp.test( handleObj.namespace ) ) &&
+					( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
+					handlers.splice( j, 1 );
+
+					if ( handleObj.selector ) {
+						handlers.delegateCount--;
+					}
+					if ( special.remove ) {
+						special.remove.call( elem, handleObj );
+					}
+				}
+			}
+
+			// Remove generic event handler if we removed something and no more handlers exist
+			// (avoids potential for endless recursion during removal of special event handlers)
+			if ( origCount && !handlers.length ) {
+				if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
+					jQuery.removeEvent( elem, type, elemData.handle );
+				}
+
+				delete events[ type ];
+			}
+		}
+
+		// Remove the expando if it's no longer used
+		if ( jQuery.isEmptyObject( events ) ) {
+			delete elemData.handle;
+
+			// removeData also checks for emptiness and clears the expando if empty
+			// so use it instead of delete
+			jQuery._removeData( elem, "events" );
+		}
+	},
+
+	trigger: function( event, data, elem, onlyHandlers ) {
+		var handle, ontype, cur,
+			bubbleType, special, tmp, i,
+			eventPath = [ elem || document ],
+			type = core_hasOwn.call( event, "type" ) ? event.type : event,
+			namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
+
+		cur = tmp = elem = elem || document;
+
+		// Don't do events on text and comment nodes
+		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+			return;
+		}
+
+		// focus/blur morphs to focusin/out; ensure we're not firing them right now
+		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
+			return;
+		}
+
+		if ( type.indexOf(".") >= 0 ) {
+			// Namespaced trigger; create a regexp to match event type in handle()
+			namespaces = type.split(".");
+			type = namespaces.shift();
+			namespaces.sort();
+		}
+		ontype = type.indexOf(":") < 0 && "on" + type;
+
+		// Caller can pass in a jQuery.Event object, Object, or just an event type string
+		event = event[ jQuery.expando ] ?
+			event :
+			new jQuery.Event( type, typeof event === "object" && event );
+
+		// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
+		event.isTrigger = onlyHandlers ? 2 : 3;
+		event.namespace = namespaces.join(".");
+		event.namespace_re = event.namespace ?
+			new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
+			null;
+
+		// Clean up the event in case it is being reused
+		event.result = undefined;
+		if ( !event.target ) {
+			event.target = elem;
+		}
+
+		// Clone any incoming data and prepend the event, creating the handler arg list
+		data = data == null ?
+			[ event ] :
+			jQuery.makeArray( data, [ event ] );
+
+		// Allow special events to draw outside the lines
+		special = jQuery.event.special[ type ] || {};
+		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
+			return;
+		}
+
+		// Determine event propagation path in advance, per W3C events spec (#9951)
+		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
+		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
+
+			bubbleType = special.delegateType || type;
+			if ( !rfocusMorph.test( bubbleType + type ) ) {
+				cur = cur.parentNode;
+			}
+			for ( ; cur; cur = cur.parentNode ) {
+				eventPath.push( cur );
+				tmp = cur;
+			}
+
+			// Only add window if we got to document (e.g., not plain obj or detached DOM)
+			if ( tmp === (elem.ownerDocument || document) ) {
+				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
+			}
+		}
+
+		// Fire handlers on the event path
+		i = 0;
+		while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
+
+			event.type = i > 1 ?
+				bubbleType :
+				special.bindType || type;
+
+			// jQuery handler
+			handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
+			if ( handle ) {
+				handle.apply( cur, data );
+			}
+
+			// Native handler
+			handle = ontype && cur[ ontype ];
+			if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
+				event.preventDefault();
+			}
+		}
+		event.type = type;
+
+		// If nobody prevented the default action, do it now
+		if ( !onlyHandlers && !event.isDefaultPrevented() ) {
+
+			if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
+				jQuery.acceptData( elem ) ) {
+
+				// Call a native DOM method on the target with the same name name as the event.
+				// Can't use an .isFunction() check here because IE6/7 fails that test.
+				// Don't do default actions on window, that's where global variables be (#6170)
+				if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
+
+					// Don't re-trigger an onFOO event when we call its FOO() method
+					tmp = elem[ ontype ];
+
+					if ( tmp ) {
+						elem[ ontype ] = null;
+					}
+
+					// Prevent re-triggering of the same event, since we already bubbled it above
+					jQuery.event.triggered = type;
+					try {
+						elem[ type ]();
+					} catch ( e ) {
+						// IE<9 dies on focus/blur to hidden element (#1486,#12518)
+						// only reproducible on winXP IE8 native, not IE9 in IE8 mode
+					}
+					jQuery.event.triggered = undefined;
+
+					if ( tmp ) {
+						elem[ ontype ] = tmp;
+					}
+				}
+			}
+		}
+
+		return event.result;
+	},
+
+	dispatch: function( event ) {
+
+		// Make a writable jQuery.Event from the native event object
+		event = jQuery.event.fix( event );
+
+		var i, ret, handleObj, matched, j,
+			handlerQueue = [],
+			args = core_slice.call( arguments ),
+			handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
+			special = jQuery.event.special[ event.type ] || {};
+
+		// Use the fix-ed jQuery.Event rather than the (read-only) native event
+		args[0] = event;
+		event.delegateTarget = this;
+
+		// Call the preDispatch hook for the mapped type, and let it bail if desired
+		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
+			return;
+		}
+
+		// Determine handlers
+		handlerQueue = jQuery.event.handlers.call( this, event, handlers );
+
+		// Run delegates first; they may want to stop propagation beneath us
+		i = 0;
+		while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
+			event.currentTarget = matched.elem;
+
+			j = 0;
+			while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
+
+				// Triggered event must either 1) have no namespace, or
+				// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
+				if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
+
+					event.handleObj = handleObj;
+					event.data = handleObj.data;
+
+					ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
+							.apply( matched.elem, args );
+
+					if ( ret !== undefined ) {
+						if ( (event.result = ret) === false ) {
+							event.preventDefault();
+							event.stopPropagation();
+						}
+					}
+				}
+			}
+		}
+
+		// Call the postDispatch hook for the mapped type
+		if ( special.postDispatch ) {
+			special.postDispatch.call( this, event );
+		}
+
+		return event.result;
+	},
+
+	handlers: function( event, handlers ) {
+		var sel, handleObj, matches, i,
+			handlerQueue = [],
+			delegateCount = handlers.delegateCount,
+			cur = event.target;
+
+		// Find delegate handlers
+		// Black-hole SVG <use> instance trees (#13180)
+		// Avoid non-left-click bubbling in Firefox (#3861)
+		if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
+
+			/* jshint eqeqeq: false */
+			for ( ; cur != this; cur = cur.parentNode || this ) {
+				/* jshint eqeqeq: true */
+
+				// Don't check non-elements (#13208)
+				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
+				if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
+					matches = [];
+					for ( i = 0; i < delegateCount; i++ ) {
+						handleObj = handlers[ i ];
+
+						// Don't conflict with Object.prototype properties (#13203)
+						sel = handleObj.selector + " ";
+
+						if ( matches[ sel ] === undefined ) {
+							matches[ sel ] = handleObj.needsContext ?
+								jQuery( sel, this ).index( cur ) >= 0 :
+								jQuery.find( sel, this, null, [ cur ] ).length;
+						}
+						if ( matches[ sel ] ) {
+							matches.push( handleObj );
+						}
+					}
+					if ( matches.length ) {
+						handlerQueue.push({ elem: cur, handlers: matches });
+					}
+				}
+			}
+		}
+
+		// Add the remaining (directly-bound) handlers
+		if ( delegateCount < handlers.length ) {
+			handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
+		}
+
+		return handlerQueue;
+	},
+
+	fix: function( event ) {
+		if ( event[ jQuery.expando ] ) {
+			return event;
+		}
+
+		// Create a writable copy of the event object and normalize some properties
+		var i, prop, copy,
+			type = event.type,
+			originalEvent = event,
+			fixHook = this.fixHooks[ type ];
+
+		if ( !fixHook ) {
+			this.fixHooks[ type ] = fixHook =
+				rmouseEvent.test( type ) ? this.mouseHooks :
+				rkeyEvent.test( type ) ? this.keyHooks :
+				{};
+		}
+		copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
+
+		event = new jQuery.Event( originalEvent );
+
+		i = copy.length;
+		while ( i-- ) {
+			prop = copy[ i ];
+			event[ prop ] = originalEvent[ prop ];
+		}
+
+		// Support: IE<9
+		// Fix target property (#1925)
+		if ( !event.target ) {
+			event.target = originalEvent.srcElement || document;
+		}
+
+		// Support: Chrome 23+, Safari?
+		// Target should not be a text node (#504, #13143)
+		if ( event.target.nodeType === 3 ) {
+			event.target = event.target.parentNode;
+		}
+
+		// Support: IE<9
+		// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
+		event.metaKey = !!event.metaKey;
+
+		return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
+	},
+
+	// Includes some event props shared by KeyEvent and MouseEvent
+	props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
+
+	fixHooks: {},
+
+	keyHooks: {
+		props: "char charCode key keyCode".split(" "),
+		filter: function( event, original ) {
+
+			// Add which for key events
+			if ( event.which == null ) {
+				event.which = original.charCode != null ? original.charCode : original.keyCode;
+			}
+
+			return event;
+		}
+	},
+
+	mouseHooks: {
+		props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
+		filter: function( event, original ) {
+			var body, eventDoc, doc,
+				button = original.button,
+				fromElement = original.fromElement;
+
+			// Calculate pageX/Y if missing and clientX/Y available
+			if ( event.pageX == null && original.clientX != null ) {
+				eventDoc = event.target.ownerDocument || document;
+				doc = eventDoc.documentElement;
+				body = eventDoc.body;
+
+				event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
+				event.pageY = original.clientY + ( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) - ( doc && doc.clientTop  || body && body.clientTop  || 0 );
+			}
+
+			// Add relatedTarget, if necessary
+			if ( !event.relatedTarget && fromElement ) {
+				event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
+			}
+
+			// Add which for click: 1 === left; 2 === middle; 3 === right
+			// Note: button is not normalized, so don't use it
+			if ( !event.which && button !== undefined ) {
+				event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
+			}
+
+			return event;
+		}
+	},
+
+	special: {
+		load: {
+			// Prevent triggered image.load events from bubbling to window.load
+			noBubble: true
+		},
+		focus: {
+			// Fire native event if possible so blur/focus sequence is correct
+			trigger: function() {
+				if ( this !== safeActiveElement() && this.focus ) {
+					try {
+						this.focus();
+						return false;
+					} catch ( e ) {
+						// Support: IE<9
+						// If we error on focus to hidden element (#1486, #12518),
+						// let .trigger() run the handlers
+					}
+				}
+			},
+			delegateType: "focusin"
+		},
+		blur: {
+			trigger: function() {
+				if ( this === safeActiveElement() && this.blur ) {
+					this.blur();
+					return false;
+				}
+			},
+			delegateType: "focusout"
+		},
+		click: {
+			// For checkbox, fire native event so checked state will be right
+			trigger: function() {
+				if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
+					this.click();
+					return false;
+				}
+			},
+
+			// For cross-browser consistency, don't fire native .click() on links
+			_default: function( event ) {
+				return jQuery.nodeName( event.target, "a" );
+			}
+		},
+
+		beforeunload: {
+			postDispatch: function( event ) {
+
+				// Even when returnValue equals to undefined Firefox will still show alert
+				if ( event.result !== undefined ) {
+					event.originalEvent.returnValue = event.result;
+				}
+			}
+		}
+	},
+
+	simulate: function( type, elem, event, bubble ) {
+		// Piggyback on a donor event to simulate a different one.
+		// Fake originalEvent to avoid donor's stopPropagation, but if the
+		// simulated event prevents default then we do the same on the donor.
+		var e = jQuery.extend(
+			new jQuery.Event(),
+			event,
+			{
+				type: type,
+				isSimulated: true,
+				originalEvent: {}
+			}
+		);
+		if ( bubble ) {
+			jQuery.event.trigger( e, null, elem );
+		} else {
+			jQuery.event.dispatch.call( elem, e );
+		}
+		if ( e.isDefaultPrevented() ) {
+			event.preventDefault();
+		}
+	}
+};
+
+jQuery.removeEvent = document.removeEventListener ?
+	function( elem, type, handle ) {
+		if ( elem.removeEventListener ) {
+			elem.removeEventListener( type, handle, false );
+		}
+	} :
+	function( elem, type, handle ) {
+		var name = "on" + type;
+
+		if ( elem.detachEvent ) {
+
+			// #8545, #7054, preventing memory leaks for custom events in IE6-8
+			// detachEvent needed property on element, by name of that event, to properly expose it to GC
+			if ( typeof elem[ name ] === core_strundefined ) {
+				elem[ name ] = null;
+			}
+
+			elem.detachEvent( name, handle );
+		}
+	};
+
+jQuery.Event = function( src, props ) {
+	// Allow instantiation without the 'new' keyword
+	if ( !(this instanceof jQuery.Event) ) {
+		return new jQuery.Event( src, props );
+	}
+
+	// Event object
+	if ( src && src.type ) {
+		this.originalEvent = src;
+		this.type = src.type;
+
+		// Events bubbling up the document may have been marked as prevented
+		// by a handler lower down the tree; reflect the correct value.
+		this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
+			src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
+
+	// Event type
+	} else {
+		this.type = src;
+	}
+
+	// Put explicitly provided properties onto the event object
+	if ( props ) {
+		jQuery.extend( this, props );
+	}
+
+	// Create a timestamp if incoming event doesn't have one
+	this.timeStamp = src && src.timeStamp || jQuery.now();
+
+	// Mark it as fixed
+	this[ jQuery.expando ] = true;
+};
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+	isDefaultPrevented: returnFalse,
+	isPropagationStopped: returnFalse,
+	isImmediatePropagationStopped: returnFalse,
+
+	preventDefault: function() {
+		var e = this.originalEvent;
+
+		this.isDefaultPrevented = returnTrue;
+		if ( !e ) {
+			return;
+		}
+
+		// If preventDefault exists, run it on the original event
+		if ( e.preventDefault ) {
+			e.preventDefault();
+
+		// Support: IE
+		// Otherwise set the returnValue property of the original event to false
+		} else {
+			e.returnValue = false;
+		}
+	},
+	stopPropagation: function() {
+		var e = this.originalEvent;
+
+		this.isPropagationStopped = returnTrue;
+		if ( !e ) {
+			return;
+		}
+		// If stopPropagation exists, run it on the original event
+		if ( e.stopPropagation ) {
+			e.stopPropagation();
+		}
+
+		// Support: IE
+		// Set the cancelBubble property of the original event to true
+		e.cancelBubble = true;
+	},
+	stopImmediatePropagation: function() {
+		this.isImmediatePropagationStopped = returnTrue;
+		this.stopPropagation();
+	}
+};
+
+// Create mouseenter/leave events using mouseover/out and event-time checks
+jQuery.each({
+	mouseenter: "mouseover",
+	mouseleave: "mouseout"
+}, function( orig, fix ) {
+	jQuery.event.special[ orig ] = {
+		delegateType: fix,
+		bindType: fix,
+
+		handle: function( event ) {
+			var ret,
+				target = this,
+				related = event.relatedTarget,
+				handleObj = event.handleObj;
+
+			// For mousenter/leave call the handler if related is outside the target.
+			// NB: No relatedTarget if the mouse left/entered the browser window
+			if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
+				event.type = handleObj.origType;
+				ret = handleObj.handler.apply( this, arguments );
+				event.type = fix;
+			}
+			return ret;
+		}
+	};
+});
+
+// IE submit delegation
+if ( !jQuery.support.submitBubbles ) {
+
+	jQuery.event.special.submit = {
+		setup: function() {
+			// Only need this for delegated form submit events
+			if ( jQuery.nodeName( this, "form" ) ) {
+				return false;
+			}
+
+			// Lazy-add a submit handler when a descendant form may potentially be submitted
+			jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
+				// Node name check avoids a VML-related crash in IE (#9807)
+				var elem = e.target,
+					form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
+				if ( form && !jQuery._data( form, "submitBubbles" ) ) {
+					jQuery.event.add( form, "submit._submit", function( event ) {
+						event._submit_bubble = true;
+					});
+					jQuery._data( form, "submitBubbles", true );
+				}
+			});
+			// return undefined since we don't need an event listener
+		},
+
+		postDispatch: function( event ) {
+			// If form was submitted by the user, bubble the event up the tree
+			if ( event._submit_bubble ) {
+				delete event._submit_bubble;
+				if ( this.parentNode && !event.isTrigger ) {
+					jQuery.event.simulate( "submit", this.parentNode, event, true );
+				}
+			}
+		},
+
+		teardown: function() {
+			// Only need this for delegated form submit events
+			if ( jQuery.nodeName( this, "form" ) ) {
+				return false;
+			}
+
+			// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
+			jQuery.event.remove( this, "._submit" );
+		}
+	};
+}
+
+// IE change delegation and checkbox/radio fix
+if ( !jQuery.support.changeBubbles ) {
+
+	jQuery.event.special.change = {
+
+		setup: function() {
+
+			if ( rformElems.test( this.nodeName ) ) {
+				// IE doesn't fire change on a check/radio until blur; trigger it on click
+				// after a propertychange. Eat the blur-change in special.change.handle.
+				// This still fires onchange a second time for check/radio after blur.
+				if ( this.type === "checkbox" || this.type === "radio" ) {
+					jQuery.event.add( this, "propertychange._change", function( event ) {
+						if ( event.originalEvent.propertyName === "checked" ) {
+							this._just_changed = true;
+						}
+					});
+					jQuery.event.add( this, "click._change", function( event ) {
+						if ( this._just_changed && !event.isTrigger ) {
+							this._just_changed = false;
+						}
+						// Allow triggered, simulated change events (#11500)
+						jQuery.event.simulate( "change", this, event, true );
+					});
+				}
+				return false;
+			}
+			// Delegated event; lazy-add a change handler on descendant inputs
+			jQuery.event.add( this, "beforeactivate._change", function( e ) {
+				var elem = e.target;
+
+				if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
+					jQuery.event.add( elem, "change._change", function( event ) {
+						if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
+							jQuery.event.simulate( "change", this.parentNode, event, true );
+						}
+					});
+					jQuery._data( elem, "changeBubbles", true );
+				}
+			});
+		},
+
+		handle: function( event ) {
+			var elem = event.target;
+
+			// Swallow native change events from checkbox/radio, we already triggered them above
+			if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
+				return event.handleObj.handler.apply( this, arguments );
+			}
+		},
+
+		teardown: function() {
+			jQuery.event.remove( this, "._change" );
+
+			return !rformElems.test( this.nodeName );
+		}
+	};
+}
+
+// Create "bubbling" focus and blur events
+if ( !jQuery.support.focusinBubbles ) {
+	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+		// Attach a single capturing handler while someone wants focusin/focusout
+		var attaches = 0,
+			handler = function( event ) {
+				jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
+			};
+
+		jQuery.event.special[ fix ] = {
+			setup: function() {
+				if ( attaches++ === 0 ) {
+					document.addEventListener( orig, handler, true );
+				}
+			},
+			teardown: function() {
+				if ( --attaches === 0 ) {
+					document.removeEventListener( orig, handler, true );
+				}
+			}
+		};
+	});
+}
+
+jQuery.fn.extend({
+
+	on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
+		var type, origFn;
+
+		// Types can be a map of types/handlers
+		if ( typeof types === "object" ) {
+			// ( types-Object, selector, data )
+			if ( typeof selector !== "string" ) {
+				// ( types-Object, data )
+				data = data || selector;
+				selector = undefined;
+			}
+			for ( type in types ) {
+				this.on( type, selector, data, types[ type ], one );
+			}
+			return this;
+		}
+
+		if ( data == null && fn == null ) {
+			// ( types, fn )
+			fn = selector;
+			data = selector = undefined;
+		} else if ( fn == null ) {
+			if ( typeof selector === "string" ) {
+				// ( types, selector, fn )
+				fn = data;
+				data = undefined;
+			} else {
+				// ( types, data, fn )
+				fn = data;
+				data = selector;
+				selector = undefined;
+			}
+		}
+		if ( fn === false ) {
+			fn = returnFalse;
+		} else if ( !fn ) {
+			return this;
+		}
+
+		if ( one === 1 ) {
+			origFn = fn;
+			fn = function( event ) {
+				// Can use an empty set, since event contains the info
+				jQuery().off( event );
+				return origFn.apply( this, arguments );
+			};
+			// Use same guid so caller can remove using origFn
+			fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
+		}
+		return this.each( function() {
+			jQuery.event.add( this, types, fn, data, selector );
+		});
+	},
+	one: function( types, selector, data, fn ) {
+		return this.on( types, selector, data, fn, 1 );
+	},
+	off: function( types, selector, fn ) {
+		var handleObj, type;
+		if ( types && types.preventDefault && types.handleObj ) {
+			// ( event )  dispatched jQuery.Event
+			handleObj = types.handleObj;
+			jQuery( types.delegateTarget ).off(
+				handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
+				handleObj.selector,
+				handleObj.handler
+			);
+			return this;
+		}
+		if ( typeof types === "object" ) {
+			// ( types-object [, selector] )
+			for ( type in types ) {
+				this.off( type, selector, types[ type ] );
+			}
+			return this;
+		}
+		if ( selector === false || typeof selector === "function" ) {
+			// ( types [, fn] )
+			fn = selector;
+			selector = undefined;
+		}
+		if ( fn === false ) {
+			fn = returnFalse;
+		}
+		return this.each(function() {
+			jQuery.event.remove( this, types, fn, selector );
+		});
+	},
+
+	trigger: function( type, data ) {
+		return this.each(function() {
+			jQuery.event.trigger( type, data, this );
+		});
+	},
+	triggerHandler: function( type, data ) {
+		var elem = this[0];
+		if ( elem ) {
+			return jQuery.event.trigger( type, data, elem, true );
+		}
+	}
+});
+var isSimple = /^.[^:#\[\.,]*$/,
+	rparentsprev = /^(?:parents|prev(?:Until|All))/,
+	rneedsContext = jQuery.expr.match.needsContext,
+	// methods guaranteed to produce a unique set when starting from a unique set
+	guaranteedUnique = {
+		children: true,
+		contents: true,
+		next: true,
+		prev: true
+	};
+
+jQuery.fn.extend({
+	find: function( selector ) {
+		var i,
+			ret = [],
+			self = this,
+			len = self.length;
+
+		if ( typeof selector !== "string" ) {
+			return this.pushStack( jQuery( selector ).filter(function() {
+				for ( i = 0; i < len; i++ ) {
+					if ( jQuery.contains( self[ i ], this ) ) {
+						return true;
+					}
+				}
+			}) );
+		}
+
+		for ( i = 0; i < len; i++ ) {
+			jQuery.find( selector, self[ i ], ret );
+		}
+
+		// Needed because $( selector, context ) becomes $( context ).find( selector )
+		ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
+		ret.selector = this.selector ? this.selector + " " + selector : selector;
+		return ret;
+	},
+
+	has: function( target ) {
+		var i,
+			targets = jQuery( target, this ),
+			len = targets.length;
+
+		return this.filter(function() {
+			for ( i = 0; i < len; i++ ) {
+				if ( jQuery.contains( this, targets[i] ) ) {
+					return true;
+				}
+			}
+		});
+	},
+
+	not: function( selector ) {
+		return this.pushStack( winnow(this, selector || [], true) );
+	},
+
+	filter: function( selector ) {
+		return this.pushStack( winnow(this, selector || [], false) );
+	},
+
+	is: function( selector ) {
+		return !!winnow(
+			this,
+
+			// If this is a positional/relative selector, check membership in the returned set
+			// so $("p:first").is("p:last") won't return true for a doc with two "p".
+			typeof selector === "string" && rneedsContext.test( selector ) ?
+				jQuery( selector ) :
+				selector || [],
+			false
+		).length;
+	},
+
+	closest: function( selectors, context ) {
+		var cur,
+			i = 0,
+			l = this.length,
+			ret = [],
+			pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
+				jQuery( selectors, context || this.context ) :
+				0;
+
+		for ( ; i < l; i++ ) {
+			for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
+				// Always skip document fragments
+				if ( cur.nodeType < 11 && (pos ?
+					pos.index(cur) > -1 :
+
+					// Don't pass non-elements to Sizzle
+					cur.nodeType === 1 &&
+						jQuery.find.matchesSelector(cur, selectors)) ) {
+
+					cur = ret.push( cur );
+					break;
+				}
+			}
+		}
+
+		return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
+	},
+
+	// Determine the position of an element within
+	// the matched set of elements
+	index: function( elem ) {
+
+		// No argument, return index in parent
+		if ( !elem ) {
+			return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
+		}
+
+		// index in selector
+		if ( typeof elem === "string" ) {
+			return jQuery.inArray( this[0], jQuery( elem ) );
+		}
+
+		// Locate the position of the desired element
+		return jQuery.inArray(
+			// If it receives a jQuery object, the first element is used
+			elem.jquery ? elem[0] : elem, this );
+	},
+
+	add: function( selector, context ) {
+		var set = typeof selector === "string" ?
+				jQuery( selector, context ) :
+				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
+			all = jQuery.merge( this.get(), set );
+
+		return this.pushStack( jQuery.unique(all) );
+	},
+
+	addBack: function( selector ) {
+		return this.add( selector == null ?
+			this.prevObject : this.prevObject.filter(selector)
+		);
+	}
+});
+
+function sibling( cur, dir ) {
+	do {
+		cur = cur[ dir ];
+	} while ( cur && cur.nodeType !== 1 );
+
+	return cur;
+}
+
+jQuery.each({
+	parent: function( elem ) {
+		var parent = elem.parentNode;
+		return parent && parent.nodeType !== 11 ? parent : null;
+	},
+	parents: function( elem ) {
+		return jQuery.dir( elem, "parentNode" );
+	},
+	parentsUntil: function( elem, i, until ) {
+		return jQuery.dir( elem, "parentNode", until );
+	},
+	next: function( elem ) {
+		return sibling( elem, "nextSibling" );
+	},
+	prev: function( elem ) {
+		return sibling( elem, "previousSibling" );
+	},
+	nextAll: function( elem ) {
+		return jQuery.dir( elem, "nextSibling" );
+	},
+	prevAll: function( elem ) {
+		return jQuery.dir( elem, "previousSibling" );
+	},
+	nextUntil: function( elem, i, until ) {
+		return jQuery.dir( elem, "nextSibling", until );
+	},
+	prevUntil: function( elem, i, until ) {
+		return jQuery.dir( elem, "previousSibling", until );
+	},
+	siblings: function( elem ) {
+		return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
+	},
+	children: function( elem ) {
+		return jQuery.sibling( elem.firstChild );
+	},
+	contents: function( elem ) {
+		return jQuery.nodeName( elem, "iframe" ) ?
+			elem.contentDocument || elem.contentWindow.document :
+			jQuery.merge( [], elem.childNodes );
+	}
+}, function( name, fn ) {
+	jQuery.fn[ name ] = function( until, selector ) {
+		var ret = jQuery.map( this, fn, until );
+
+		if ( name.slice( -5 ) !== "Until" ) {
+			selector = until;
+		}
+
+		if ( selector && typeof selector === "string" ) {
+			ret = jQuery.filter( selector, ret );
+		}
+
+		if ( this.length > 1 ) {
+			// Remove duplicates
+			if ( !guaranteedUnique[ name ] ) {
+				ret = jQuery.unique( ret );
+			}
+
+			// Reverse order for parents* and prev-derivatives
+			if ( rparentsprev.test( name ) ) {
+				ret = ret.reverse();
+			}
+		}
+
+		return this.pushStack( ret );
+	};
+});
+
+jQuery.extend({
+	filter: function( expr, elems, not ) {
+		var elem = elems[ 0 ];
+
+		if ( not ) {
+			expr = ":not(" + expr + ")";
+		}
+
+		return elems.length === 1 && elem.nodeType === 1 ?
+			jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
+			jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
+				return elem.nodeType === 1;
+			}));
+	},
+
+	dir: function( elem, dir, until ) {
+		var matched = [],
+			cur = elem[ dir ];
+
+		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
+			if ( cur.nodeType === 1 ) {
+				matched.push( cur );
+			}
+			cur = cur[dir];
+		}
+		return matched;
+	},
+
+	sibling: function( n, elem ) {
+		var r = [];
+
+		for ( ; n; n = n.nextSibling ) {
+			if ( n.nodeType === 1 && n !== elem ) {
+				r.push( n );
+			}
+		}
+
+		return r;
+	}
+});
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, not ) {
+	if ( jQuery.isFunction( qualifier ) ) {
+		return jQuery.grep( elements, function( elem, i ) {
+			/* jshint -W018 */
+			return !!qualifier.call( elem, i, elem ) !== not;
+		});
+
+	}
+
+	if ( qualifier.nodeType ) {
+		return jQuery.grep( elements, function( elem ) {
+			return ( elem === qualifier ) !== not;
+		});
+
+	}
+
+	if ( typeof qualifier === "string" ) {
+		if ( isSimple.test( qualifier ) ) {
+			return jQuery.filter( qualifier, elements, not );
+		}
+
+		qualifier = jQuery.filter( qualifier, elements );
+	}
+
+	return jQuery.grep( elements, function( elem ) {
+		return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
+	});
+}
+function createSafeFragment( document ) {
+	var list = nodeNames.split( "|" ),
+		safeFrag = document.createDocumentFragment();
+
+	if ( safeFrag.createElement ) {
+		while ( list.length ) {
+			safeFrag.createElement(
+				list.pop()
+			);
+		}
+	}
+	return safeFrag;
+}
+
+var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
+		"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
+	rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
+	rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
+	rleadingWhitespace = /^\s+/,
+	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
+	rtagName = /<([\w:]+)/,
+	rtbody = /<tbody/i,
+	rhtml = /<|&#?\w+;/,
+	rnoInnerhtml = /<(?:script|style|link)/i,
+	manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
+	// checked="checked" or checked
+	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+	rscriptType = /^$|\/(?:java|ecma)script/i,
+	rscriptTypeMasked = /^true\/(.*)/,
+	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
+
+	// We have to close these tags to support XHTML (#13200)
+	wrapMap = {
+		option: [ 1, "<select multiple='multiple'>", "</select>" ],
+		legend: [ 1, "<fieldset>", "</fieldset>" ],
+		area: [ 1, "<map>", "</map>" ],
+		param: [ 1, "<object>", "</object>" ],
+		thead: [ 1, "<table>", "</table>" ],
+		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
+		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+
+		// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
+		// unless wrapped in a div with non-breaking characters in front of it.
+		_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>"  ]
+	},
+	safeFragment = createSafeFragment( document ),
+	fragmentDiv = safeFragment.appendChild( document.createElement("div") );
+
+wrapMap.optgroup = wrapMap.option;
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+jQuery.fn.extend({
+	text: function( value ) {
+		return jQuery.access( this, function( value ) {
+			return value === undefined ?
+				jQuery.text( this ) :
+				this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
+		}, null, value, arguments.length );
+	},
+
+	append: function() {
+		return this.domManip( arguments, function( elem ) {
+			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+				var target = manipulationTarget( this, elem );
+				target.appendChild( elem );
+			}
+		});
+	},
+
+	prepend: function() {
+		return this.domManip( arguments, function( elem ) {
+			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+				var target = manipulationTarget( this, elem );
+				target.insertBefore( elem, target.firstChild );
+			}
+		});
+	},
+
+	before: function() {
+		return this.domManip( arguments, function( elem ) {
+			if ( this.parentNode ) {
+				this.parentNode.insertBefore( elem, this );
+			}
+		});
+	},
+
+	after: function() {
+		return this.domManip( arguments, function( elem ) {
+			if ( this.parentNode ) {
+				this.parentNode.insertBefore( elem, this.nextSibling );
+			}
+		});
+	},
+
+	// keepData is for internal use only--do not document
+	remove: function( selector, keepData ) {
+		var elem,
+			elems = selector ? jQuery.filter( selector, this ) : this,
+			i = 0;
+
+		for ( ; (elem = elems[i]) != null; i++ ) {
+
+			if ( !keepData && elem.nodeType === 1 ) {
+				jQuery.cleanData( getAll( elem ) );
+			}
+
+			if ( elem.parentNode ) {
+				if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
+					setGlobalEval( getAll( elem, "script" ) );
+				}
+				elem.parentNode.removeChild( elem );
+			}
+		}
+
+		return this;
+	},
+
+	empty: function() {
+		var elem,
+			i = 0;
+
+		for ( ; (elem = this[i]) != null; i++ ) {
+			// Remove element nodes and prevent memory leaks
+			if ( elem.nodeType === 1 ) {
+				jQuery.cleanData( getAll( elem, false ) );
+			}
+
+			// Remove any remaining nodes
+			while ( elem.firstChild ) {
+				elem.removeChild( elem.firstChild );
+			}
+
+			// If this is a select, ensure that it displays empty (#12336)
+			// Support: IE<9
+			if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
+				elem.options.length = 0;
+			}
+		}
+
+		return this;
+	},
+
+	clone: function( dataAndEvents, deepDataAndEvents ) {
+		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
+		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
+
+		return this.map( function () {
+			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
+		});
+	},
+
+	html: function( value ) {
+		return jQuery.access( this, function( value ) {
+			var elem = this[0] || {},
+				i = 0,
+				l = this.length;
+
+			if ( value === undefined ) {
+				return elem.nodeType === 1 ?
+					elem.innerHTML.replace( rinlinejQuery, "" ) :
+					undefined;
+			}
+
+			// See if we can take a shortcut and just use innerHTML
+			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
+				( jQuery.support.htmlSerialize || !rnoshimcache.test( value )  ) &&
+				( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
+				!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
+
+				value = value.replace( rxhtmlTag, "<$1></$2>" );
+
+				try {
+					for (; i < l; i++ ) {
+						// Remove element nodes and prevent memory leaks
+						elem = this[i] || {};
+						if ( elem.nodeType === 1 ) {
+							jQuery.cleanData( getAll( elem, false ) );
+							elem.innerHTML = value;
+						}
+					}
+
+					elem = 0;
+
+				// If using innerHTML throws an exception, use the fallback method
+				} catch(e) {}
+			}
+
+			if ( elem ) {
+				this.empty().append( value );
+			}
+		}, null, value, arguments.length );
+	},
+
+	replaceWith: function() {
+		var
+			// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
+			args = jQuery.map( this, function( elem ) {
+				return [ elem.nextSibling, elem.parentNode ];
+			}),
+			i = 0;
+
+		// Make the changes, replacing each context element with the new content
+		this.domManip( arguments, function( elem ) {
+			var next = args[ i++ ],
+				parent = args[ i++ ];
+
+			if ( parent ) {
+				// Don't use the snapshot next if it has moved (#13810)
+				if ( next && next.parentNode !== parent ) {
+					next = this.nextSibling;
+				}
+				jQuery( this ).remove();
+				parent.insertBefore( elem, next );
+			}
+		// Allow new content to include elements from the context set
+		}, true );
+
+		// Force removal if there was no new content (e.g., from empty arguments)
+		return i ? this : this.remove();
+	},
+
+	detach: function( selector ) {
+		return this.remove( selector, true );
+	},
+
+	domManip: function( args, callback, allowIntersection ) {
+
+		// Flatten any nested arrays
+		args = core_concat.apply( [], args );
+
+		var first, node, hasScripts,
+			scripts, doc, fragment,
+			i = 0,
+			l = this.length,
+			set = this,
+			iNoClone = l - 1,
+			value = args[0],
+			isFunction = jQuery.isFunction( value );
+
+		// We can't cloneNode fragments that contain checked, in WebKit
+		if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
+			return this.each(function( index ) {
+				var self = set.eq( index );
+				if ( isFunction ) {
+					args[0] = value.call( this, index, self.html() );
+				}
+				self.domManip( args, callback, allowIntersection );
+			});
+		}
+
+		if ( l ) {
+			fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
+			first = fragment.firstChild;
+
+			if ( fragment.childNodes.length === 1 ) {
+				fragment = first;
+			}
+
+			if ( first ) {
+				scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
+				hasScripts = scripts.length;
+
+				// Use the original fragment for the last item instead of the first because it can end up
+				// being emptied incorrectly in certain situations (#8070).
+				for ( ; i < l; i++ ) {
+					node = fragment;
+
+					if ( i !== iNoClone ) {
+						node = jQuery.clone( node, true, true );
+
+						// Keep references to cloned scripts for later restoration
+						if ( hasScripts ) {
+							jQuery.merge( scripts, getAll( node, "script" ) );
+						}
+					}
+
+					callback.call( this[i], node, i );
+				}
+
+				if ( hasScripts ) {
+					doc = scripts[ scripts.length - 1 ].ownerDocument;
+
+					// Reenable scripts
+					jQuery.map( scripts, restoreScript );
+
+					// Evaluate executable scripts on first document insertion
+					for ( i = 0; i < hasScripts; i++ ) {
+						node = scripts[ i ];
+						if ( rscriptType.test( node.type || "" ) &&
+							!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
+
+							if ( node.src ) {
+								// Hope ajax is available...
+								jQuery._evalUrl( node.src );
+							} else {
+								jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
+							}
+						}
+					}
+				}
+
+				// Fix #11809: Avoid leaking memory
+				fragment = first = null;
+			}
+		}
+
+		return this;
+	}
+});
+
+// Support: IE<8
+// Manipulating tables requires a tbody
+function manipulationTarget( elem, content ) {
+	return jQuery.nodeName( elem, "table" ) &&
+		jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
+
+		elem.getElementsByTagName("tbody")[0] ||
+			elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
+		elem;
+}
+
+// Replace/restore the type attribute of script elements for safe DOM manipulation
+function disableScript( elem ) {
+	elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
+	return elem;
+}
+function restoreScript( elem ) {
+	var match = rscriptTypeMasked.exec( elem.type );
+	if ( match ) {
+		elem.type = match[1];
+	} else {
+		elem.removeAttribute("type");
+	}
+	return elem;
+}
+
+// Mark scripts as having already been evaluated
+function setGlobalEval( elems, refElements ) {
+	var elem,
+		i = 0;
+	for ( ; (elem = elems[i]) != null; i++ ) {
+		jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
+	}
+}
+
+function cloneCopyEvent( src, dest ) {
+
+	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
+		return;
+	}
+
+	var type, i, l,
+		oldData = jQuery._data( src ),
+		curData = jQuery._data( dest, oldData ),
+		events = oldData.events;
+
+	if ( events ) {
+		delete curData.handle;
+		curData.events = {};
+
+		for ( type in events ) {
+			for ( i = 0, l = events[ type ].length; i < l; i++ ) {
+				jQuery.event.add( dest, type, events[ type ][ i ] );
+			}
+		}
+	}
+
+	// make the cloned public data object a copy from the original
+	if ( curData.data ) {
+		curData.data = jQuery.extend( {}, curData.data );
+	}
+}
+
+function fixCloneNodeIssues( src, dest ) {
+	var nodeName, e, data;
+
+	// We do not need to do anything for non-Elements
+	if ( dest.nodeType !== 1 ) {
+		return;
+	}
+
+	nodeName = dest.nodeName.toLowerCase();
+
+	// IE6-8 copies events bound via attachEvent when using cloneNode.
+	if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
+		data = jQuery._data( dest );
+
+		for ( e in data.events ) {
+			jQuery.removeEvent( dest, e, data.handle );
+		}
+
+		// Event data gets referenced instead of copied if the expando gets copied too
+		dest.removeAttribute( jQuery.expando );
+	}
+
+	// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
+	if ( nodeName === "script" && dest.text !== src.text ) {
+		disableScript( dest ).text = src.text;
+		restoreScript( dest );
+
+	// IE6-10 improperly clones children of object elements using classid.
+	// IE10 throws NoModificationAllowedError if parent is null, #12132.
+	} else if ( nodeName === "object" ) {
+		if ( dest.parentNode ) {
+			dest.outerHTML = src.outerHTML;
+		}
+
+		// This path appears unavoidable for IE9. When cloning an object
+		// element in IE9, the outerHTML strategy above is not sufficient.
+		// If the src has innerHTML and the destination does not,
+		// copy the src.innerHTML into the dest.innerHTML. #10324
+		if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
+			dest.innerHTML = src.innerHTML;
+		}
+
+	} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
+		// IE6-8 fails to persist the checked state of a cloned checkbox
+		// or radio button. Worse, IE6-7 fail to give the cloned element
+		// a checked appearance if the defaultChecked value isn't also set
+
+		dest.defaultChecked = dest.checked = src.checked;
+
+		// IE6-7 get confused and end up setting the value of a cloned
+		// checkbox/radio button to an empty string instead of "on"
+		if ( dest.value !== src.value ) {
+			dest.value = src.value;
+		}
+
+	// IE6-8 fails to return the selected option to the default selected
+	// state when cloning options
+	} else if ( nodeName === "option" ) {
+		dest.defaultSelected = dest.selected = src.defaultSelected;
+
+	// IE6-8 fails to set the defaultValue to the correct value when
+	// cloning other types of input fields
+	} else if ( nodeName === "input" || nodeName === "textarea" ) {
+		dest.defaultValue = src.defaultValue;
+	}
+}
+
+jQuery.each({
+	appendTo: "append",
+	prependTo: "prepend",
+	insertBefore: "before",
+	insertAfter: "after",
+	replaceAll: "replaceWith"
+}, function( name, original ) {
+	jQuery.fn[ name ] = function( selector ) {
+		var elems,
+			i = 0,
+			ret = [],
+			insert = jQuery( selector ),
+			last = insert.length - 1;
+
+		for ( ; i <= last; i++ ) {
+			elems = i === last ? this : this.clone(true);
+			jQuery( insert[i] )[ original ]( elems );
+
+			// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
+			core_push.apply( ret, elems.get() );
+		}
+
+		return this.pushStack( ret );
+	};
+});
+
+function getAll( context, tag ) {
+	var elems, elem,
+		i = 0,
+		found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
+			typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
+			undefined;
+
+	if ( !found ) {
+		for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
+			if ( !tag || jQuery.nodeName( elem, tag ) ) {
+				found.push( elem );
+			} else {
+				jQuery.merge( found, getAll( elem, tag ) );
+			}
+		}
+	}
+
+	return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
+		jQuery.merge( [ context ], found ) :
+		found;
+}
+
+// Used in buildFragment, fixes the defaultChecked property
+function fixDefaultChecked( elem ) {
+	if ( manipulation_rcheckableType.test( elem.type ) ) {
+		elem.defaultChecked = elem.checked;
+	}
+}
+
+jQuery.extend({
+	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+		var destElements, node, clone, i, srcElements,
+			inPage = jQuery.contains( elem.ownerDocument, elem );
+
+		if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
+			clone = elem.cloneNode( true );
+
+		// IE<=8 does not properly clone detached, unknown element nodes
+		} else {
+			fragmentDiv.innerHTML = elem.outerHTML;
+			fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
+		}
+
+		if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
+				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
+
+			// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
+			destElements = getAll( clone );
+			srcElements = getAll( elem );
+
+			// Fix all IE cloning issues
+			for ( i = 0; (node = srcElements[i]) != null; ++i ) {
+				// Ensure that the destination node is not null; Fixes #9587
+				if ( destElements[i] ) {
+					fixCloneNodeIssues( node, destElements[i] );
+				}
+			}
+		}
+
+		// Copy the events from the original to the clone
+		if ( dataAndEvents ) {
+			if ( deepDataAndEvents ) {
+				srcElements = srcElements || getAll( elem );
+				destElements = destElements || getAll( clone );
+
+				for ( i = 0; (node = srcElements[i]) != null; i++ ) {
+					cloneCopyEvent( node, destElements[i] );
+				}
+			} else {
+				cloneCopyEvent( elem, clone );
+			}
+		}
+
+		// Preserve script evaluation history
+		destElements = getAll( clone, "script" );
+		if ( destElements.length > 0 ) {
+			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
+		}
+
+		destElements = srcElements = node = null;
+
+		// Return the cloned set
+		return clone;
+	},
+
+	buildFragment: function( elems, context, scripts, selection ) {
+		var j, elem, contains,
+			tmp, tag, tbody, wrap,
+			l = elems.length,
+
+			// Ensure a safe fragment
+			safe = createSafeFragment( context ),
+
+			nodes = [],
+			i = 0;
+
+		for ( ; i < l; i++ ) {
+			elem = elems[ i ];
+
+			if ( elem || elem === 0 ) {
+
+				// Add nodes directly
+				if ( jQuery.type( elem ) === "object" ) {
+					jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
+
+				// Convert non-html into a text node
+				} else if ( !rhtml.test( elem ) ) {
+					nodes.push( context.createTextNode( elem ) );
+
+				// Convert html into DOM nodes
+				} else {
+					tmp = tmp || safe.appendChild( context.createElement("div") );
+
+					// Deserialize a standard representation
+					tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
+					wrap = wrapMap[ tag ] || wrapMap._default;
+
+					tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
+
+					// Descend through wrappers to the right content
+					j = wrap[0];
+					while ( j-- ) {
+						tmp = tmp.lastChild;
+					}
+
+					// Manually add leading whitespace removed by IE
+					if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
+						nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
+					}
+
+					// Remove IE's autoinserted <tbody> from table fragments
+					if ( !jQuery.support.tbody ) {
+
+						// String was a <table>, *may* have spurious <tbody>
+						elem = tag === "table" && !rtbody.test( elem ) ?
+							tmp.firstChild :
+
+							// String was a bare <thead> or <tfoot>
+							wrap[1] === "<table>" && !rtbody.test( elem ) ?
+								tmp :
+								0;
+
+						j = elem && elem.childNodes.length;
+						while ( j-- ) {
+							if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
+								elem.removeChild( tbody );
+							}
+						}
+					}
+
+					jQuery.merge( nodes, tmp.childNodes );
+
+					// Fix #12392 for WebKit and IE > 9
+					tmp.textContent = "";
+
+					// Fix #12392 for oldIE
+					while ( tmp.firstChild ) {
+						tmp.removeChild( tmp.firstChild );
+					}
+
+					// Remember the top-level container for proper cleanup
+					tmp = safe.lastChild;
+				}
+			}
+		}
+
+		// Fix #11356: Clear elements from fragment
+		if ( tmp ) {
+			safe.removeChild( tmp );
+		}
+
+		// Reset defaultChecked for any radios and checkboxes
+		// about to be appended to the DOM in IE 6/7 (#8060)
+		if ( !jQuery.support.appendChecked ) {
+			jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
+		}
+
+		i = 0;
+		while ( (elem = nodes[ i++ ]) ) {
+
+			// #4087 - If origin and destination elements are the same, and this is
+			// that element, do not do anything
+			if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
+				continue;
+			}
+
+			contains = jQuery.contains( elem.ownerDocument, elem );
+
+			// Append to fragment
+			tmp = getAll( safe.appendChild( elem ), "script" );
+
+			// Preserve script evaluation history
+			if ( contains ) {
+				setGlobalEval( tmp );
+			}
+
+			// Capture executables
+			if ( scripts ) {
+				j = 0;
+				while ( (elem = tmp[ j++ ]) ) {
+					if ( rscriptType.test( elem.type || "" ) ) {
+						scripts.push( elem );
+					}
+				}
+			}
+		}
+
+		tmp = null;
+
+		return safe;
+	},
+
+	cleanData: function( elems, /* internal */ acceptData ) {
+		var elem, type, id, data,
+			i = 0,
+			internalKey = jQuery.expando,
+			cache = jQuery.cache,
+			deleteExpando = jQuery.support.deleteExpando,
+			special = jQuery.event.special;
+
+		for ( ; (elem = elems[i]) != null; i++ ) {
+
+			if ( acceptData || jQuery.acceptData( elem ) ) {
+
+				id = elem[ internalKey ];
+				data = id && cache[ id ];
+
+				if ( data ) {
+					if ( data.events ) {
+						for ( type in data.events ) {
+							if ( special[ type ] ) {
+								jQuery.event.remove( elem, type );
+
+							// This is a shortcut to avoid jQuery.event.remove's overhead
+							} else {
+								jQuery.removeEvent( elem, type, data.handle );
+							}
+						}
+					}
+
+					// Remove cache only if it was not already removed by jQuery.event.remove
+					if ( cache[ id ] ) {
+
+						delete cache[ id ];
+
+						// IE does not allow us to delete expando properties from nodes,
+						// nor does it have a removeAttribute function on Document nodes;
+						// we must handle all of these cases
+						if ( deleteExpando ) {
+							delete elem[ internalKey ];
+
+						} else if ( typeof elem.removeAttribute !== core_strundefined ) {
+							elem.removeAttribute( internalKey );
+
+						} else {
+							elem[ internalKey ] = null;
+						}
+
+						core_deletedIds.push( id );
+					}
+				}
+			}
+		}
+	},
+
+	_evalUrl: function( url ) {
+		return jQuery.ajax({
+			url: url,
+			type: "GET",
+			dataType: "script",
+			async: false,
+			global: false,
+			"throws": true
+		});
+	}
+});
+jQuery.fn.extend({
+	wrapAll: function( html ) {
+		if ( jQuery.isFunction( html ) ) {
+			return this.each(function(i) {
+				jQuery(this).wrapAll( html.call(this, i) );
+			});
+		}
+
+		if ( this[0] ) {
+			// The elements to wrap the target around
+			var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
+
+			if ( this[0].parentNode ) {
+				wrap.insertBefore( this[0] );
+			}
+
+			wrap.map(function() {
+				var elem = this;
+
+				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
+					elem = elem.firstChild;
+				}
+
+				return elem;
+			}).append( this );
+		}
+
+		return this;
+	},
+
+	wrapInner: function( html ) {
+		if ( jQuery.isFunction( html ) ) {
+			return this.each(function(i) {
+				jQuery(this).wrapInner( html.call(this, i) );
+			});
+		}
+
+		return this.each(function() {
+			var self = jQuery( this ),
+				contents = self.contents();
+
+			if ( contents.length ) {
+				contents.wrapAll( html );
+
+			} else {
+				self.append( html );
+			}
+		});
+	},
+
+	wrap: function( html ) {
+		var isFunction = jQuery.isFunction( html );
+
+		return this.each(function(i) {
+			jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
+		});
+	},
+
+	unwrap: function() {
+		return this.parent().each(function() {
+			if ( !jQuery.nodeName( this, "body" ) ) {
+				jQuery( this ).replaceWith( this.childNodes );
+			}
+		}).end();
+	}
+});
+var iframe, getStyles, curCSS,
+	ralpha = /alpha\([^)]*\)/i,
+	ropacity = /opacity\s*=\s*([^)]*)/,
+	rposition = /^(top|right|bottom|left)$/,
+	// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
+	// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
+	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
+	rmargin = /^margin/,
+	rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
+	rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
+	rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
+	elemdisplay = { BODY: "block" },
+
+	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+	cssNormalTransform = {
+		letterSpacing: 0,
+		fontWeight: 400
+	},
+
+	cssExpand = [ "Top", "Right", "Bottom", "Left" ],
+	cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
+
+// return a css property mapped to a potentially vendor prefixed property
+function vendorPropName( style, name ) {
+
+	// shortcut for names that are not vendor prefixed
+	if ( name in style ) {
+		return name;
+	}
+
+	// check for vendor prefixed names
+	var capName = name.charAt(0).toUpperCase() + name.slice(1),
+		origName = name,
+		i = cssPrefixes.length;
+
+	while ( i-- ) {
+		name = cssPrefixes[ i ] + capName;
+		if ( name in style ) {
+			return name;
+		}
+	}
+
+	return origName;
+}
+
+function isHidden( elem, el ) {
+	// isHidden might be called from jQuery#filter function;
+	// in that case, element will be second argument
+	elem = el || elem;
+	return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
+}
+
+function showHide( elements, show ) {
+	var display, elem, hidden,
+		values = [],
+		index = 0,
+		length = elements.length;
+
+	for ( ; index < length; index++ ) {
+		elem = elements[ index ];
+		if ( !elem.style ) {
+			continue;
+		}
+
+		values[ index ] = jQuery._data( elem, "olddisplay" );
+		display = elem.style.display;
+		if ( show ) {
+			// Reset the inline display of this element to learn if it is
+			// being hidden by cascaded rules or not
+			if ( !values[ index ] && display === "none" ) {
+				elem.style.display = "";
+			}
+
+			// Set elements which have been overridden with display: none
+			// in a stylesheet to whatever the default browser style is
+			// for such an element
+			if ( elem.style.display === "" && isHidden( elem ) ) {
+				values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
+			}
+		} else {
+
+			if ( !values[ index ] ) {
+				hidden = isHidden( elem );
+
+				if ( display && display !== "none" || !hidden ) {
+					jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
+				}
+			}
+		}
+	}
+
+	// Set the display of most of the elements in a second loop
+	// to avoid the constant reflow
+	for ( index = 0; index < length; index++ ) {
+		elem = elements[ index ];
+		if ( !elem.style ) {
+			continue;
+		}
+		if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
+			elem.style.display = show ? values[ index ] || "" : "none";
+		}
+	}
+
+	return elements;
+}
+
+jQuery.fn.extend({
+	css: function( name, value ) {
+		return jQuery.access( this, function( elem, name, value ) {
+			var len, styles,
+				map = {},
+				i = 0;
+
+			if ( jQuery.isArray( name ) ) {
+				styles = getStyles( elem );
+				len = name.length;
+
+				for ( ; i < len; i++ ) {
+					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
+				}
+
+				return map;
+			}
+
+			return value !== undefined ?
+				jQuery.style( elem, name, value ) :
+				jQuery.css( elem, name );
+		}, name, value, arguments.length > 1 );
+	},
+	show: function() {
+		return showHide( this, true );
+	},
+	hide: function() {
+		return showHide( this );
+	},
+	toggle: function( state ) {
+		if ( typeof state === "boolean" ) {
+			return state ? this.show() : this.hide();
+		}
+
+		return this.each(function() {
+			if ( isHidden( this ) ) {
+				jQuery( this ).show();
+			} else {
+				jQuery( this ).hide();
+			}
+		});
+	}
+});
+
+jQuery.extend({
+	// Add in style property hooks for overriding the default
+	// behavior of getting and setting a style property
+	cssHooks: {
+		opacity: {
+			get: function( elem, computed ) {
+				if ( computed ) {
+					// We should always get a number back from opacity
+					var ret = curCSS( elem, "opacity" );
+					return ret === "" ? "1" : ret;
+				}
+			}
+		}
+	},
+
+	// Don't automatically add "px" to these possibly-unitless properties
+	cssNumber: {
+		"columnCount": true,
+		"fillOpacity": true,
+		"fontWeight": true,
+		"lineHeight": true,
+		"opacity": true,
+		"order": true,
+		"orphans": true,
+		"widows": true,
+		"zIndex": true,
+		"zoom": true
+	},
+
+	// Add in properties whose names you wish to fix before
+	// setting or getting the value
+	cssProps: {
+		// normalize float css property
+		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
+	},
+
+	// Get and set the style property on a DOM Node
+	style: function( elem, name, value, extra ) {
+		// Don't set styles on text and comment nodes
+		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
+			return;
+		}
+
+		// Make sure that we're working with the right name
+		var ret, type, hooks,
+			origName = jQuery.camelCase( name ),
+			style = elem.style;
+
+		name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
+
+		// gets hook for the prefixed version
+		// followed by the unprefixed version
+		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+		// Check if we're setting a value
+		if ( value !== undefined ) {
+			type = typeof value;
+
+			// convert relative number strings (+= or -=) to relative numbers. #7345
+			if ( type === "string" && (ret = rrelNum.exec( value )) ) {
+				value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
+				// Fixes bug #9237
+				type = "number";
+			}
+
+			// Make sure that NaN and null values aren't set. See: #7116
+			if ( value == null || type === "number" && isNaN( value ) ) {
+				return;
+			}
+
+			// If a number was passed in, add 'px' to the (except for certain CSS properties)
+			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
+				value += "px";
+			}
+
+			// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
+			// but it would mean to define eight (for every problematic property) identical functions
+			if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
+				style[ name ] = "inherit";
+			}
+
+			// If a hook was provided, use that value, otherwise just set the specified value
+			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
+
+				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
+				// Fixes bug #5509
+				try {
+					style[ name ] = value;
+				} catch(e) {}
+			}
+
+		} else {
+			// If a hook was provided get the non-computed value from there
+			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
+				return ret;
+			}
+
+			// Otherwise just get the value from the style object
+			return style[ name ];
+		}
+	},
+
+	css: function( elem, name, extra, styles ) {
+		var num, val, hooks,
+			origName = jQuery.camelCase( name );
+
+		// Make sure that we're working with the right name
+		name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
+
+		// gets hook for the prefixed version
+		// followed by the unprefixed version
+		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+		// If a hook was provided get the computed value from there
+		if ( hooks && "get" in hooks ) {
+			val = hooks.get( elem, true, extra );
+		}
+
+		// Otherwise, if a way to get the computed value exists, use that
+		if ( val === undefined ) {
+			val = curCSS( elem, name, styles );
+		}
+
+		//convert "normal" to computed value
+		if ( val === "normal" && name in cssNormalTransform ) {
+			val = cssNormalTransform[ name ];
+		}
+
+		// Return, converting to number if forced or a qualifier was provided and val looks numeric
+		if ( extra === "" || extra ) {
+			num = parseFloat( val );
+			return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
+		}
+		return val;
+	}
+});
+
+// NOTE: we've included the "window" in window.getComputedStyle
+// because jsdom on node.js will break without it.
+if ( window.getComputedStyle ) {
+	getStyles = function( elem ) {
+		return window.getComputedStyle( elem, null );
+	};
+
+	curCSS = function( elem, name, _computed ) {
+		var width, minWidth, maxWidth,
+			computed = _computed || getStyles( elem ),
+
+			// getPropertyValue is only needed for .css('filter') in IE9, see #12537
+			ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
+			style = elem.style;
+
+		if ( computed ) {
+
+			if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
+				ret = jQuery.style( elem, name );
+			}
+
+			// A tribute to the "awesome hack by Dean Edwards"
+			// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
+			// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
+			// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
+			if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
+
+				// Remember the original values
+				width = style.width;
+				minWidth = style.minWidth;
+				maxWidth = style.maxWidth;
+
+				// Put in the new values to get a computed value out
+				style.minWidth = style.maxWidth = style.width = ret;
+				ret = computed.width;
+
+				// Revert the changed values
+				style.width = width;
+				style.minWidth = minWidth;
+				style.maxWidth = maxWidth;
+			}
+		}
+
+		return ret;
+	};
+} else if ( document.documentElement.currentStyle ) {
+	getStyles = function( elem ) {
+		return elem.currentStyle;
+	};
+
+	curCSS = function( elem, name, _computed ) {
+		var left, rs, rsLeft,
+			computed = _computed || getStyles( elem ),
+			ret = computed ? computed[ name ] : undefined,
+			style = elem.style;
+
+		// Avoid setting ret to empty string here
+		// so we don't default to auto
+		if ( ret == null && style && style[ name ] ) {
+			ret = style[ name ];
+		}
+
+		// From the awesome hack by Dean Edwards
+		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+		// If we're not dealing with a regular pixel number
+		// but a number that has a weird ending, we need to convert it to pixels
+		// but not position css attributes, as those are proportional to the parent element instead
+		// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
+		if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
+
+			// Remember the original values
+			left = style.left;
+			rs = elem.runtimeStyle;
+			rsLeft = rs && rs.left;
+
+			// Put in the new values to get a computed value out
+			if ( rsLeft ) {
+				rs.left = elem.currentStyle.left;
+			}
+			style.left = name === "fontSize" ? "1em" : ret;
+			ret = style.pixelLeft + "px";
+
+			// Revert the changed values
+			style.left = left;
+			if ( rsLeft ) {
+				rs.left = rsLeft;
+			}
+		}
+
+		return ret === "" ? "auto" : ret;
+	};
+}
+
+function setPositiveNumber( elem, value, subtract ) {
+	var matches = rnumsplit.exec( value );
+	return matches ?
+		// Guard against undefined "subtract", e.g., when used as in cssHooks
+		Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
+		value;
+}
+
+function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
+	var i = extra === ( isBorderBox ? "border" : "content" ) ?
+		// If we already have the right measurement, avoid augmentation
+		4 :
+		// Otherwise initialize for horizontal or vertical properties
+		name === "width" ? 1 : 0,
+
+		val = 0;
+
+	for ( ; i < 4; i += 2 ) {
+		// both box models exclude margin, so add it if we want it
+		if ( extra === "margin" ) {
+			val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
+		}
+
+		if ( isBorderBox ) {
+			// border-box includes padding, so remove it if we want content
+			if ( extra === "content" ) {
+				val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
+			}
+
+			// at this point, extra isn't border nor margin, so remove border
+			if ( extra !== "margin" ) {
+				val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+			}
+		} else {
+			// at this point, extra isn't content, so add padding
+			val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
+
+			// at this point, extra isn't content nor padding, so add border
+			if ( extra !== "padding" ) {
+				val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+			}
+		}
+	}
+
+	return val;
+}
+
+function getWidthOrHeight( elem, name, extra ) {
+
+	// Start with offset property, which is equivalent to the border-box value
+	var valueIsBorderBox = true,
+		val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
+		styles = getStyles( elem ),
+		isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
+
+	// some non-html elements return undefined for offsetWidth, so check for null/undefined
+	// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
+	// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
+	if ( val <= 0 || val == null ) {
+		// Fall back to computed then uncomputed css if necessary
+		val = curCSS( elem, name, styles );
+		if ( val < 0 || val == null ) {
+			val = elem.style[ name ];
+		}
+
+		// Computed unit is not pixels. Stop here and return.
+		if ( rnumnonpx.test(val) ) {
+			return val;
+		}
+
+		// we need the check for style in case a browser which returns unreliable values
+		// for getComputedStyle silently falls back to the reliable elem.style
+		valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
+
+		// Normalize "", auto, and prepare for extra
+		val = parseFloat( val ) || 0;
+	}
+
+	// use the active box-sizing model to add/subtract irrelevant styles
+	return ( val +
+		augmentWidthOrHeight(
+			elem,
+			name,
+			extra || ( isBorderBox ? "border" : "content" ),
+			valueIsBorderBox,
+			styles
+		)
+	) + "px";
+}
+
+// Try to determine the default display value of an element
+function css_defaultDisplay( nodeName ) {
+	var doc = document,
+		display = elemdisplay[ nodeName ];
+
+	if ( !display ) {
+		display = actualDisplay( nodeName, doc );
+
+		// If the simple way fails, read from inside an iframe
+		if ( display === "none" || !display ) {
+			// Use the already-created iframe if possible
+			iframe = ( iframe ||
+				jQuery("<iframe frameborder='0' width='0' height='0'/>")
+				.css( "cssText", "display:block !important" )
+			).appendTo( doc.documentElement );
+
+			// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
+			doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
+			doc.write("<!doctype html><html><body>");
+			doc.close();
+
+			display = actualDisplay( nodeName, doc );
+			iframe.detach();
+		}
+
+		// Store the correct default display
+		elemdisplay[ nodeName ] = display;
+	}
+
+	return display;
+}
+
+// Called ONLY from within css_defaultDisplay
+function actualDisplay( name, doc ) {
+	var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
+		display = jQuery.css( elem[0], "display" );
+	elem.remove();
+	return display;
+}
+
+jQuery.each([ "height", "width" ], function( i, name ) {
+	jQuery.cssHooks[ name ] = {
+		get: function( elem, computed, extra ) {
+			if ( computed ) {
+				// certain elements can have dimension info if we invisibly show them
+				// however, it must have a current display style that would benefit from this
+				return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
+					jQuery.swap( elem, cssShow, function() {
+						return getWidthOrHeight( elem, name, extra );
+					}) :
+					getWidthOrHeight( elem, name, extra );
+			}
+		},
+
+		set: function( elem, value, extra ) {
+			var styles = extra && getStyles( elem );
+			return setPositiveNumber( elem, value, extra ?
+				augmentWidthOrHeight(
+					elem,
+					name,
+					extra,
+					jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
+					styles
+				) : 0
+			);
+		}
+	};
+});
+
+if ( !jQuery.support.opacity ) {
+	jQuery.cssHooks.opacity = {
+		get: function( elem, computed ) {
+			// IE uses filters for opacity
+			return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
+				( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
+				computed ? "1" : "";
+		},
+
+		set: function( elem, value ) {
+			var style = elem.style,
+				currentStyle = elem.currentStyle,
+				opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
+				filter = currentStyle && currentStyle.filter || style.filter || "";
+
+			// IE has trouble with opacity if it does not have layout
+			// Force it by setting the zoom level
+			style.zoom = 1;
+
+			// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
+			// if value === "", then remove inline opacity #12685
+			if ( ( value >= 1 || value === "" ) &&
+					jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
+					style.removeAttribute ) {
+
+				// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
+				// if "filter:" is present at all, clearType is disabled, we want to avoid this
+				// style.removeAttribute is IE Only, but so apparently is this code path...
+				style.removeAttribute( "filter" );
+
+				// if there is no filter style applied in a css rule or unset inline opacity, we are done
+				if ( value === "" || currentStyle && !currentStyle.filter ) {
+					return;
+				}
+			}
+
+			// otherwise, set new filter values
+			style.filter = ralpha.test( filter ) ?
+				filter.replace( ralpha, opacity ) :
+				filter + " " + opacity;
+		}
+	};
+}
+
+// These hooks cannot be added until DOM ready because the support test
+// for it is not run until after DOM ready
+jQuery(function() {
+	if ( !jQuery.support.reliableMarginRight ) {
+		jQuery.cssHooks.marginRight = {
+			get: function( elem, computed ) {
+				if ( computed ) {
+					// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+					// Work around by temporarily setting element display to inline-block
+					return jQuery.swap( elem, { "display": "inline-block" },
+						curCSS, [ elem, "marginRight" ] );
+				}
+			}
+		};
+	}
+
+	// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
+	// getComputedStyle returns percent when specified for top/left/bottom/right
+	// rather than make the css module depend on the offset module, we just check for it here
+	if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
+		jQuery.each( [ "top", "left" ], function( i, prop ) {
+			jQuery.cssHooks[ prop ] = {
+				get: function( elem, computed ) {
+					if ( computed ) {
+						computed = curCSS( elem, prop );
+						// if curCSS returns percentage, fallback to offset
+						return rnumnonpx.test( computed ) ?
+							jQuery( elem ).position()[ prop ] + "px" :
+							computed;
+					}
+				}
+			};
+		});
+	}
+
+});
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+	jQuery.expr.filters.hidden = function( elem ) {
+		// Support: Opera <= 12.12
+		// Opera reports offsetWidths and offsetHeights less than zero on some elements
+		return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
+			(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
+	};
+
+	jQuery.expr.filters.visible = function( elem ) {
+		return !jQuery.expr.filters.hidden( elem );
+	};
+}
+
+// These hooks are used by animate to expand properties
+jQuery.each({
+	margin: "",
+	padding: "",
+	border: "Width"
+}, function( prefix, suffix ) {
+	jQuery.cssHooks[ prefix + suffix ] = {
+		expand: function( value ) {
+			var i = 0,
+				expanded = {},
+
+				// assumes a single number if not a string
+				parts = typeof value === "string" ? value.split(" ") : [ value ];
+
+			for ( ; i < 4; i++ ) {
+				expanded[ prefix + cssExpand[ i ] + suffix ] =
+					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
+			}
+
+			return expanded;
+		}
+	};
+
+	if ( !rmargin.test( prefix ) ) {
+		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
+	}
+});
+var r20 = /%20/g,
+	rbracket = /\[\]$/,
+	rCRLF = /\r?\n/g,
+	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
+	rsubmittable = /^(?:input|select|textarea|keygen)/i;
+
+jQuery.fn.extend({
+	serialize: function() {
+		return jQuery.param( this.serializeArray() );
+	},
+	serializeArray: function() {
+		return this.map(function(){
+			// Can add propHook for "elements" to filter or add form elements
+			var elements = jQuery.prop( this, "elements" );
+			return elements ? jQuery.makeArray( elements ) : this;
+		})
+		.filter(function(){
+			var type = this.type;
+			// Use .is(":disabled") so that fieldset[disabled] works
+			return this.name && !jQuery( this ).is( ":disabled" ) &&
+				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
+				( this.checked || !manipulation_rcheckableType.test( type ) );
+		})
+		.map(function( i, elem ){
+			var val = jQuery( this ).val();
+
+			return val == null ?
+				null :
+				jQuery.isArray( val ) ?
+					jQuery.map( val, function( val ){
+						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+					}) :
+					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+		}).get();
+	}
+});
+
+//Serialize an array of form elements or a set of
+//key/values into a query string
+jQuery.param = function( a, traditional ) {
+	var prefix,
+		s = [],
+		add = function( key, value ) {
+			// If value is a function, invoke it and return its value
+			value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
+			s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
+		};
+
+	// Set traditional to true for jQuery <= 1.3.2 behavior.
+	if ( traditional === undefined ) {
+		traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
+	}
+
+	// If an array was passed in, assume that it is an array of form elements.
+	if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
+		// Serialize the form elements
+		jQuery.each( a, function() {
+			add( this.name, this.value );
+		});
+
+	} else {
+		// If traditional, encode the "old" way (the way 1.3.2 or older
+		// did it), otherwise encode params recursively.
+		for ( prefix in a ) {
+			buildParams( prefix, a[ prefix ], traditional, add );
+		}
+	}
+
+	// Return the resulting serialization
+	return s.join( "&" ).replace( r20, "+" );
+};
+
+function buildParams( prefix, obj, traditional, add ) {
+	var name;
+
+	if ( jQuery.isArray( obj ) ) {
+		// Serialize array item.
+		jQuery.each( obj, function( i, v ) {
+			if ( traditional || rbracket.test( prefix ) ) {
+				// Treat each array item as a scalar.
+				add( prefix, v );
+
+			} else {
+				// Item is non-scalar (array or object), encode its numeric index.
+				buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
+			}
+		});
+
+	} else if ( !traditional && jQuery.type( obj ) === "object" ) {
+		// Serialize object item.
+		for ( name in obj ) {
+			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
+		}
+
+	} else {
+		// Serialize scalar item.
+		add( prefix, obj );
+	}
+}
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+	"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
+
+	// Handle event binding
+	jQuery.fn[ name ] = function( data, fn ) {
+		return arguments.length > 0 ?
+			this.on( name, null, data, fn ) :
+			this.trigger( name );
+	};
+});
+
+jQuery.fn.extend({
+	hover: function( fnOver, fnOut ) {
+		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+	},
+
+	bind: function( types, data, fn ) {
+		return this.on( types, null, data, fn );
+	},
+	unbind: function( types, fn ) {
+		return this.off( types, null, fn );
+	},
+
+	delegate: function( selector, types, data, fn ) {
+		return this.on( types, selector, data, fn );
+	},
+	undelegate: function( selector, types, fn ) {
+		// ( namespace ) or ( selector, types [, fn] )
+		return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
+	}
+});
+var
+	// Document location
+	ajaxLocParts,
+	ajaxLocation,
+	ajax_nonce = jQuery.now(),
+
+	ajax_rquery = /\?/,
+	rhash = /#.*$/,
+	rts = /([?&])_=[^&]*/,
+	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
+	// #7653, #8125, #8152: local protocol detection
+	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
+	rnoContent = /^(?:GET|HEAD)$/,
+	rprotocol = /^\/\//,
+	rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
+
+	// Keep a copy of the old load method
+	_load = jQuery.fn.load,
+
+	/* Prefilters
+	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+	 * 2) These are called:
+	 *    - BEFORE asking for a transport
+	 *    - AFTER param serialization (s.data is a string if s.processData is true)
+	 * 3) key is the dataType
+	 * 4) the catchall symbol "*" can be used
+	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+	 */
+	prefilters = {},
+
+	/* Transports bindings
+	 * 1) key is the dataType
+	 * 2) the catchall symbol "*" can be used
+	 * 3) selection will start with transport dataType and THEN go to "*" if needed
+	 */
+	transports = {},
+
+	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
+	allTypes = "*/".concat("*");
+
+// #8138, IE may throw an exception when accessing
+// a field from window.location if document.domain has been set
+try {
+	ajaxLocation = location.href;
+} catch( e ) {
+	// Use the href attribute of an A element
+	// since IE will modify it given document.location
+	ajaxLocation = document.createElement( "a" );
+	ajaxLocation.href = "";
+	ajaxLocation = ajaxLocation.href;
+}
+
+// Segment location into parts
+ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+	// dataTypeExpression is optional and defaults to "*"
+	return function( dataTypeExpression, func ) {
+
+		if ( typeof dataTypeExpression !== "string" ) {
+			func = dataTypeExpression;
+			dataTypeExpression = "*";
+		}
+
+		var dataType,
+			i = 0,
+			dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
+
+		if ( jQuery.isFunction( func ) ) {
+			// For each dataType in the dataTypeExpression
+			while ( (dataType = dataTypes[i++]) ) {
+				// Prepend if requested
+				if ( dataType[0] === "+" ) {
+					dataType = dataType.slice( 1 ) || "*";
+					(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
+
+				// Otherwise append
+				} else {
+					(structure[ dataType ] = structure[ dataType ] || []).push( func );
+				}
+			}
+		}
+	};
+}
+
+// Base inspection function for prefilters and transports
+function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
+
+	var inspected = {},
+		seekingTransport = ( structure === transports );
+
+	function inspect( dataType ) {
+		var selected;
+		inspected[ dataType ] = true;
+		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
+			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
+			if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
+				options.dataTypes.unshift( dataTypeOrTransport );
+				inspect( dataTypeOrTransport );
+				return false;
+			} else if ( seekingTransport ) {
+				return !( selected = dataTypeOrTransport );
+			}
+		});
+		return selected;
+	}
+
+	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
+}
+
+// A special extend for ajax options
+// that takes "flat" options (not to be deep extended)
+// Fixes #9887
+function ajaxExtend( target, src ) {
+	var deep, key,
+		flatOptions = jQuery.ajaxSettings.flatOptions || {};
+
+	for ( key in src ) {
+		if ( src[ key ] !== undefined ) {
+			( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
+		}
+	}
+	if ( deep ) {
+		jQuery.extend( true, target, deep );
+	}
+
+	return target;
+}
+
+jQuery.fn.load = function( url, params, callback ) {
+	if ( typeof url !== "string" && _load ) {
+		return _load.apply( this, arguments );
+	}
+
+	var selector, response, type,
+		self = this,
+		off = url.indexOf(" ");
+
+	if ( off >= 0 ) {
+		selector = url.slice( off, url.length );
+		url = url.slice( 0, off );
+	}
+
+	// If it's a function
+	if ( jQuery.isFunction( params ) ) {
+
+		// We assume that it's the callback
+		callback = params;
+		params = undefined;
+
+	// Otherwise, build a param string
+	} else if ( params && typeof params === "object" ) {
+		type = "POST";
+	}
+
+	// If we have elements to modify, make the request
+	if ( self.length > 0 ) {
+		jQuery.ajax({
+			url: url,
+
+			// if "type" variable is undefined, then "GET" method will be used
+			type: type,
+			dataType: "html",
+			data: params
+		}).done(function( responseText ) {
+
+			// Save response for use in complete callback
+			response = arguments;
+
+			self.html( selector ?
+
+				// If a selector was specified, locate the right elements in a dummy div
+				// Exclude scripts to avoid IE 'Permission Denied' errors
+				jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
+
+				// Otherwise use the full result
+				responseText );
+
+		}).complete( callback && function( jqXHR, status ) {
+			self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
+		});
+	}
+
+	return this;
+};
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
+	jQuery.fn[ type ] = function( fn ){
+		return this.on( type, fn );
+	};
+});
+
+jQuery.extend({
+
+	// Counter for holding the number of active queries
+	active: 0,
+
+	// Last-Modified header cache for next request
+	lastModified: {},
+	etag: {},
+
+	ajaxSettings: {
+		url: ajaxLocation,
+		type: "GET",
+		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
+		global: true,
+		processData: true,
+		async: true,
+		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+		/*
+		timeout: 0,
+		data: null,
+		dataType: null,
+		username: null,
+		password: null,
+		cache: null,
+		throws: false,
+		traditional: false,
+		headers: {},
+		*/
+
+		accepts: {
+			"*": allTypes,
+			text: "text/plain",
+			html: "text/html",
+			xml: "application/xml, text/xml",
+			json: "application/json, text/javascript"
+		},
+
+		contents: {
+			xml: /xml/,
+			html: /html/,
+			json: /json/
+		},
+
+		responseFields: {
+			xml: "responseXML",
+			text: "responseText",
+			json: "responseJSON"
+		},
+
+		// Data converters
+		// Keys separate source (or catchall "*") and destination types with a single space
+		converters: {
+
+			// Convert anything to text
+			"* text": String,
+
+			// Text to html (true = no transformation)
+			"text html": true,
+
+			// Evaluate text as a json expression
+			"text json": jQuery.parseJSON,
+
+			// Parse text as xml
+			"text xml": jQuery.parseXML
+		},
+
+		// For options that shouldn't be deep extended:
+		// you can add your own custom options here if
+		// and when you create one that shouldn't be
+		// deep extended (see ajaxExtend)
+		flatOptions: {
+			url: true,
+			context: true
+		}
+	},
+
+	// Creates a full fledged settings object into target
+	// with both ajaxSettings and settings fields.
+	// If target is omitted, writes into ajaxSettings.
+	ajaxSetup: function( target, settings ) {
+		return settings ?
+
+			// Building a settings object
+			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
+
+			// Extending ajaxSettings
+			ajaxExtend( jQuery.ajaxSettings, target );
+	},
+
+	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+	ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+	// Main method
+	ajax: function( url, options ) {
+
+		// If url is an object, simulate pre-1.5 signature
+		if ( typeof url === "object" ) {
+			options = url;
+			url = undefined;
+		}
+
+		// Force options to be an object
+		options = options || {};
+
+		var // Cross-domain detection vars
+			parts,
+			// Loop variable
+			i,
+			// URL without anti-cache param
+			cacheURL,
+			// Response headers as string
+			responseHeadersString,
+			// timeout handle
+			timeoutTimer,
+
+			// To know if global events are to be dispatched
+			fireGlobals,
+
+			transport,
+			// Response headers
+			responseHeaders,
+			// Create the final options object
+			s = jQuery.ajaxSetup( {}, options ),
+			// Callbacks context
+			callbackContext = s.context || s,
+			// Context for global events is callbackContext if it is a DOM node or jQuery collection
+			globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
+				jQuery( callbackContext ) :
+				jQuery.event,
+			// Deferreds
+			deferred = jQuery.Deferred(),
+			completeDeferred = jQuery.Callbacks("once memory"),
+			// Status-dependent callbacks
+			statusCode = s.statusCode || {},
+			// Headers (they are sent all at once)
+			requestHeaders = {},
+			requestHeadersNames = {},
+			// The jqXHR state
+			state = 0,
+			// Default abort message
+			strAbort = "canceled",
+			// Fake xhr
+			jqXHR = {
+				readyState: 0,
+
+				// Builds headers hashtable if needed
+				getResponseHeader: function( key ) {
+					var match;
+					if ( state === 2 ) {
+						if ( !responseHeaders ) {
+							responseHeaders = {};
+							while ( (match = rheaders.exec( responseHeadersString )) ) {
+								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+							}
+						}
+						match = responseHeaders[ key.toLowerCase() ];
+					}
+					return match == null ? null : match;
+				},
+
+				// Raw string
+				getAllResponseHeaders: function() {
+					return state === 2 ? responseHeadersString : null;
+				},
+
+				// Caches the header
+				setRequestHeader: function( name, value ) {
+					var lname = name.toLowerCase();
+					if ( !state ) {
+						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
+						requestHeaders[ name ] = value;
+					}
+					return this;
+				},
+
+				// Overrides response content-type header
+				overrideMimeType: function( type ) {
+					if ( !state ) {
+						s.mimeType = type;
+					}
+					return this;
+				},
+
+				// Status-dependent callbacks
+				statusCode: function( map ) {
+					var code;
+					if ( map ) {
+						if ( state < 2 ) {
+							for ( code in map ) {
+								// Lazy-add the new callback in a way that preserves old ones
+								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
+							}
+						} else {
+							// Execute the appropriate callbacks
+							jqXHR.always( map[ jqXHR.status ] );
+						}
+					}
+					return this;
+				},
+
+				// Cancel the request
+				abort: function( statusText ) {
+					var finalText = statusText || strAbort;
+					if ( transport ) {
+						transport.abort( finalText );
+					}
+					done( 0, finalText );
+					return this;
+				}
+			};
+
+		// Attach deferreds
+		deferred.promise( jqXHR ).complete = completeDeferred.add;
+		jqXHR.success = jqXHR.done;
+		jqXHR.error = jqXHR.fail;
+
+		// Remove hash character (#7531: and string promotion)
+		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
+		// Handle falsy url in the settings object (#10093: consistency with old signature)
+		// We also use the url parameter if available
+		s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
+
+		// Alias method option to type as per ticket #12004
+		s.type = options.method || options.type || s.method || s.type;
+
+		// Extract dataTypes list
+		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
+
+		// A cross-domain request is in order when we have a protocol:host:port mismatch
+		if ( s.crossDomain == null ) {
+			parts = rurl.exec( s.url.toLowerCase() );
+			s.crossDomain = !!( parts &&
+				( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
+					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
+						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
+			);
+		}
+
+		// Convert data if not already a string
+		if ( s.data && s.processData && typeof s.data !== "string" ) {
+			s.data = jQuery.param( s.data, s.traditional );
+		}
+
+		// Apply prefilters
+		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
+
+		// If request was aborted inside a prefilter, stop there
+		if ( state === 2 ) {
+			return jqXHR;
+		}
+
+		// We can fire global events as of now if asked to
+		fireGlobals = s.global;
+
+		// Watch for a new set of requests
+		if ( fireGlobals && jQuery.active++ === 0 ) {
+			jQuery.event.trigger("ajaxStart");
+		}
+
+		// Uppercase the type
+		s.type = s.type.toUpperCase();
+
+		// Determine if request has content
+		s.hasContent = !rnoContent.test( s.type );
+
+		// Save the URL in case we're toying with the If-Modified-Since
+		// and/or If-None-Match header later on
+		cacheURL = s.url;
+
+		// More options handling for requests with no content
+		if ( !s.hasContent ) {
+
+			// If data is available, append data to url
+			if ( s.data ) {
+				cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
+				// #9682: remove data so that it's not used in an eventual retry
+				delete s.data;
+			}
+
+			// Add anti-cache in url if needed
+			if ( s.cache === false ) {
+				s.url = rts.test( cacheURL ) ?
+
+					// If there is already a '_' parameter, set its value
+					cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
+
+					// Otherwise add one to the end
+					cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
+			}
+		}
+
+		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+		if ( s.ifModified ) {
+			if ( jQuery.lastModified[ cacheURL ] ) {
+				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
+			}
+			if ( jQuery.etag[ cacheURL ] ) {
+				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
+			}
+		}
+
+		// Set the correct header, if data is being sent
+		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+			jqXHR.setRequestHeader( "Content-Type", s.contentType );
+		}
+
+		// Set the Accepts header for the server, depending on the dataType
+		jqXHR.setRequestHeader(
+			"Accept",
+			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+				s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
+				s.accepts[ "*" ]
+		);
+
+		// Check for headers option
+		for ( i in s.headers ) {
+			jqXHR.setRequestHeader( i, s.headers[ i ] );
+		}
+
+		// Allow custom headers/mimetypes and early abort
+		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
+			// Abort if not done already and return
+			return jqXHR.abort();
+		}
+
+		// aborting is no longer a cancellation
+		strAbort = "abort";
+
+		// Install callbacks on deferreds
+		for ( i in { success: 1, error: 1, complete: 1 } ) {
+			jqXHR[ i ]( s[ i ] );
+		}
+
+		// Get transport
+		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
+
+		// If no transport, we auto-abort
+		if ( !transport ) {
+			done( -1, "No Transport" );
+		} else {
+			jqXHR.readyState = 1;
+
+			// Send global event
+			if ( fireGlobals ) {
+				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
+			}
+			// Timeout
+			if ( s.async && s.timeout > 0 ) {
+				timeoutTimer = setTimeout(function() {
+					jqXHR.abort("timeout");
+				}, s.timeout );
+			}
+
+			try {
+				state = 1;
+				transport.send( requestHeaders, done );
+			} catch ( e ) {
+				// Propagate exception as error if not done
+				if ( state < 2 ) {
+					done( -1, e );
+				// Simply rethrow otherwise
+				} else {
+					throw e;
+				}
+			}
+		}
+
+		// Callback for when everything is done
+		function done( status, nativeStatusText, responses, headers ) {
+			var isSuccess, success, error, response, modified,
+				statusText = nativeStatusText;
+
+			// Called once
+			if ( state === 2 ) {
+				return;
+			}
+
+			// State is "done" now
+			state = 2;
+
+			// Clear timeout if it exists
+			if ( timeoutTimer ) {
+				clearTimeout( timeoutTimer );
+			}
+
+			// Dereference transport for early garbage collection
+			// (no matter how long the jqXHR object will be used)
+			transport = undefined;
+
+			// Cache response headers
+			responseHeadersString = headers || "";
+
+			// Set readyState
+			jqXHR.readyState = status > 0 ? 4 : 0;
+
+			// Determine if successful
+			isSuccess = status >= 200 && status < 300 || status === 304;
+
+			// Get response data
+			if ( responses ) {
+				response = ajaxHandleResponses( s, jqXHR, responses );
+			}
+
+			// Convert no matter what (that way responseXXX fields are always set)
+			response = ajaxConvert( s, response, jqXHR, isSuccess );
+
+			// If successful, handle type chaining
+			if ( isSuccess ) {
+
+				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+				if ( s.ifModified ) {
+					modified = jqXHR.getResponseHeader("Last-Modified");
+					if ( modified ) {
+						jQuery.lastModified[ cacheURL ] = modified;
+					}
+					modified = jqXHR.getResponseHeader("etag");
+					if ( modified ) {
+						jQuery.etag[ cacheURL ] = modified;
+					}
+				}
+
+				// if no content
+				if ( status === 204 || s.type === "HEAD" ) {
+					statusText = "nocontent";
+
+				// if not modified
+				} else if ( status === 304 ) {
+					statusText = "notmodified";
+
+				// If we have data, let's convert it
+				} else {
+					statusText = response.state;
+					success = response.data;
+					error = response.error;
+					isSuccess = !error;
+				}
+			} else {
+				// We extract error from statusText
+				// then normalize statusText and status for non-aborts
+				error = statusText;
+				if ( status || !statusText ) {
+					statusText = "error";
+					if ( status < 0 ) {
+						status = 0;
+					}
+				}
+			}
+
+			// Set data for the fake xhr object
+			jqXHR.status = status;
+			jqXHR.statusText = ( nativeStatusText || statusText ) + "";
+
+			// Success/Error
+			if ( isSuccess ) {
+				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
+			} else {
+				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
+			}
+
+			// Status-dependent callbacks
+			jqXHR.statusCode( statusCode );
+			statusCode = undefined;
+
+			if ( fireGlobals ) {
+				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
+					[ jqXHR, s, isSuccess ? success : error ] );
+			}
+
+			// Complete
+			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
+
+			if ( fireGlobals ) {
+				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
+				// Handle the global AJAX counter
+				if ( !( --jQuery.active ) ) {
+					jQuery.event.trigger("ajaxStop");
+				}
+			}
+		}
+
+		return jqXHR;
+	},
+
+	getJSON: function( url, data, callback ) {
+		return jQuery.get( url, data, callback, "json" );
+	},
+
+	getScript: function( url, callback ) {
+		return jQuery.get( url, undefined, callback, "script" );
+	}
+});
+
+jQuery.each( [ "get", "post" ], function( i, method ) {
+	jQuery[ method ] = function( url, data, callback, type ) {
+		// shift arguments if data argument was omitted
+		if ( jQuery.isFunction( data ) ) {
+			type = type || callback;
+			callback = data;
+			data = undefined;
+		}
+
+		return jQuery.ajax({
+			url: url,
+			type: method,
+			dataType: type,
+			data: data,
+			success: callback
+		});
+	};
+});
+
+/* Handles responses to an ajax request:
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jqXHR, responses ) {
+	var firstDataType, ct, finalDataType, type,
+		contents = s.contents,
+		dataTypes = s.dataTypes;
+
+	// Remove auto dataType and get content-type in the process
+	while( dataTypes[ 0 ] === "*" ) {
+		dataTypes.shift();
+		if ( ct === undefined ) {
+			ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
+		}
+	}
+
+	// Check if we're dealing with a known content-type
+	if ( ct ) {
+		for ( type in contents ) {
+			if ( contents[ type ] && contents[ type ].test( ct ) ) {
+				dataTypes.unshift( type );
+				break;
+			}
+		}
+	}
+
+	// Check to see if we have a response for the expected dataType
+	if ( dataTypes[ 0 ] in responses ) {
+		finalDataType = dataTypes[ 0 ];
+	} else {
+		// Try convertible dataTypes
+		for ( type in responses ) {
+			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
+				finalDataType = type;
+				break;
+			}
+			if ( !firstDataType ) {
+				firstDataType = type;
+			}
+		}
+		// Or just use first one
+		finalDataType = finalDataType || firstDataType;
+	}
+
+	// If we found a dataType
+	// We add the dataType to the list if needed
+	// and return the corresponding response
+	if ( finalDataType ) {
+		if ( finalDataType !== dataTypes[ 0 ] ) {
+			dataTypes.unshift( finalDataType );
+		}
+		return responses[ finalDataType ];
+	}
+}
+
+/* Chain conversions given the request and the original response
+ * Also sets the responseXXX fields on the jqXHR instance
+ */
+function ajaxConvert( s, response, jqXHR, isSuccess ) {
+	var conv2, current, conv, tmp, prev,
+		converters = {},
+		// Work with a copy of dataTypes in case we need to modify it for conversion
+		dataTypes = s.dataTypes.slice();
+
+	// Create converters map with lowercased keys
+	if ( dataTypes[ 1 ] ) {
+		for ( conv in s.converters ) {
+			converters[ conv.toLowerCase() ] = s.converters[ conv ];
+		}
+	}
+
+	current = dataTypes.shift();
+
+	// Convert to each sequential dataType
+	while ( current ) {
+
+		if ( s.responseFields[ current ] ) {
+			jqXHR[ s.responseFields[ current ] ] = response;
+		}
+
+		// Apply the dataFilter if provided
+		if ( !prev && isSuccess && s.dataFilter ) {
+			response = s.dataFilter( response, s.dataType );
+		}
+
+		prev = current;
+		current = dataTypes.shift();
+
+		if ( current ) {
+
+			// There's only work to do if current dataType is non-auto
+			if ( current === "*" ) {
+
+				current = prev;
+
+			// Convert response if prev dataType is non-auto and differs from current
+			} else if ( prev !== "*" && prev !== current ) {
+
+				// Seek a direct converter
+				conv = converters[ prev + " " + current ] || converters[ "* " + current ];
+
+				// If none found, seek a pair
+				if ( !conv ) {
+					for ( conv2 in converters ) {
+
+						// If conv2 outputs current
+						tmp = conv2.split( " " );
+						if ( tmp[ 1 ] === current ) {
+
+							// If prev can be converted to accepted input
+							conv = converters[ prev + " " + tmp[ 0 ] ] ||
+								converters[ "* " + tmp[ 0 ] ];
+							if ( conv ) {
+								// Condense equivalence converters
+								if ( conv === true ) {
+									conv = converters[ conv2 ];
+
+								// Otherwise, insert the intermediate dataType
+								} else if ( converters[ conv2 ] !== true ) {
+									current = tmp[ 0 ];
+									dataTypes.unshift( tmp[ 1 ] );
+								}
+								break;
+							}
+						}
+					}
+				}
+
+				// Apply converter (if not an equivalence)
+				if ( conv !== true ) {
+
+					// Unless errors are allowed to bubble, catch and return them
+					if ( conv && s[ "throws" ] ) {
+						response = conv( response );
+					} else {
+						try {
+							response = conv( response );
+						} catch ( e ) {
+							return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
+						}
+					}
+				}
+			}
+		}
+	}
+
+	return { state: "success", data: response };
+}
+// Install script dataType
+jQuery.ajaxSetup({
+	accepts: {
+		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+	},
+	contents: {
+		script: /(?:java|ecma)script/
+	},
+	converters: {
+		"text script": function( text ) {
+			jQuery.globalEval( text );
+			return text;
+		}
+	}
+});
+
+// Handle cache's special case and global
+jQuery.ajaxPrefilter( "script", function( s ) {
+	if ( s.cache === undefined ) {
+		s.cache = false;
+	}
+	if ( s.crossDomain ) {
+		s.type = "GET";
+		s.global = false;
+	}
+});
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function(s) {
+
+	// This transport only deals with cross domain requests
+	if ( s.crossDomain ) {
+
+		var script,
+			head = document.head || jQuery("head")[0] || document.documentElement;
+
+		return {
+
+			send: function( _, callback ) {
+
+				script = document.createElement("script");
+
+				script.async = true;
+
+				if ( s.scriptCharset ) {
+					script.charset = s.scriptCharset;
+				}
+
+				script.src = s.url;
+
+				// Attach handlers for all browsers
+				script.onload = script.onreadystatechange = function( _, isAbort ) {
+
+					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
+
+						// Handle memory leak in IE
+						script.onload = script.onreadystatechange = null;
+
+						// Remove the script
+						if ( script.parentNode ) {
+							script.parentNode.removeChild( script );
+						}
+
+						// Dereference the script
+						script = null;
+
+						// Callback if not abort
+						if ( !isAbort ) {
+							callback( 200, "success" );
+						}
+					}
+				};
+
+				// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
+				// Use native DOM manipulation to avoid our domManip AJAX trickery
+				head.insertBefore( script, head.firstChild );
+			},
+
+			abort: function() {
+				if ( script ) {
+					script.onload( undefined, true );
+				}
+			}
+		};
+	}
+});
+var oldCallbacks = [],
+	rjsonp = /(=)\?(?=&|$)|\?\?/;
+
+// Default jsonp settings
+jQuery.ajaxSetup({
+	jsonp: "callback",
+	jsonpCallback: function() {
+		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
+		this[ callback ] = true;
+		return callback;
+	}
+});
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
+
+	var callbackName, overwritten, responseContainer,
+		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
+			"url" :
+			typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
+		);
+
+	// Handle iff the expected data type is "jsonp" or we have a parameter to set
+	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
+
+		// Get callback name, remembering preexisting value associated with it
+		callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
+			s.jsonpCallback() :
+			s.jsonpCallback;
+
+		// Insert callback into url or form data
+		if ( jsonProp ) {
+			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
+		} else if ( s.jsonp !== false ) {
+			s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
+		}
+
+		// Use data converter to retrieve json after script execution
+		s.converters["script json"] = function() {
+			if ( !responseContainer ) {
+				jQuery.error( callbackName + " was not called" );
+			}
+			return responseContainer[ 0 ];
+		};
+
+		// force json dataType
+		s.dataTypes[ 0 ] = "json";
+
+		// Install callback
+		overwritten = window[ callbackName ];
+		window[ callbackName ] = function() {
+			responseContainer = arguments;
+		};
+
+		// Clean-up function (fires after converters)
+		jqXHR.always(function() {
+			// Restore preexisting value
+			window[ callbackName ] = overwritten;
+
+			// Save back as free
+			if ( s[ callbackName ] ) {
+				// make sure that re-using the options doesn't screw things around
+				s.jsonpCallback = originalSettings.jsonpCallback;
+
+				// save the callback name for future use
+				oldCallbacks.push( callbackName );
+			}
+
+			// Call if it was a function and we have a response
+			if ( responseContainer && jQuery.isFunction( overwritten ) ) {
+				overwritten( responseContainer[ 0 ] );
+			}
+
+			responseContainer = overwritten = undefined;
+		});
+
+		// Delegate to script
+		return "script";
+	}
+});
+var xhrCallbacks, xhrSupported,
+	xhrId = 0,
+	// #5280: Internet Explorer will keep connections alive if we don't abort on unload
+	xhrOnUnloadAbort = window.ActiveXObject && function() {
+		// Abort all pending requests
+		var key;
+		for ( key in xhrCallbacks ) {
+			xhrCallbacks[ key ]( undefined, true );
+		}
+	};
+
+// Functions to create xhrs
+function createStandardXHR() {
+	try {
+		return new window.XMLHttpRequest();
+	} catch( e ) {}
+}
+
+function createActiveXHR() {
+	try {
+		return new window.ActiveXObject("Microsoft.XMLHTTP");
+	} catch( e ) {}
+}
+
+// Create the request object
+// (This is still attached to ajaxSettings for backward compatibility)
+jQuery.ajaxSettings.xhr = window.ActiveXObject ?
+	/* Microsoft failed to properly
+	 * implement the XMLHttpRequest in IE7 (can't request local files),
+	 * so we use the ActiveXObject when it is available
+	 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
+	 * we need a fallback.
+	 */
+	function() {
+		return !this.isLocal && createStandardXHR() || createActiveXHR();
+	} :
+	// For all other browsers, use the standard XMLHttpRequest object
+	createStandardXHR;
+
+// Determine support properties
+xhrSupported = jQuery.ajaxSettings.xhr();
+jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+xhrSupported = jQuery.support.ajax = !!xhrSupported;
+
+// Create transport if the browser can provide an xhr
+if ( xhrSupported ) {
+
+	jQuery.ajaxTransport(function( s ) {
+		// Cross domain only allowed if supported through XMLHttpRequest
+		if ( !s.crossDomain || jQuery.support.cors ) {
+
+			var callback;
+
+			return {
+				send: function( headers, complete ) {
+
+					// Get a new xhr
+					var handle, i,
+						xhr = s.xhr();
+
+					// Open the socket
+					// Passing null username, generates a login popup on Opera (#2865)
+					if ( s.username ) {
+						xhr.open( s.type, s.url, s.async, s.username, s.password );
+					} else {
+						xhr.open( s.type, s.url, s.async );
+					}
+
+					// Apply custom fields if provided
+					if ( s.xhrFields ) {
+						for ( i in s.xhrFields ) {
+							xhr[ i ] = s.xhrFields[ i ];
+						}
+					}
+
+					// Override mime type if needed
+					if ( s.mimeType && xhr.overrideMimeType ) {
+						xhr.overrideMimeType( s.mimeType );
+					}
+
+					// X-Requested-With header
+					// For cross-domain requests, seeing as conditions for a preflight are
+					// akin to a jigsaw puzzle, we simply never set it to be sure.
+					// (it can always be set on a per-request basis or even using ajaxSetup)
+					// For same-domain requests, won't change header if already provided.
+					if ( !s.crossDomain && !headers["X-Requested-With"] ) {
+						headers["X-Requested-With"] = "XMLHttpRequest";
+					}
+
+					// Need an extra try/catch for cross domain requests in Firefox 3
+					try {
+						for ( i in headers ) {
+							xhr.setRequestHeader( i, headers[ i ] );
+						}
+					} catch( err ) {}
+
+					// Do send the request
+					// This may raise an exception which is actually
+					// handled in jQuery.ajax (so no try/catch here)
+					xhr.send( ( s.hasContent && s.data ) || null );
+
+					// Listener
+					callback = function( _, isAbort ) {
+						var status, responseHeaders, statusText, responses;
+
+						// Firefox throws exceptions when accessing properties
+						// of an xhr when a network error occurred
+						// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
+						try {
+
+							// Was never called and is aborted or complete
+							if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
+
+								// Only called once
+								callback = undefined;
+
+								// Do not keep as active anymore
+								if ( handle ) {
+									xhr.onreadystatechange = jQuery.noop;
+									if ( xhrOnUnloadAbort ) {
+										delete xhrCallbacks[ handle ];
+									}
+								}
+
+								// If it's an abort
+								if ( isAbort ) {
+									// Abort it manually if needed
+									if ( xhr.readyState !== 4 ) {
+										xhr.abort();
+									}
+								} else {
+									responses = {};
+									status = xhr.status;
+									responseHeaders = xhr.getAllResponseHeaders();
+
+									// When requesting binary data, IE6-9 will throw an exception
+									// on any attempt to access responseText (#11426)
+									if ( typeof xhr.responseText === "string" ) {
+										responses.text = xhr.responseText;
+									}
+
+									// Firefox throws an exception when accessing
+									// statusText for faulty cross-domain requests
+									try {
+										statusText = xhr.statusText;
+									} catch( e ) {
+										// We normalize with Webkit giving an empty statusText
+										statusText = "";
+									}
+
+									// Filter status for non standard behaviors
+
+									// If the request is local and we have data: assume a success
+									// (success with no data won't get notified, that's the best we
+									// can do given current implementations)
+									if ( !status && s.isLocal && !s.crossDomain ) {
+										status = responses.text ? 200 : 404;
+									// IE - #1450: sometimes returns 1223 when it should be 204
+									} else if ( status === 1223 ) {
+										status = 204;
+									}
+								}
+							}
+						} catch( firefoxAccessException ) {
+							if ( !isAbort ) {
+								complete( -1, firefoxAccessException );
+							}
+						}
+
+						// Call complete if needed
+						if ( responses ) {
+							complete( status, statusText, responses, responseHeaders );
+						}
+					};
+
+					if ( !s.async ) {
+						// if we're in sync mode we fire the callback
+						callback();
+					} else if ( xhr.readyState === 4 ) {
+						// (IE6 & IE7) if it's in cache and has been
+						// retrieved directly we need to fire the callback
+						setTimeout( callback );
+					} else {
+						handle = ++xhrId;
+						if ( xhrOnUnloadAbort ) {
+							// Create the active xhrs callbacks list if needed
+							// and attach the unload handler
+							if ( !xhrCallbacks ) {
+								xhrCallbacks = {};
+								jQuery( window ).unload( xhrOnUnloadAbort );
+							}
+							// Add to list of active xhrs callbacks
+							xhrCallbacks[ handle ] = callback;
+						}
+						xhr.onreadystatechange = callback;
+					}
+				},
+
+				abort: function() {
+					if ( callback ) {
+						callback( undefined, true );
+					}
+				}
+			};
+		}
+	});
+}
+var fxNow, timerId,
+	rfxtypes = /^(?:toggle|show|hide)$/,
+	rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
+	rrun = /queueHooks$/,
+	animationPrefilters = [ defaultPrefilter ],
+	tweeners = {
+		"*": [function( prop, value ) {
+			var tween = this.createTween( prop, value ),
+				target = tween.cur(),
+				parts = rfxnum.exec( value ),
+				unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
+
+				// Starting value computation is required for potential unit mismatches
+				start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
+					rfxnum.exec( jQuery.css( tween.elem, prop ) ),
+				scale = 1,
+				maxIterations = 20;
+
+			if ( start && start[ 3 ] !== unit ) {
+				// Trust units reported by jQuery.css
+				unit = unit || start[ 3 ];
+
+				// Make sure we update the tween properties later on
+				parts = parts || [];
+
+				// Iteratively approximate from a nonzero starting point
+				start = +target || 1;
+
+				do {
+					// If previous iteration zeroed out, double until we get *something*
+					// Use a string for doubling factor so we don't accidentally see scale as unchanged below
+					scale = scale || ".5";
+
+					// Adjust and apply
+					start = start / scale;
+					jQuery.style( tween.elem, prop, start + unit );
+
+				// Update scale, tolerating zero or NaN from tween.cur()
+				// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
+				} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
+			}
+
+			// Update tween properties
+			if ( parts ) {
+				start = tween.start = +start || +target || 0;
+				tween.unit = unit;
+				// If a +=/-= token was provided, we're doing a relative animation
+				tween.end = parts[ 1 ] ?
+					start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+					+parts[ 2 ];
+			}
+
+			return tween;
+		}]
+	};
+
+// Animations created synchronously will run synchronously
+function createFxNow() {
+	setTimeout(function() {
+		fxNow = undefined;
+	});
+	return ( fxNow = jQuery.now() );
+}
+
+function createTween( value, prop, animation ) {
+	var tween,
+		collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
+		index = 0,
+		length = collection.length;
+	for ( ; index < length; index++ ) {
+		if ( (tween = collection[ index ].call( animation, prop, value )) ) {
+
+			// we're done with this property
+			return tween;
+		}
+	}
+}
+
+function Animation( elem, properties, options ) {
+	var result,
+		stopped,
+		index = 0,
+		length = animationPrefilters.length,
+		deferred = jQuery.Deferred().always( function() {
+			// don't match elem in the :animated selector
+			delete tick.elem;
+		}),
+		tick = function() {
+			if ( stopped ) {
+				return false;
+			}
+			var currentTime = fxNow || createFxNow(),
+				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
+				// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
+				temp = remaining / animation.duration || 0,
+				percent = 1 - temp,
+				index = 0,
+				length = animation.tweens.length;
+
+			for ( ; index < length ; index++ ) {
+				animation.tweens[ index ].run( percent );
+			}
+
+			deferred.notifyWith( elem, [ animation, percent, remaining ]);
+
+			if ( percent < 1 && length ) {
+				return remaining;
+			} else {
+				deferred.resolveWith( elem, [ animation ] );
+				return false;
+			}
+		},
+		animation = deferred.promise({
+			elem: elem,
+			props: jQuery.extend( {}, properties ),
+			opts: jQuery.extend( true, { specialEasing: {} }, options ),
+			originalProperties: properties,
+			originalOptions: options,
+			startTime: fxNow || createFxNow(),
+			duration: options.duration,
+			tweens: [],
+			createTween: function( prop, end ) {
+				var tween = jQuery.Tween( elem, animation.opts, prop, end,
+						animation.opts.specialEasing[ prop ] || animation.opts.easing );
+				animation.tweens.push( tween );
+				return tween;
+			},
+			stop: function( gotoEnd ) {
+				var index = 0,
+					// if we are going to the end, we want to run all the tweens
+					// otherwise we skip this part
+					length = gotoEnd ? animation.tweens.length : 0;
+				if ( stopped ) {
+					return this;
+				}
+				stopped = true;
+				for ( ; index < length ; index++ ) {
+					animation.tweens[ index ].run( 1 );
+				}
+
+				// resolve when we played the last frame
+				// otherwise, reject
+				if ( gotoEnd ) {
+					deferred.resolveWith( elem, [ animation, gotoEnd ] );
+				} else {
+					deferred.rejectWith( elem, [ animation, gotoEnd ] );
+				}
+				return this;
+			}
+		}),
+		props = animation.props;
+
+	propFilter( props, animation.opts.specialEasing );
+
+	for ( ; index < length ; index++ ) {
+		result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
+		if ( result ) {
+			return result;
+		}
+	}
+
+	jQuery.map( props, createTween, animation );
+
+	if ( jQuery.isFunction( animation.opts.start ) ) {
+		animation.opts.start.call( elem, animation );
+	}
+
+	jQuery.fx.timer(
+		jQuery.extend( tick, {
+			elem: elem,
+			anim: animation,
+			queue: animation.opts.queue
+		})
+	);
+
+	// attach callbacks from options
+	return animation.progress( animation.opts.progress )
+		.done( animation.opts.done, animation.opts.complete )
+		.fail( animation.opts.fail )
+		.always( animation.opts.always );
+}
+
+function propFilter( props, specialEasing ) {
+	var index, name, easing, value, hooks;
+
+	// camelCase, specialEasing and expand cssHook pass
+	for ( index in props ) {
+		name = jQuery.camelCase( index );
+		easing = specialEasing[ name ];
+		value = props[ index ];
+		if ( jQuery.isArray( value ) ) {
+			easing = value[ 1 ];
+			value = props[ index ] = value[ 0 ];
+		}
+
+		if ( index !== name ) {
+			props[ name ] = value;
+			delete props[ index ];
+		}
+
+		hooks = jQuery.cssHooks[ name ];
+		if ( hooks && "expand" in hooks ) {
+			value = hooks.expand( value );
+			delete props[ name ];
+
+			// not quite $.extend, this wont overwrite keys already present.
+			// also - reusing 'index' from above because we have the correct "name"
+			for ( index in value ) {
+				if ( !( index in props ) ) {
+					props[ index ] = value[ index ];
+					specialEasing[ index ] = easing;
+				}
+			}
+		} else {
+			specialEasing[ name ] = easing;
+		}
+	}
+}
+
+jQuery.Animation = jQuery.extend( Animation, {
+
+	tweener: function( props, callback ) {
+		if ( jQuery.isFunction( props ) ) {
+			callback = props;
+			props = [ "*" ];
+		} else {
+			props = props.split(" ");
+		}
+
+		var prop,
+			index = 0,
+			length = props.length;
+
+		for ( ; index < length ; index++ ) {
+			prop = props[ index ];
+			tweeners[ prop ] = tweeners[ prop ] || [];
+			tweeners[ prop ].unshift( callback );
+		}
+	},
+
+	prefilter: function( callback, prepend ) {
+		if ( prepend ) {
+			animationPrefilters.unshift( callback );
+		} else {
+			animationPrefilters.push( callback );
+		}
+	}
+});
+
+function defaultPrefilter( elem, props, opts ) {
+	/* jshint validthis: true */
+	var prop, value, toggle, tween, hooks, oldfire,
+		anim = this,
+		orig = {},
+		style = elem.style,
+		hidden = elem.nodeType && isHidden( elem ),
+		dataShow = jQuery._data( elem, "fxshow" );
+
+	// handle queue: false promises
+	if ( !opts.queue ) {
+		hooks = jQuery._queueHooks( elem, "fx" );
+		if ( hooks.unqueued == null ) {
+			hooks.unqueued = 0;
+			oldfire = hooks.empty.fire;
+			hooks.empty.fire = function() {
+				if ( !hooks.unqueued ) {
+					oldfire();
+				}
+			};
+		}
+		hooks.unqueued++;
+
+		anim.always(function() {
+			// doing this makes sure that the complete handler will be called
+			// before this completes
+			anim.always(function() {
+				hooks.unqueued--;
+				if ( !jQuery.queue( elem, "fx" ).length ) {
+					hooks.empty.fire();
+				}
+			});
+		});
+	}
+
+	// height/width overflow pass
+	if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
+		// Make sure that nothing sneaks out
+		// Record all 3 overflow attributes because IE does not
+		// change the overflow attribute when overflowX and
+		// overflowY are set to the same value
+		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
+
+		// Set display property to inline-block for height/width
+		// animations on inline elements that are having width/height animated
+		if ( jQuery.css( elem, "display" ) === "inline" &&
+				jQuery.css( elem, "float" ) === "none" ) {
+
+			// inline-level elements accept inline-block;
+			// block-level elements need to be inline with layout
+			if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
+				style.display = "inline-block";
+
+			} else {
+				style.zoom = 1;
+			}
+		}
+	}
+
+	if ( opts.overflow ) {
+		style.overflow = "hidden";
+		if ( !jQuery.support.shrinkWrapBlocks ) {
+			anim.always(function() {
+				style.overflow = opts.overflow[ 0 ];
+				style.overflowX = opts.overflow[ 1 ];
+				style.overflowY = opts.overflow[ 2 ];
+			});
+		}
+	}
+
+
+	// show/hide pass
+	for ( prop in props ) {
+		value = props[ prop ];
+		if ( rfxtypes.exec( value ) ) {
+			delete props[ prop ];
+			toggle = toggle || value === "toggle";
+			if ( value === ( hidden ? "hide" : "show" ) ) {
+				continue;
+			}
+			orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
+		}
+	}
+
+	if ( !jQuery.isEmptyObject( orig ) ) {
+		if ( dataShow ) {
+			if ( "hidden" in dataShow ) {
+				hidden = dataShow.hidden;
+			}
+		} else {
+			dataShow = jQuery._data( elem, "fxshow", {} );
+		}
+
+		// store state if its toggle - enables .stop().toggle() to "reverse"
+		if ( toggle ) {
+			dataShow.hidden = !hidden;
+		}
+		if ( hidden ) {
+			jQuery( elem ).show();
+		} else {
+			anim.done(function() {
+				jQuery( elem ).hide();
+			});
+		}
+		anim.done(function() {
+			var prop;
+			jQuery._removeData( elem, "fxshow" );
+			for ( prop in orig ) {
+				jQuery.style( elem, prop, orig[ prop ] );
+			}
+		});
+		for ( prop in orig ) {
+			tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
+
+			if ( !( prop in dataShow ) ) {
+				dataShow[ prop ] = tween.start;
+				if ( hidden ) {
+					tween.end = tween.start;
+					tween.start = prop === "width" || prop === "height" ? 1 : 0;
+				}
+			}
+		}
+	}
+}
+
+function Tween( elem, options, prop, end, easing ) {
+	return new Tween.prototype.init( elem, options, prop, end, easing );
+}
+jQuery.Tween = Tween;
+
+Tween.prototype = {
+	constructor: Tween,
+	init: function( elem, options, prop, end, easing, unit ) {
+		this.elem = elem;
+		this.prop = prop;
+		this.easing = easing || "swing";
+		this.options = options;
+		this.start = this.now = this.cur();
+		this.end = end;
+		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
+	},
+	cur: function() {
+		var hooks = Tween.propHooks[ this.prop ];
+
+		return hooks && hooks.get ?
+			hooks.get( this ) :
+			Tween.propHooks._default.get( this );
+	},
+	run: function( percent ) {
+		var eased,
+			hooks = Tween.propHooks[ this.prop ];
+
+		if ( this.options.duration ) {
+			this.pos = eased = jQuery.easing[ this.easing ](
+				percent, this.options.duration * percent, 0, 1, this.options.duration
+			);
+		} else {
+			this.pos = eased = percent;
+		}
+		this.now = ( this.end - this.start ) * eased + this.start;
+
+		if ( this.options.step ) {
+			this.options.step.call( this.elem, this.now, this );
+		}
+
+		if ( hooks && hooks.set ) {
+			hooks.set( this );
+		} else {
+			Tween.propHooks._default.set( this );
+		}
+		return this;
+	}
+};
+
+Tween.prototype.init.prototype = Tween.prototype;
+
+Tween.propHooks = {
+	_default: {
+		get: function( tween ) {
+			var result;
+
+			if ( tween.elem[ tween.prop ] != null &&
+				(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
+				return tween.elem[ tween.prop ];
+			}
+
+			// passing an empty string as a 3rd parameter to .css will automatically
+			// attempt a parseFloat and fallback to a string if the parse fails
+			// so, simple values such as "10px" are parsed to Float.
+			// complex values such as "rotate(1rad)" are returned as is.
+			result = jQuery.css( tween.elem, tween.prop, "" );
+			// Empty strings, null, undefined and "auto" are converted to 0.
+			return !result || result === "auto" ? 0 : result;
+		},
+		set: function( tween ) {
+			// use step hook for back compat - use cssHook if its there - use .style if its
+			// available and use plain properties where available
+			if ( jQuery.fx.step[ tween.prop ] ) {
+				jQuery.fx.step[ tween.prop ]( tween );
+			} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
+				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
+			} else {
+				tween.elem[ tween.prop ] = tween.now;
+			}
+		}
+	}
+};
+
+// Support: IE <=9
+// Panic based approach to setting things on disconnected nodes
+
+Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
+	set: function( tween ) {
+		if ( tween.elem.nodeType && tween.elem.parentNode ) {
+			tween.elem[ tween.prop ] = tween.now;
+		}
+	}
+};
+
+jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
+	var cssFn = jQuery.fn[ name ];
+	jQuery.fn[ name ] = function( speed, easing, callback ) {
+		return speed == null || typeof speed === "boolean" ?
+			cssFn.apply( this, arguments ) :
+			this.animate( genFx( name, true ), speed, easing, callback );
+	};
+});
+
+jQuery.fn.extend({
+	fadeTo: function( speed, to, easing, callback ) {
+
+		// show any hidden elements after setting opacity to 0
+		return this.filter( isHidden ).css( "opacity", 0 ).show()
+
+			// animate to the value specified
+			.end().animate({ opacity: to }, speed, easing, callback );
+	},
+	animate: function( prop, speed, easing, callback ) {
+		var empty = jQuery.isEmptyObject( prop ),
+			optall = jQuery.speed( speed, easing, callback ),
+			doAnimation = function() {
+				// Operate on a copy of prop so per-property easing won't be lost
+				var anim = Animation( this, jQuery.extend( {}, prop ), optall );
+
+				// Empty animations, or finishing resolves immediately
+				if ( empty || jQuery._data( this, "finish" ) ) {
+					anim.stop( true );
+				}
+			};
+			doAnimation.finish = doAnimation;
+
+		return empty || optall.queue === false ?
+			this.each( doAnimation ) :
+			this.queue( optall.queue, doAnimation );
+	},
+	stop: function( type, clearQueue, gotoEnd ) {
+		var stopQueue = function( hooks ) {
+			var stop = hooks.stop;
+			delete hooks.stop;
+			stop( gotoEnd );
+		};
+
+		if ( typeof type !== "string" ) {
+			gotoEnd = clearQueue;
+			clearQueue = type;
+			type = undefined;
+		}
+		if ( clearQueue && type !== false ) {
+			this.queue( type || "fx", [] );
+		}
+
+		return this.each(function() {
+			var dequeue = true,
+				index = type != null && type + "queueHooks",
+				timers = jQuery.timers,
+				data = jQuery._data( this );
+
+			if ( index ) {
+				if ( data[ index ] && data[ index ].stop ) {
+					stopQueue( data[ index ] );
+				}
+			} else {
+				for ( index in data ) {
+					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
+						stopQueue( data[ index ] );
+					}
+				}
+			}
+
+			for ( index = timers.length; index--; ) {
+				if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
+					timers[ index ].anim.stop( gotoEnd );
+					dequeue = false;
+					timers.splice( index, 1 );
+				}
+			}
+
+			// start the next in the queue if the last step wasn't forced
+			// timers currently will call their complete callbacks, which will dequeue
+			// but only if they were gotoEnd
+			if ( dequeue || !gotoEnd ) {
+				jQuery.dequeue( this, type );
+			}
+		});
+	},
+	finish: function( type ) {
+		if ( type !== false ) {
+			type = type || "fx";
+		}
+		return this.each(function() {
+			var index,
+				data = jQuery._data( this ),
+				queue = data[ type + "queue" ],
+				hooks = data[ type + "queueHooks" ],
+				timers = jQuery.timers,
+				length = queue ? queue.length : 0;
+
+			// enable finishing flag on private data
+			data.finish = true;
+
+			// empty the queue first
+			jQuery.queue( this, type, [] );
+
+			if ( hooks && hooks.stop ) {
+				hooks.stop.call( this, true );
+			}
+
+			// look for any active animations, and finish them
+			for ( index = timers.length; index--; ) {
+				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
+					timers[ index ].anim.stop( true );
+					timers.splice( index, 1 );
+				}
+			}
+
+			// look for any animations in the old queue and finish them
+			for ( index = 0; index < length; index++ ) {
+				if ( queue[ index ] && queue[ index ].finish ) {
+					queue[ index ].finish.call( this );
+				}
+			}
+
+			// turn off finishing flag
+			delete data.finish;
+		});
+	}
+});
+
+// Generate parameters to create a standard animation
+function genFx( type, includeWidth ) {
+	var which,
+		attrs = { height: type },
+		i = 0;
+
+	// if we include width, step value is 1 to do all cssExpand values,
+	// if we don't include width, step value is 2 to skip over Left and Right
+	includeWidth = includeWidth? 1 : 0;
+	for( ; i < 4 ; i += 2 - includeWidth ) {
+		which = cssExpand[ i ];
+		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
+	}
+
+	if ( includeWidth ) {
+		attrs.opacity = attrs.width = type;
+	}
+
+	return attrs;
+}
+
+// Generate shortcuts for custom animations
+jQuery.each({
+	slideDown: genFx("show"),
+	slideUp: genFx("hide"),
+	slideToggle: genFx("toggle"),
+	fadeIn: { opacity: "show" },
+	fadeOut: { opacity: "hide" },
+	fadeToggle: { opacity: "toggle" }
+}, function( name, props ) {
+	jQuery.fn[ name ] = function( speed, easing, callback ) {
+		return this.animate( props, speed, easing, callback );
+	};
+});
+
+jQuery.speed = function( speed, easing, fn ) {
+	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
+		complete: fn || !fn && easing ||
+			jQuery.isFunction( speed ) && speed,
+		duration: speed,
+		easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
+	};
+
+	opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+		opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
+
+	// normalize opt.queue - true/undefined/null -> "fx"
+	if ( opt.queue == null || opt.queue === true ) {
+		opt.queue = "fx";
+	}
+
+	// Queueing
+	opt.old = opt.complete;
+
+	opt.complete = function() {
+		if ( jQuery.isFunction( opt.old ) ) {
+			opt.old.call( this );
+		}
+
+		if ( opt.queue ) {
+			jQuery.dequeue( this, opt.queue );
+		}
+	};
+
+	return opt;
+};
+
+jQuery.easing = {
+	linear: function( p ) {
+		return p;
+	},
+	swing: function( p ) {
+		return 0.5 - Math.cos( p*Math.PI ) / 2;
+	}
+};
+
+jQuery.timers = [];
+jQuery.fx = Tween.prototype.init;
+jQuery.fx.tick = function() {
+	var timer,
+		timers = jQuery.timers,
+		i = 0;
+
+	fxNow = jQuery.now();
+
+	for ( ; i < timers.length; i++ ) {
+		timer = timers[ i ];
+		// Checks the timer has not already been removed
+		if ( !timer() && timers[ i ] === timer ) {
+			timers.splice( i--, 1 );
+		}
+	}
+
+	if ( !timers.length ) {
+		jQuery.fx.stop();
+	}
+	fxNow = undefined;
+};
+
+jQuery.fx.timer = function( timer ) {
+	if ( timer() && jQuery.timers.push( timer ) ) {
+		jQuery.fx.start();
+	}
+};
+
+jQuery.fx.interval = 13;
+
+jQuery.fx.start = function() {
+	if ( !timerId ) {
+		timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
+	}
+};
+
+jQuery.fx.stop = function() {
+	clearInterval( timerId );
+	timerId = null;
+};
+
+jQuery.fx.speeds = {
+	slow: 600,
+	fast: 200,
+	// Default speed
+	_default: 400
+};
+
+// Back Compat <1.8 extension point
+jQuery.fx.step = {};
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+	jQuery.expr.filters.animated = function( elem ) {
+		return jQuery.grep(jQuery.timers, function( fn ) {
+			return elem === fn.elem;
+		}).length;
+	};
+}
+jQuery.fn.offset = function( options ) {
+	if ( arguments.length ) {
+		return options === undefined ?
+			this :
+			this.each(function( i ) {
+				jQuery.offset.setOffset( this, options, i );
+			});
+	}
+
+	var docElem, win,
+		box = { top: 0, left: 0 },
+		elem = this[ 0 ],
+		doc = elem && elem.ownerDocument;
+
+	if ( !doc ) {
+		return;
+	}
+
+	docElem = doc.documentElement;
+
+	// Make sure it's not a disconnected DOM node
+	if ( !jQuery.contains( docElem, elem ) ) {
+		return box;
+	}
+
+	// If we don't have gBCR, just use 0,0 rather than error
+	// BlackBerry 5, iOS 3 (original iPhone)
+	if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
+		box = elem.getBoundingClientRect();
+	}
+	win = getWindow( doc );
+	return {
+		top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
+		left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
+	};
+};
+
+jQuery.offset = {
+
+	setOffset: function( elem, options, i ) {
+		var position = jQuery.css( elem, "position" );
+
+		// set position first, in-case top/left are set even on static elem
+		if ( position === "static" ) {
+			elem.style.position = "relative";
+		}
+
+		var curElem = jQuery( elem ),
+			curOffset = curElem.offset(),
+			curCSSTop = jQuery.css( elem, "top" ),
+			curCSSLeft = jQuery.css( elem, "left" ),
+			calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
+			props = {}, curPosition = {}, curTop, curLeft;
+
+		// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
+		if ( calculatePosition ) {
+			curPosition = curElem.position();
+			curTop = curPosition.top;
+			curLeft = curPosition.left;
+		} else {
+			curTop = parseFloat( curCSSTop ) || 0;
+			curLeft = parseFloat( curCSSLeft ) || 0;
+		}
+
+		if ( jQuery.isFunction( options ) ) {
+			options = options.call( elem, i, curOffset );
+		}
+
+		if ( options.top != null ) {
+			props.top = ( options.top - curOffset.top ) + curTop;
+		}
+		if ( options.left != null ) {
+			props.left = ( options.left - curOffset.left ) + curLeft;
+		}
+
+		if ( "using" in options ) {
+			options.using.call( elem, props );
+		} else {
+			curElem.css( props );
+		}
+	}
+};
+
+
+jQuery.fn.extend({
+
+	position: function() {
+		if ( !this[ 0 ] ) {
+			return;
+		}
+
+		var offsetParent, offset,
+			parentOffset = { top: 0, left: 0 },
+			elem = this[ 0 ];
+
+		// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
+		if ( jQuery.css( elem, "position" ) === "fixed" ) {
+			// we assume that getBoundingClientRect is available when computed position is fixed
+			offset = elem.getBoundingClientRect();
+		} else {
+			// Get *real* offsetParent
+			offsetParent = this.offsetParent();
+
+			// Get correct offsets
+			offset = this.offset();
+			if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
+				parentOffset = offsetParent.offset();
+			}
+
+			// Add offsetParent borders
+			parentOffset.top  += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
+			parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
+		}
+
+		// Subtract parent offsets and element margins
+		// note: when an element has margin: auto the offsetLeft and marginLeft
+		// are the same in Safari causing offset.left to incorrectly be 0
+		return {
+			top:  offset.top  - parentOffset.top - jQuery.css( elem, "marginTop", true ),
+			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
+		};
+	},
+
+	offsetParent: function() {
+		return this.map(function() {
+			var offsetParent = this.offsetParent || docElem;
+			while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
+				offsetParent = offsetParent.offsetParent;
+			}
+			return offsetParent || docElem;
+		});
+	}
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
+	var top = /Y/.test( prop );
+
+	jQuery.fn[ method ] = function( val ) {
+		return jQuery.access( this, function( elem, method, val ) {
+			var win = getWindow( elem );
+
+			if ( val === undefined ) {
+				return win ? (prop in win) ? win[ prop ] :
+					win.document.documentElement[ method ] :
+					elem[ method ];
+			}
+
+			if ( win ) {
+				win.scrollTo(
+					!top ? val : jQuery( win ).scrollLeft(),
+					top ? val : jQuery( win ).scrollTop()
+				);
+
+			} else {
+				elem[ method ] = val;
+			}
+		}, method, val, arguments.length, null );
+	};
+});
+
+function getWindow( elem ) {
+	return jQuery.isWindow( elem ) ?
+		elem :
+		elem.nodeType === 9 ?
+			elem.defaultView || elem.parentWindow :
+			false;
+}
+// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
+jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
+	jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
+		// margin is only for outerHeight, outerWidth
+		jQuery.fn[ funcName ] = function( margin, value ) {
+			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
+				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
+
+			return jQuery.access( this, function( elem, type, value ) {
+				var doc;
+
+				if ( jQuery.isWindow( elem ) ) {
+					// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
+					// isn't a whole lot we can do. See pull request at this URL for discussion:
+					// https://github.com/jquery/jquery/pull/764
+					return elem.document.documentElement[ "client" + name ];
+				}
+
+				// Get document width or height
+				if ( elem.nodeType === 9 ) {
+					doc = elem.documentElement;
+
+					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
+					// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
+					return Math.max(
+						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
+						elem.body[ "offset" + name ], doc[ "offset" + name ],
+						doc[ "client" + name ]
+					);
+				}
+
+				return value === undefined ?
+					// Get width or height on the element, requesting but not forcing parseFloat
+					jQuery.css( elem, type, extra ) :
+
+					// Set width or height on the element
+					jQuery.style( elem, type, value, extra );
+			}, type, chainable ? margin : undefined, chainable, null );
+		};
+	});
+});
+// Limit scope pollution from any deprecated API
+// (function() {
+
+// The number of elements contained in the matched element set
+jQuery.fn.size = function() {
+	return this.length;
+};
+
+jQuery.fn.andSelf = jQuery.fn.addBack;
+
+// })();
+if ( typeof module === "object" && module && typeof module.exports === "object" ) {
+	// Expose jQuery as module.exports in loaders that implement the Node
+	// module pattern (including browserify). Do not create the global, since
+	// the user will be storing it themselves locally, and globals are frowned
+	// upon in the Node module world.
+	module.exports = jQuery;
+} else {
+	// Otherwise expose jQuery to the global object as usual
+	window.jQuery = window.$ = jQuery;
+
+	// Register as a named AMD module, since jQuery can be concatenated with other
+	// files that may use define, but not via a proper concatenation script that
+	// understands anonymous AMD modules. A named AMD is safest and most robust
+	// way to register. Lowercase jquery is used because AMD module names are
+	// derived from file names, and jQuery is normally delivered in a lowercase
+	// file name. Do this after creating the global so that if an AMD module wants
+	// to call noConflict to hide this version of jQuery, it will work.
+	if ( typeof define === "function" && define.amd ) {
+		define( "jquery", [], function () { return jQuery; } );
+	}
+}
+
+})( window );
diff --git a/static/js/json2.js b/static/js/json2.js
new file mode 100644
--- /dev/null
+++ b/static/js/json2.js
@@ -0,0 +1,486 @@
+/*
+    json2.js
+    2013-05-26
+
+    Public Domain.
+
+    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+    See http://www.JSON.org/js.html
+
+
+    This code should be minified before deployment.
+    See http://javascript.crockford.com/jsmin.html
+
+    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+    NOT CONTROL.
+
+
+    This file creates a global JSON object containing two methods: stringify
+    and parse.
+
+        JSON.stringify(value, replacer, space)
+            value       any JavaScript value, usually an object or array.
+
+            replacer    an optional parameter that determines how object
+                        values are stringified for objects. It can be a
+                        function or an array of strings.
+
+            space       an optional parameter that specifies the indentation
+                        of nested structures. If it is omitted, the text will
+                        be packed without extra whitespace. If it is a number,
+                        it will specify the number of spaces to indent at each
+                        level. If it is a string (such as '\t' or '&nbsp;'),
+                        it contains the characters used to indent at each level.
+
+            This method produces a JSON text from a JavaScript value.
+
+            When an object value is found, if the object contains a toJSON
+            method, its toJSON method will be called and the result will be
+            stringified. A toJSON method does not serialize: it returns the
+            value represented by the name/value pair that should be serialized,
+            or undefined if nothing should be serialized. The toJSON method
+            will be passed the key associated with the value, and this will be
+            bound to the value
+
+            For example, this would serialize Dates as ISO strings.
+
+                Date.prototype.toJSON = function (key) {
+                    function f(n) {
+                        // Format integers to have at least two digits.
+                        return n < 10 ? '0' + n : n;
+                    }
+
+                    return this.getUTCFullYear()   + '-' +
+                         f(this.getUTCMonth() + 1) + '-' +
+                         f(this.getUTCDate())      + 'T' +
+                         f(this.getUTCHours())     + ':' +
+                         f(this.getUTCMinutes())   + ':' +
+                         f(this.getUTCSeconds())   + 'Z';
+                };
+
+            You can provide an optional replacer method. It will be passed the
+            key and value of each member, with this bound to the containing
+            object. The value that is returned from your method will be
+            serialized. If your method returns undefined, then the member will
+            be excluded from the serialization.
+
+            If the replacer parameter is an array of strings, then it will be
+            used to select the members to be serialized. It filters the results
+            such that only members with keys listed in the replacer array are
+            stringified.
+
+            Values that do not have JSON representations, such as undefined or
+            functions, will not be serialized. Such values in objects will be
+            dropped; in arrays they will be replaced with null. You can use
+            a replacer function to replace those with JSON values.
+            JSON.stringify(undefined) returns undefined.
+
+            The optional space parameter produces a stringification of the
+            value that is filled with line breaks and indentation to make it
+            easier to read.
+
+            If the space parameter is a non-empty string, then that string will
+            be used for indentation. If the space parameter is a number, then
+            the indentation will be that many spaces.
+
+            Example:
+
+            text = JSON.stringify(['e', {pluribus: 'unum'}]);
+            // text is '["e",{"pluribus":"unum"}]'
+
+
+            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+            text = JSON.stringify([new Date()], function (key, value) {
+                return this[key] instanceof Date ?
+                    'Date(' + this[key] + ')' : value;
+            });
+            // text is '["Date(---current time---)"]'
+
+
+        JSON.parse(text, reviver)
+            This method parses a JSON text to produce an object or array.
+            It can throw a SyntaxError exception.
+
+            The optional reviver parameter is a function that can filter and
+            transform the results. It receives each of the keys and values,
+            and its return value is used instead of the original value.
+            If it returns what it received, then the structure is not modified.
+            If it returns undefined then the member is deleted.
+
+            Example:
+
+            // Parse the text. Values that look like ISO date strings will
+            // be converted to Date objects.
+
+            myData = JSON.parse(text, function (key, value) {
+                var a;
+                if (typeof value === 'string') {
+                    a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+                    if (a) {
+                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+                            +a[5], +a[6]));
+                    }
+                }
+                return value;
+            });
+
+            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+                var d;
+                if (typeof value === 'string' &&
+                        value.slice(0, 5) === 'Date(' &&
+                        value.slice(-1) === ')') {
+                    d = new Date(value.slice(5, -1));
+                    if (d) {
+                        return d;
+                    }
+                }
+                return value;
+            });
+
+
+    This is a reference implementation. You are free to copy, modify, or
+    redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+    lastIndex, length, parse, prototype, push, replace, slice, stringify,
+    test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+    JSON = {};
+}
+
+(function () {
+    'use strict';
+
+    function f(n) {
+        // Format integers to have at least two digits.
+        return n < 10 ? '0' + n : n;
+    }
+
+    if (typeof Date.prototype.toJSON !== 'function') {
+
+        Date.prototype.toJSON = function () {
+
+            return isFinite(this.valueOf())
+                ? this.getUTCFullYear()     + '-' +
+                    f(this.getUTCMonth() + 1) + '-' +
+                    f(this.getUTCDate())      + 'T' +
+                    f(this.getUTCHours())     + ':' +
+                    f(this.getUTCMinutes())   + ':' +
+                    f(this.getUTCSeconds())   + 'Z'
+                : null;
+        };
+
+        String.prototype.toJSON      =
+            Number.prototype.toJSON  =
+            Boolean.prototype.toJSON = function () {
+                return this.valueOf();
+            };
+    }
+
+    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+        gap,
+        indent,
+        meta = {    // table of character substitutions
+            '\b': '\\b',
+            '\t': '\\t',
+            '\n': '\\n',
+            '\f': '\\f',
+            '\r': '\\r',
+            '"' : '\\"',
+            '\\': '\\\\'
+        },
+        rep;
+
+
+    function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+        escapable.lastIndex = 0;
+        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+            var c = meta[a];
+            return typeof c === 'string'
+                ? c
+                : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+        }) + '"' : '"' + string + '"';
+    }
+
+
+    function str(key, holder) {
+
+// Produce a string from holder[key].
+
+        var i,          // The loop counter.
+            k,          // The member key.
+            v,          // The member value.
+            length,
+            mind = gap,
+            partial,
+            value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+        if (value && typeof value === 'object' &&
+                typeof value.toJSON === 'function') {
+            value = value.toJSON(key);
+        }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+        if (typeof rep === 'function') {
+            value = rep.call(holder, key, value);
+        }
+
+// What happens next depends on the value's type.
+
+        switch (typeof value) {
+        case 'string':
+            return quote(value);
+
+        case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+            return isFinite(value) ? String(value) : 'null';
+
+        case 'boolean':
+        case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+            return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+        case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+            if (!value) {
+                return 'null';
+            }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+            gap += indent;
+            partial = [];
+
+// Is the value an array?
+
+            if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+                length = value.length;
+                for (i = 0; i < length; i += 1) {
+                    partial[i] = str(i, value) || 'null';
+                }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+                v = partial.length === 0
+                    ? '[]'
+                    : gap
+                    ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+                    : '[' + partial.join(',') + ']';
+                gap = mind;
+                return v;
+            }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+            if (rep && typeof rep === 'object') {
+                length = rep.length;
+                for (i = 0; i < length; i += 1) {
+                    if (typeof rep[i] === 'string') {
+                        k = rep[i];
+                        v = str(k, value);
+                        if (v) {
+                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
+                        }
+                    }
+                }
+            } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+                for (k in value) {
+                    if (Object.prototype.hasOwnProperty.call(value, k)) {
+                        v = str(k, value);
+                        if (v) {
+                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
+                        }
+                    }
+                }
+            }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+            v = partial.length === 0
+                ? '{}'
+                : gap
+                ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+                : '{' + partial.join(',') + '}';
+            gap = mind;
+            return v;
+        }
+    }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+    if (typeof JSON.stringify !== 'function') {
+        JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+            var i;
+            gap = '';
+            indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+            if (typeof space === 'number') {
+                for (i = 0; i < space; i += 1) {
+                    indent += ' ';
+                }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+            } else if (typeof space === 'string') {
+                indent = space;
+            }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+            rep = replacer;
+            if (replacer && typeof replacer !== 'function' &&
+                    (typeof replacer !== 'object' ||
+                    typeof replacer.length !== 'number')) {
+                throw new Error('JSON.stringify');
+            }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+            return str('', {'': value});
+        };
+    }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+    if (typeof JSON.parse !== 'function') {
+        JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+            var j;
+
+            function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+                var k, v, value = holder[key];
+                if (value && typeof value === 'object') {
+                    for (k in value) {
+                        if (Object.prototype.hasOwnProperty.call(value, k)) {
+                            v = walk(value, k);
+                            if (v !== undefined) {
+                                value[k] = v;
+                            } else {
+                                delete value[k];
+                            }
+                        }
+                    }
+                }
+                return reviver.call(holder, key, value);
+            }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+            text = String(text);
+            cx.lastIndex = 0;
+            if (cx.test(text)) {
+                text = text.replace(cx, function (a) {
+                    return '\\u' +
+                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+                });
+            }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+            if (/^[\],:{}\s]*$/
+                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+                j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+                return typeof reviver === 'function'
+                    ? walk({'': j}, '')
+                    : j;
+            }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+            throw new SyntaxError('JSON.parse');
+        };
+    }
+}());
diff --git a/static/js/map.js b/static/js/map.js
new file mode 100644
--- /dev/null
+++ b/static/js/map.js
@@ -0,0 +1,384 @@
+// Creates a mouse handler that calculates client coordinates before calling the real handler.
+function mkClientMouseEvent(handler, elem) {
+	return function(evt) {
+		var parentOffset = $(elem).offset();
+		evt.elemX = evt.pageX - parentOffset.left;
+		evt.elemY = evt.pageY - parentOffset.top;
+		handler(evt);
+	};
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// class Map
+///////////////////////////////////////////////////////////////////////////////
+function Map(canvas, numX, numY, cellSize, shipDef) {
+	var drag = new MouseDrag(canvas, 4);
+	var render = new Render(canvas, numX, numY, cellSize);
+	var that = this; // this-reference for callbacks
+	// convert between grid and canvas coordinates
+	var toC = function(gridCoord) { return gridCoord * cellSize; };
+	var toG = function(canvasCoord) { return Math.floor(canvasCoord / cellSize); };
+
+	// PUBLIC PROPERTIES
+	this.ships = []
+	this.safetyMargin = 1;
+	this.shipDef = shipDef;
+	this.width = numX * cellSize;
+	this.height = numY * cellSize;
+
+	// update canvas
+	$(canvas).attr('width', this.width);
+	$(canvas).attr('height', this.height);
+
+	// DRAG EVENTS
+	// drag.onDragStart.add(function (evt) {
+
+	// });
+	drag.onDragging.add(function (evt) {
+		shipOX = toG(evt.origin.x);
+		shipOY = toG(evt.origin.y);
+		curShipX = toG(evt.pos.x);
+		curShipY = toG(evt.pos.y);
+
+		var ship = Ship.fromLine(shipOX, shipOY, curShipX, curShipY);
+		that.redraw();
+		style = that.shipAdmissible(ship) ? render.validShipStyle : render.invalidShipStyle;
+		render.drawShip(ship, style);
+	});
+	drag.onDragged.add(function (evt) {
+		shipOX = toG(evt.origin.x);
+		shipOY = toG(evt.origin.y);
+		curShipX = toG(evt.pos.x);
+		curShipY = toG(evt.pos.y);
+		var ship = Ship.fromLine(shipOX, shipOY, curShipX, curShipY);
+		if(that.shipAdmissible(ship)) {
+			that.ships.push(ship);
+			that.shipDef.takeShip(ship.Size);
+		} else if(s = that.shipSelected(ship)) {
+			that.ships.splice(that.ships.indexOf(s),1);
+			that.shipDef.returnShip(s.Size);
+		}
+		that.redraw();
+	});
+	drag.onCancelDrag.add(function () {
+		that.redraw();
+	});
+	drag.onClick.add(function (evt) {
+		shipOX = toG(evt.pos.x);
+		shipOY = toG(evt.pos.y);
+		for (var i = that.ships.length - 1; i >= 0; i--) {
+			if(that.ships[i].contains(shipOX, shipOY, 0)) {
+				that.shipDef.returnShip(that.ships[i].Size);
+				that.ships.splice(i, 1);
+			}
+		};
+		that.redraw();
+	});
+
+	this.shipAdmissible = function (ship) {
+		for (var i = this.ships.length - 1; i >= 0; i--) {
+			if(ship.intersects(this.ships[i], this.safetyMargin)) {
+				return false;
+			}
+		};
+		return shipDef.hasShip(ship.Size);
+	};
+	this.redraw = function() {
+		render.clear();
+		for (var i = this.ships.length - 1; i >= 0; i--) {
+			render.drawShipMargin(this.ships[i], this.safetyMargin);
+			render.drawShip(this.ships[i], render.placedShipStyle);
+		};
+	};
+	this.reset = function() {
+		this.ships.splice(0, this.ships.length);
+		this.shipDef.reset();
+		this.redraw();
+	};
+	this.shipSelected = function (ship) {
+		for (var i = this.ships.length - 1; i >= 0; i--) {
+			if (ship.equals(this.ships[i])) {
+				return this.ships[i];
+			}
+		}
+		return null;
+	}
+
+	// initial redraw
+	this.redraw();
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// class MouseDrag
+///////////////////////////////////////////////////////////////////////////////
+function MouseDrag(elem, threshold) {
+	var startDragging = false;
+	var dragging = false;
+
+	// define events
+	this.onClick = new CustomEvent();
+	this.onDragStart = new CustomEvent();
+	this.onDragging = new CustomEvent();
+	this.onDragged = new CustomEvent();
+	this.onCancelDrag = new CustomEvent();
+
+	var dragOrigin;
+	var that = this;
+
+	var onMouseDown = function(evt) {
+		dragOrigin = {x: evt.elemX, y:evt.elemY};
+		startDragging = true;
+		evt.preventDefault();
+	};
+	var onMouseMove = function(evt) {
+		if(startDragging) {
+			var dx = evt.elemX - dragOrigin.x;
+			var dy = evt.elemY - dragOrigin.y;
+			if(dx * dx + dy * dy >= threshold * threshold) {
+				startDragging = false;
+				dragging = true;
+				that.onDragStart.raise({origin: dragOrigin});
+			}
+		} else if(dragging) {
+			that.onDragging.raise({origin: dragOrigin, pos: {x:evt.elemX, y: evt.elemY}});
+		}
+
+		evt.preventDefault();
+	};
+	var onMouseUp = function(evt) {
+		if(dragging) {
+			that.onDragged.raise({origin: dragOrigin, pos: {x:evt.elemX, y: evt.elemY}});
+		} else if(startDragging) {
+			that.onClick.raise({pos: {x:evt.elemX, y: evt.elemY}});
+		}
+		dragging = false;
+		startDragging = false;
+		evt.preventDefault();
+	};
+	var onMouseLeave = function () {
+		if(dragging) {
+			that.onCancelDrag.raise();
+		}
+		startDragging = false;
+		dragging = false;
+	}
+
+	// register events
+	$(elem).mousedown(mkClientMouseEvent(onMouseDown, elem));
+	$(elem).mouseup(mkClientMouseEvent(onMouseUp, elem));
+	$(elem).mousemove(mkClientMouseEvent(onMouseMove, elem));
+	$(elem).mouseleave(onMouseLeave);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// class CustomEvent
+///////////////////////////////////////////////////////////////////////////////
+function CustomEvent() {
+	this.callbacks = [];
+}
+CustomEvent.prototype.add = function (handler) {
+	this.callbacks.push(handler);
+};
+CustomEvent.prototype.remove = function (handler) {
+	var i = this.callbacks.indexOf(handler);
+	if(i >= 0) {
+		this.callbacks.splice(i, 1);
+	}
+};
+CustomEvent.prototype.raise = function (arg) {
+	for (var i = this.callbacks.length - 1; i >= 0; i--) {
+		this.callbacks[i](arg);
+	};
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// class Render
+///////////////////////////////////////////////////////////////////////////////
+function Render(canvas, numX, numY, cellSize) {
+	var c2d = canvas.getContext("2d");
+
+	// convert between grid and canvas coordinates
+	var toC = function(gridCoord) { return gridCoord * cellSize; };
+	var toG = function(canvasCoord) { return Math.floor(canvasCoord); };
+
+	// calculate pixel size of map
+	var width = toC(numX);
+	var height = toC(numY);
+
+	// resize canvas element
+	$(canvas).attr('width', width);
+	$(canvas).attr('height', height);
+
+	// ship styles
+	this.validShipStyle   = { thickness: 1, border: 'rgb(0, 200, 0)', fill : '#AEF100' };
+	this.invalidShipStyle = { thickness: 1, border: 'rgb(255, 0, 0)', fill : '#FD0006' };
+	this.placedShipStyle  = { thickness: 1, border: 'rgb(0, 0, 200)', fill : '#AEF100' };
+	this.blockedCellColor = 'rgba(200, 200, 200, 0.5)';
+	// grid style
+	this.gridStyle        = { thickness: 2, color: '#D2F870'};
+
+	// rendering functions
+	this.clear = function () {
+		c2d.clearRect(0, 0, width, height);
+	};
+	this.drawGrid = function () {
+		c2d.save();
+		// draw map grid
+		c2d.beginPath();
+		c2d.strokeStyle = this.gridStyle.color;
+		c2d.lineWidth = this.gridStyle.thickness;
+		for(var x = 0; x <= width; x += cellSize) {
+			c2d.moveTo(x, 0);
+			c2d.lineTo(x, height);
+		}
+		for(var y = 0; y <= height; y += cellSize) {
+			c2d.moveTo(0, y);
+			c2d.lineTo(width, y);
+		}
+		c2d.stroke();
+		c2d.restore();
+	}
+	this.drawShip = function (ship, style) {
+		c2d.save();
+
+		c2d.strokeStyle = style.border;
+		c2d.lineWidth = style.thickness;
+		c2d.fillStyle = style.fill;
+
+		var rx = toC(ship.X);
+		var ry = toC(ship.Y);
+		var rw = toC(ship.Width);
+		var rh = toC(ship.Height);
+		c2d.fillRect(rx, ry, rw, rh);
+		c2d.strokeRect(rx, ry, rw, rh);
+
+		c2d.restore();
+	};
+	this.drawShipMargin = function (ship, margin) {
+		c2d.save();
+		c2d.fillStyle = this.blockedCellColor;
+		var rx = toC(ship.X - margin);
+		var ry = toC(ship.Y - margin);
+		var rw = toC(ship.Width + 2 * margin);
+		var rh = toC(ship.Height + 2 * margin);
+		c2d.fillRect(rx, ry, rw, rh);
+		c2d.restore();
+	};
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// class ShipDef
+///////////////////////////////////////////////////////////////////////////////
+function ShipDef(shipDefOrig) {
+	var shipDef = {};
+	this.shipTypes = [];
+	for(var len in shipDefOrig) {
+		shipDef[len] = shipDefOrig[len];
+		this.shipTypes.push(parseInt(len));
+	}
+	
+	this.onChanged = new CustomEvent();
+
+	this.hasShip = function (length) {
+		return shipDef[length] > 0;
+	};
+	this.shipCount = function(length) {
+		return shipDef[length];
+	};
+	this.total = function() {
+		var t = 0;
+		for(var len in shipDef) {
+			t += shipDef[len];
+		}
+		return t;
+	};
+	this.takeShip = function (length) {
+		if(this.hasShip(length)) {
+			shipDef[length] -= 1;
+		}
+		this.onChanged.raise(this);
+	};
+	this.returnShip = function (length) {
+		if(shipDef[length] < shipDefOrig[length]) {
+			shipDef[length] += 1;
+		}
+		this.onChanged.raise(this);
+	};
+	this.reset = function () {
+		for(var len in shipDefOrig) {
+			shipDef[len] = shipDefOrig[len];
+		}
+		this.onChanged.raise(this);
+	};
+}
+ShipDef.fromList = function(shipList) {
+	var shipDefOrig = {};
+	for (var i = shipList.length - 1; i >= 0; i--) {
+		var len = shipList[i];
+		if(len in shipDefOrig)
+			shipDefOrig[len] += 1;
+		else
+			shipDefOrig[len] = 1;
+	};
+	return new ShipDef(shipDefOrig);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// class Ship
+///////////////////////////////////////////////////////////////////////////////
+function Ship(x, y, size, orientation) {
+	this.X = x;
+	this.Y = y;
+	this.Size = size;
+	this.Orientation = orientation;
+	if(this.Orientation == 0) {
+		this.Width = this.Size;
+		this.Height = 1;
+	} else {
+		this.Width = 1;
+		this.Height = this.Size;
+	}
+	this.contains = function(x,y,margin) {
+		return (x >= this.X - margin) && (y >= this.Y - margin) && (x < this.X + this.Width + margin) && (y < this.Y + this.Height + margin);
+	};
+	this.intersects = function(other, margin) {
+		var tr = this.X + this.Width - 1;
+		var tb = this.Y + this.Height - 1;
+		var or = other.X + other.Width + margin - 1;
+		var ob = other.Y + other.Height + margin - 1;
+		return (this.X <= or &&
+				other.X - margin <= tr &&
+				this.Y <= ob &&
+				other.Y - margin <= tb);
+	};
+	this.equals = function(other) {
+		return (this.X == other.X && 
+			    this.Y == other.Y && 
+			    this.Orientation == other.Orientation);
+	}
+}
+Ship.fromLine = function(x1, y1, x2, y2) {
+	if(Math.abs(x2 - x1) >= Math.abs(y2 - y1)) {
+		y2 = y1;
+		if(x2 < x1) {
+			var t = x1;
+			x1 = x2;
+			x2 = t;
+		}
+		var shipSize = Math.abs(x2 - x1) + 1;
+		var orientation = 0;
+	} else {
+		x2 = x1;
+		if(y2 < y1) {
+			var t = y1;
+			y1 = y2;
+			y2 = t;
+		}
+		var shipSize = Math.abs(y2 - y1) + 1;
+		var orientation = 1;
+	}
+	return new Ship(x1, y1, shipSize, orientation);
+}
diff --git a/templates/about.cassius b/templates/about.cassius
new file mode 100644
--- /dev/null
+++ b/templates/about.cassius
@@ -0,0 +1,6 @@
+body
+  font-family: sans-serif
+  overflow-x: hidden
+  background: #020402 url(@{StaticR img_dreadnought_png}) no-repeat
+  background-position: 50% 0px
+  color: #5FC0CE
diff --git a/templates/about.hamlet b/templates/about.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/about.hamlet
@@ -0,0 +1,10 @@
+<h1> _{MsgHowToPlay}
+<h2> _{MsgHowToPlaceShipsHeading}
+<p> _{MsgHowToPlaceShipsFull}
+<h2> _{MsgHowToPlayHeading}
+<p> _{MsgHowToPlayFull}
+<h2> _{MsgHowToWinHeading}
+<p> _{MsgHowToWinFull maxTurns countdownTurns}
+
+<h1> _{MsgReallyFair}
+<p> _{MsgReallyFairFull sourceURL aiURL}
diff --git a/templates/board.cassius b/templates/board.cassius
new file mode 100644
--- /dev/null
+++ b/templates/board.cassius
@@ -0,0 +1,21 @@
+div.board
+  width: 480px
+  height: 480px
+  position: relative
+
+div.board svg
+  margin: 0px
+  padding: 0px
+  position: absolute
+  top: 40px
+  left: 40px
+
+div.board div
+  position: absolute
+  margin: 0px
+  padding: 0px
+  top: 0px
+  left: 0px
+  width: 480px
+  height: 480px
+  background-image: url(@{gridStatic})
diff --git a/templates/default-layout-wrapper.hamlet b/templates/default-layout-wrapper.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/default-layout-wrapper.hamlet
@@ -0,0 +1,16 @@
+$newline never
+\<!doctype html>
+<html lang="en">
+    <head>
+        <meta charset="UTF-8">
+
+        <title>#{pageTitle pc}
+        <link rel="shortcut icon" href="@{StaticR img_favicon_ico}" type="image/x-icon" />
+        <meta name="description" content="">
+        <meta name="author" content="">
+
+        <meta name="viewport" content="width=device-width,initial-scale=1">
+
+    ^{pageHead pc}
+  <body>
+    ^{pageBody pc}
diff --git a/templates/default-layout.cassius b/templates/default-layout.cassius
new file mode 100644
--- /dev/null
+++ b/templates/default-layout.cassius
@@ -0,0 +1,143 @@
+html, body
+  height: 100%
+
+body
+  font-family: sans-serif
+  margin: 0px
+  padding: 0px
+  overflow-x: hidden
+  background: #020402 url(@{StaticR img_dreadnought_png}) no-repeat
+  background-position: 50% 100px
+  color: #5FC0CE
+
+header
+  background-color: #015965
+  padding: 10px
+  clear: both
+  box-shadow: 0 0 5px #36BBCE
+  text-align: center
+
+.wrapper
+  min-height: 100%
+  height: auto !important
+  height: 100%
+  margin: 0 auto -64px
+
+.footer
+  height: 32px;
+  clear: both
+  background-color: #015965
+  width: 100%
+  padding: 16px;
+  text-align: center
+  box-shadow: 0 0 5px #36BBCE
+
+h1.gameName
+  font-size: 40px
+  font-weight: bold
+  margin: 0px auto
+  display: inline-block
+  color: #5FC0CE
+
+h2.credits
+  display: inline-block
+  margin: 0px auto
+  color: #5FC0CE
+
+a, input
+  font-family: sans-serif
+
+div.content
+  min-height: 200px
+  margin: 0px auto
+
+.controlBox
+  text-align: center
+
+.error
+  color: #700
+  padding: 5px
+  font-weight: bold
+  border: solid 1px #8d2320
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2)
+  -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2)
+  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2)
+  -webkit-border-radius: 4px
+  -moz-border-radius: 4px
+  border-radius: 4px
+  margin: 0px auto
+  width: 800px
+
+.IEWarning
+  display: none
+
+.warning
+  color: #F00
+
+.linkButton
+  display: inline-block
+  padding: 10px 15px
+  margin: 5px 5px
+  color: #EEE
+  margin-bottom: 10px
+  text-decoration: none
+  white-space: nowrap
+  -webkit-border-radius: 4px
+  -moz-border-radius: 4px
+  border-radius: 4px
+  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4)
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2)
+  -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2)
+  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2)
+  -webkit-transition-duration: 0.2s
+  -moz-transition-duration: 0.2s
+  transition-duration: 0.2s
+  -webkit-user-select:none
+  -moz-user-select:none
+  -ms-user-select:none
+  user-select:none
+  font-size:16px
+
+.linkButton:hover, .linkButton:focus
+  text-decoration: none
+
+.linkButton:active
+  -webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6)
+  -moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6)
+  box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6)
+
+.yellowButton
+  color: #333
+  background: #AEF100
+  border: solid 1px #1c4452 
+
+.yellowButton:hover, .yellowButton:focus
+  background: #C4F83E
+  border: solid 1px #2A4E77
+
+.yellowButton:active
+  background: #719D00
+  border: solid 1px #203E5F
+
+.redButton
+  color: #CBB
+  background: #FD0006
+  border: solid 1px #8d2320
+
+.redButton:hover, .redButton:focus
+  background: #FE3F44
+  border: solid 1px #772c2a
+
+.redButton:active
+  background: #A40004
+  border: solid 1px #5f2220
+
+.linkButton:disabled
+  background:#aaa
+  border: solid 1px #999
+
+.halftransparent
+  opacity: 0.6
+
+.clear
+  clear: both
diff --git a/templates/default-layout.hamlet b/templates/default-layout.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/default-layout.hamlet
@@ -0,0 +1,25 @@
+<div .wrapper>
+  <header>
+    <h1 .gameName>_{MsgGameName}
+    $if isHome
+      <h2 .credits>_{MsgCredits}
+    <h2 .IEWarning .warning>_{MsgIEWarning}
+    <noscript>
+      <h2 .warning>_{MsgNoJavaScriptWarning}
+
+  <div .content>
+    $maybe msg <- mmsg
+       <script>
+         setTimeout(function() {alert("#{msg}")}, 200);
+    ^{widget}
+  <!-- Placeholder to prevent overlapping of page contents and footer -->
+  <div style="clear: both; height: 100px">
+  
+$if (not isHome)
+  <div .footer>
+    $if isReplay
+      <a .linkButton .yellowButton href="@{HomeR}">_{MsgLinkHome}
+    $else
+      <a .linkButton .redButton href="#!" onclick="confirmLeave()">_{MsgLinkHome}
+    <a .linkButton .yellowButton href=@{AboutR}  onclick="window.open('@{AboutR}', 'newwindow', 'width=800, height=650'); return false;">
+      _{MsgAbout}
diff --git a/templates/default-layout.julius b/templates/default-layout.julius
new file mode 100644
--- /dev/null
+++ b/templates/default-layout.julius
@@ -0,0 +1,13 @@
+function confirmLeave() {
+	conf = window.confirm("#{rawJS (messageRender MsgConfirmLeave)}");
+	if (conf == true) {
+		document.location = "@{HomeR}";
+	}
+}
+
+window.onload = function() {
+	var ua = window.navigator.userAgent;
+	if (ua.indexOf("MSIE") > 0 || ua.indexOf("Trident/") > 0) {
+		document.getElementsByClassName('IEWarning')[0].style.display = 'block';
+	}
+};
diff --git a/templates/gameended.cassius b/templates/gameended.cassius
new file mode 100644
--- /dev/null
+++ b/templates/gameended.cassius
@@ -0,0 +1,64 @@
+div.banner
+  text-align: center
+  position: fixed
+  top: 40%
+  width:100%
+  z-index: 1000
+
+div.bannerLost
+  background-color: rgba(164, 0, 4, 0.25)
+  box-shadow: 0 0 2px 2px #FE3F44 inset
+  color: #FE7276
+
+div.bannerWon
+  background-color: rgba(0, 164, 4, 0.25)
+  box-shadow: 0 0 2px 2px #40FF43 inset
+  color: #73FF75
+
+div.bannerDrawn
+  background-color: rgba(164, 164, 4, 0.25)
+  box-shadow: 0 0 2px 2px #FFFF40 inset
+  color: #FFFF73
+
+h3.bannerText
+  display: inline-block
+  font-size: 20px
+
+div.boards
+  width: 1000px
+  margin: 0px auto
+  opacity: 0.75
+
+div.actionBox
+  text-align: center
+  padding-top: 16px
+  height: 64px
+
+div.boards h3
+  text-align: center
+
+div.leftBoard
+  float: left
+  width: 500px
+
+div.rightBoard
+  width: 480px
+  float: right
+
+div.boardContent
+  box-shadow: 0 0 5px #36BBCE
+  background-color: rgba(1, 89, 101, 0.25)
+  width: 480px
+
+embed.board
+  width: 480px
+  height: 480px
+
+div.infoH
+  width: 1002px
+  margin: 0px auto
+  text-align: center
+  padding-top: 15px
+
+div.infoBoxH
+  width: 100%
diff --git a/templates/gameended.hamlet b/templates/gameended.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/gameended.hamlet
@@ -0,0 +1,51 @@
+<div .boards>
+  <div .leftBoard>
+    <div .boardContent>
+      <h3>
+        _{MsgYourFleet}
+      <div .board>
+        #{playerGridHtml game ActionFire}
+        <div>&nbsp;
+  <div .rightBoard>
+    <div .boardContent>
+      <h3>
+        _{MsgOpponentsFleet}
+      <div .board>
+        #{enemyGridHtml game True}
+        <div>&nbsp;
+
+<div .clear>
+
+<div .infoH>
+    $if drawn
+      <div .infoBoxH .bannerDrawn>
+        <h3 .bannerText>
+          _{MsgDrawn remShipsHuman}
+        <a .linkButton .redButton href="@{ReplayR gameE}">
+          _{MsgWatchReplay}
+    $elseif timedOut
+      $if humanWon
+        <div .infoBoxH .bannerWon>
+          <h3 .bannerText>
+            _{MsgWonByTimeout remShipsHuman remShipsComputer}
+          <a .linkButton .redButton href="@{ReplayR gameE}">
+            _{MsgWatchReplay}
+      $else 
+        <div .infoBoxH .bannerLost>
+          <h3 .bannerText>
+            _{MsgLostByTimeout remShipsHuman remShipsComputer}
+          <a .linkButton .redButton href="@{ReplayR gameE}">
+            _{MsgWatchReplay}
+    $else
+      $if humanWon
+        <div .infoBoxH .bannerWon>
+          <h3 .bannerText>
+            _{MsgWon}
+          <a .linkButton .redButton href="@{ReplayR gameE}">
+            _{MsgWatchReplay}
+      $else 
+        <div .infoBoxH .bannerLost>
+          <h3 .bannerText>
+            _{MsgLost}
+          <a .linkButton .redButton href="@{ReplayR gameE}">
+            _{MsgWatchReplay}
diff --git a/templates/home.cassius b/templates/home.cassius
new file mode 100644
--- /dev/null
+++ b/templates/home.cassius
@@ -0,0 +1,4 @@
+p.linkBlock
+  text-align: center
+  margin: 0px auto
+  padding: 30px
diff --git a/templates/home.hamlet b/templates/home.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/home.hamlet
@@ -0,0 +1,4 @@
+<p .linkBlock>
+  <a .linkButton .yellowButton href=@{RulesR}> _{MsgAdjustRules}
+  <a .linkButton .yellowButton href=@{PlaceShipsR defaultOptions}>_{MsgStartPlacing}
+  <a .linkButton .yellowButton href=@{AboutR}  onclick="window.open('@{AboutR}', 'newwindow', 'width=800, height=650'); return false;">_{MsgAbout}
diff --git a/templates/legend.cassius b/templates/legend.cassius
new file mode 100644
--- /dev/null
+++ b/templates/legend.cassius
@@ -0,0 +1,11 @@
+table.legendV, table.legendH
+  text-align: left
+  border-spacing: 0px
+  border-collapse: separate
+  width: 100%
+
+table.legendV td, table.legendH td
+  padding: 5px
+  vertical-align: middle
+  border-right-width: 0px
+  color: #EEE
diff --git a/templates/legend.hamlet b/templates/legend.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/legend.hamlet
@@ -0,0 +1,98 @@
+$case orientation
+  $of Horizontal
+    <table .legendH>
+      <tr>
+        <td>
+          <img src="@{legendStatic LIFogOfWar}">
+        <td>_{MsgLegendFogOfWar}
+        $if not movesAllowed
+          <td>
+            <img src="@{legendStatic LIWater}">
+          <td>_{MsgLegendWater}
+        <td>
+          <img src="@{legendStatic LIShipHit}">
+        <td>_{MsgLegendShipHit}
+        <td>
+          <img src="@{legendStatic LIShipSunk}">
+        <td>_{MsgLegendShipSunk}
+        <td>
+         <img src="@{legendStatic LILastShot}">
+        <td>_{MsgLegendLastShot}
+      $if movesAllowed
+        <tr>
+          <td>
+            <img src="@{legendStatic LIShipImmovable}">
+          <td>_{MsgLegendShipImmovable}
+          <td>
+            <img src="@{legendStatic LIShipMovable}">
+          <td>_{MsgLegendShipMovable}
+          <td>
+            <img src="@{legendStatic LIShipWithArrow}">
+          <td>_{MsgLegendShipWithArrow}
+        <tr>
+          <td colspan="2"> _{MsgLegendWaterShots}:
+          <td colspan="2" width="250">
+            <img src="@{timedLegendStatic $ TLIWater 0}" title="_{MsgLegendRightNow}">
+            <img src="@{timedLegendStatic $ TLIWater 5}" title="_{MsgLegendTurnsAgo 5}">
+            <img src="@{timedLegendStatic $ TLIWater 10}" title="_{MsgLegendTurnsAgo 10}">
+            <img src="@{timedLegendStatic $ TLIWater 15}" title="_{MsgLegendTurnsAgo 15}">
+            <img src="@{timedLegendStatic $ TLIWater 20}" title="_{MsgLegendMinTurnsAgo 20}">
+          <td colspan="2" width="250">
+            <img src="@{timedLegendStatic $ TLIMarker 0}" title="_{MsgLegendRightNow}">
+            <img src="@{timedLegendStatic $ TLIMarker 5}" title="_{MsgLegendTurnsAgo 5}">
+            <img src="@{timedLegendStatic $ TLIMarker 10}" title="_{MsgLegendTurnsAgo 10}">
+            <img src="@{timedLegendStatic $ TLIMarker 15}" title="_{MsgLegendTurnsAgo 15}">
+            <img src="@{timedLegendStatic $ TLIMarker 20}" title="_{MsgLegendMinTurnsAgo 20}">
+          
+  $of Vertical
+    <table .legendV>
+      <tr>
+        <td>
+          <img src="@{legendStatic LIFogOfWar}">
+        <td>_{MsgLegendFogOfWar}
+      <tr>
+        $if not movesAllowed
+          <td>
+            <img src="@{legendStatic LIWater}">
+          <td>_{MsgLegendWater}
+      <tr>
+        <td>
+          <img src="@{legendStatic LIShipHit}">
+        <td>_{MsgLegendShipHit}
+      <tr>
+        <td>
+          <img src="@{legendStatic LIShipSunk}">
+        <td>_{MsgLegendShipSunk}
+      <tr>
+        <td>
+          <img src="@{legendStatic LILastShot}">
+        <td>_{MsgLegendLastShot}
+      $if movesAllowed
+        <tr>
+          <td>
+            <img src="@{legendStatic LIShipImmovable}">
+          <td>_{MsgLegendShipImmovable}
+        <tr>
+          <td>
+            <img src="@{legendStatic LIShipMovable}">
+          <td>_{MsgLegendShipMovable}
+        <tr>
+          <td>
+            <img src="@{legendStatic LIShipWithArrow}">
+          <td>_{MsgLegendShipWithArrow}
+        <tr>
+          <td colspan="2"> _{MsgLegendWaterShots}:
+        <tr>
+          <td colspan="2" width="250">
+            <img src="@{timedLegendStatic $ TLIWater 0}" title="_{MsgLegendRightNow}">
+            <img src="@{timedLegendStatic $ TLIWater 5}" title="_{MsgLegendTurnsAgo 5}">
+            <img src="@{timedLegendStatic $ TLIWater 10}" title="_{MsgLegendTurnsAgo 10}">
+            <img src="@{timedLegendStatic $ TLIWater 15}" title="_{MsgLegendTurnsAgo 15}">
+            <img src="@{timedLegendStatic $ TLIWater 20}" title="_{MsgLegendMinTurnsAgo 20}">
+        <tr>
+          <td colspan="2" width="250">
+            <img src="@{timedLegendStatic $ TLIMarker 0}" title="_{MsgLegendRightNow}">
+            <img src="@{timedLegendStatic $ TLIMarker 5}" title="_{MsgLegendTurnsAgo 5}">
+            <img src="@{timedLegendStatic $ TLIMarker 10}" title="_{MsgLegendTurnsAgo 10}">
+            <img src="@{timedLegendStatic $ TLIMarker 15}" title="_{MsgLegendTurnsAgo 15}">
+            <img src="@{timedLegendStatic $ TLIMarker 20}" title="_{MsgLegendMinTurnsAgo 20}">
diff --git a/templates/placeships.cassius b/templates/placeships.cassius
new file mode 100644
--- /dev/null
+++ b/templates/placeships.cassius
@@ -0,0 +1,73 @@
+body
+  -webkit-touch-callout: none;
+  -webkit-user-select: none;
+  -moz-user-select: none;
+  user-select: none;
+
+.placeContent
+  width: 820px
+  margin: 0px auto
+
+.left
+  width: 500px
+  float: left
+
+.right
+  width: 320px
+  float: right
+
+div.boardBox, div.toolBox
+  box-shadow: 0 0 5px #36BBCE
+  background-color: rgba(1, 89, 101, 0.25)
+
+div.boardBox
+  width: 480px
+  height: 550px
+
+div.toolBox
+  width: 320px
+  height: 550px
+
+div.placeContent h3
+  text-align: center
+
+#map
+  padding: 0px;
+
+thead tr td
+  border-bottom: 1px solid #D2F870;
+  padding: 2px;
+
+tfoot tr td
+  border-top: 1px solid #D2F870;
+  padding: 2px;
+
+thead tr td:first-child, tbody tr td:first-child, tfoot tr td:first-child
+  border-right: 1px solid #D2F870;
+  padding: 2px;
+
+#mapBackground
+  width: 480px
+  height: 480px
+  position: relative
+
+#mapBackground .grid
+  width: 480px
+  height: 480px
+  top: 0px
+  left: 0px
+  position: absolute
+  background-image: url(@{gridStatic})
+
+#mapBackground .water
+  background: #36BBCE
+  width: 400px
+  height: 400px
+  top: 40px
+  left: 40px
+  position: absolute
+
+#mapBackground canvas
+  top: 40px
+  left: 40px
+  position: absolute  
diff --git a/templates/placeships.hamlet b/templates/placeships.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/placeships.hamlet
@@ -0,0 +1,30 @@
+<div .placeContent>
+  <div .left>
+    <div .boardBox>
+      <h3>_{MsgPlaceShips}
+      <div id="mapBackground">
+        <div .water>&nbsp;
+        <div .grid>&nbsp;
+        <canvas id="map">
+  <div .right>
+    <div .toolBox>
+      <h3>_{MsgAvailableShips}
+      <table id="status">
+        <thead>
+          <tr>
+            <td>_{MsgShipLength}
+            <td># _{MsgShipsAvailable}
+        <tbody>
+        <tfoot>
+          <tr>
+            <td>_{MsgShipsTotal}
+            <td id="tdTotalShips">
+      <hr>
+      <div>
+        <button .linkButton .yellowButton id="btnReset">_{MsgResetFleet}
+        <button .linkButton .yellowButton id="btnRandom">_{MsgPlaceRandom}
+      <hr>
+      <div>
+        <form id="fleetForm" action="@{PlaceShipsR options}" method="POST">
+          <input id="fleetData" name="fleetData" type="hidden" >
+          <input .linkButton .redButton id="btnSubmit" type="submit" value=_{MsgStartPlaying} disabled>
diff --git a/templates/placeships.julius b/templates/placeships.julius
new file mode 100644
--- /dev/null
+++ b/templates/placeships.julius
@@ -0,0 +1,84 @@
+var cellSize = 40;
+var nx = #{toJSON $ fst boardSize};
+var ny = #{toJSON $ snd boardSize};
+var map;
+var safetyMargin = 1;
+var shipDef = ShipDef.fromList(#{toJSON fleetShips});
+var shipLenTD = {};
+
+$(window).load(function() {
+	// setup canvas
+	var mapElem = document.getElementById("map");
+
+	map = new Map(mapElem, nx, ny, cellSize, shipDef);
+	map.safetyMargin = 1;
+	map.shipDef.onChanged.add(shipDefChanged);
+
+	// setup buttons
+	$("#btnReset").click(function() {
+		map.reset();
+	});
+	$("#btnRandom").click(function() {
+		placeRandom();
+	});
+	// setup table
+	for (var i = 0; i < shipDef.shipTypes.length; i++) {
+		var len = shipDef.shipTypes[i];
+		var td1 = $(document.createElement('td'));
+		var td2 = $(document.createElement('td'));
+		var tr = $(document.createElement('tr'));
+		td1.text(len);
+		td2.text(shipDef.shipCount(len));
+		shipLenTD[len] = td2;
+		tr.append(td1);
+		tr.append(td2);
+		$('#status tbody').append(tr);
+	};
+	shipDefChanged();
+});
+
+function placeRandom() {
+	$.ajax({
+		url: "@{PlaceShipsRndR}",
+		type: "POST",
+		dataType: "json",
+		data: { fleetData: JSON.stringify(map.ships) }
+	}).done(function(shipData) {
+		if (0 == shipData.length) {
+			alert(#{toJSON $ messageRender MsgNoPossiblePlacement});
+			return;
+		}
+
+		map.reset();
+		// Extract relevant data (x,y,size, orientation) from the fleet
+		for(var i = 0; i < shipData.length; i++) {
+			var ship = new Ship (
+				shipData[i].X,
+				shipData[i].Y,
+				shipData[i].Size,
+				shipData[i].Orientation);
+			map.ships.push(ship);
+			map.shipDef.takeShip(ship.Size);
+		}
+		// Fill in the form so we can use the fleet in the game, then update screen:
+		$("#fleetData").val(JSON.stringify(map.ships));
+		shipDefChanged();
+		map.redraw();
+	});
+}
+
+function shipDefChanged() {
+	for(var i = 0; i < shipDef.shipTypes.length; i++) {
+		var len = shipDef.shipTypes[i];
+		shipLenTD[len].text(shipDef.shipCount(len));
+	}
+	var total = shipDef.total();
+	$("#tdTotalShips").text(total);
+	if(total == 0) {
+		var jsonShips = JSON.stringify(map.ships);
+		$("#fleetData").val(jsonShips);
+		$("#btnSubmit").attr('disabled' , false);
+	} else {
+		$("#btnSubmit").attr('disabled' , true);
+	}
+}
diff --git a/templates/play.cassius b/templates/play.cassius
new file mode 100644
--- /dev/null
+++ b/templates/play.cassius
@@ -0,0 +1,120 @@
+span.expectedAction
+  font-size: 16px
+  color: #FE3F44
+
+@media all and (max-width: 1329px)
+  div.boards
+    width: 1000px
+
+  div.rightBoard
+    width: 480px
+    float: right
+
+  div.infoV
+    visibility: collapsed
+    display: none
+
+  div.legendV
+    visibility: collapsed
+    display: none
+
+  div.legendH, div.infoH
+    width: 1000px
+
+@media all and (max-width: 1629px) and (min-width: 1330px)
+  div.boards
+    width: 1300px
+
+  div.rightBoard
+    width: 480px
+    float: left
+
+  div.infoV
+    float: right
+
+  div.legendV
+    visibility: collapsed
+    display: none
+
+  div.legendH
+    width: 1300px
+
+  div.infoH
+    visibility: collapsed
+    display: none
+
+@media all and (min-width: 1630px)
+  div.boards
+    width: 1600px
+
+  div.rightBoard
+    width: 500px
+    float: left
+
+  div.infoV
+    float: left
+    width: 300px
+
+  div.legendV
+    float: right
+
+  div.infoH
+    visibility: collapsed
+    display: none
+
+  div.legendH
+    visibility: collapsed
+    display: none
+
+div.boards
+  margin: 0px auto
+
+div.actionBox
+  text-align: center
+  padding-top: 16px
+
+div.boards h3, div.boards h4
+  text-align: center
+
+div.leftBoard
+  float: left
+  width: 500px
+
+div.infoBoxV, div.infoBoxH
+  box-shadow: 0 0 5px #36BBCE
+  background-color: rgba(1, 89, 101, 0.25)
+
+div.infoBoxV
+  width: 290px
+  height: 600px
+  position: relative
+
+div.infoBoxH
+  height: 100%
+  width: 100%
+
+div.infoH, div.legendH
+  margin: 0px auto
+  text-align: center
+
+div.boardContent
+  box-shadow: 0 0 5px #36BBCE
+  background-color: rgba(1, 89, 101, 0.25)
+  width: 480px
+  height: 600px
+
+.red
+  border: 3px solid #F00
+  background: #F00
+
+.alert
+  color: #F00
+
+div.infoBoxV .watchreplay
+  text-align: center
+  position: absolute
+  bottom: 30px
+  width: 100%
+
+div.infoBoxH .watchreplay
+  margin-top: 30px
diff --git a/templates/play.hamlet b/templates/play.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/play.hamlet
@@ -0,0 +1,83 @@
+<div .boards>
+  <div .leftBoard>
+    <div .boardContent>
+      <h3>
+        _{MsgYourFleet}
+      
+      <div .board>
+        #{playerGridHtml game expectedAction}
+        <div :expectedAction == ActionMove:.actionMove>&nbsp;
+
+      <div .actionBox>
+        $if expectedAction == ActionMove
+          <form method="POST" action="@{MoveR gameE}">
+            <span .expectedAction>_{MsgMoveShip}
+            <input .linkButton .redButton type="submit" value=_{MsgSkipMove} />
+
+  <div .rightBoard>
+    <div .boardContent>
+      <h3>
+        _{MsgOpponentsFleet}
+
+      <div .board>
+        #{enemyGridHtml game False}
+        <div :expectedAction == ActionFire:.actionFire>&nbsp;
+
+      <div .actionBox>
+        $if expectedAction == ActionFire
+          <span .expectedAction>_{MsgFireShot}
+
+  <div .infoV>
+    <div .infoBoxV>
+      <h3>_{MsgHints}
+      $if devModeOpt
+        <h4>_{MsgRemainingTurns remTurns}
+      $if showCountdown game
+        <h4 .alert>
+          $if remTurns == 0
+            _{MsgLastTurn}
+          $else
+            _{MsgRemainingTurns remTurns}
+      ^{shipsOpponentWidget game Vertical}
+      <div  .watchreplay>
+        <a .linkButton .yellowButton href="#!" onclick="window.open('@{SaveGameR gameE}', 'newwindow', 'width=800, height=300'); return false;">
+          _{MsgSaveGame}
+        <br>
+        <a .linkButton .redButton href="#!" onclick="confirmReplay()">
+          _{MsgWatchReplay}
+
+  <div .legendV>
+    <div .infoBoxV>
+      <h3>_{MsgLegend}
+      ^{legendWidget Vertical (rulesMove gameRules)}
+
+<div .clear>
+
+<div .infoH>
+    <div .infoBoxH>
+      <div .watchreplay>
+        <a .linkButton .yellowButton href="#!" onclick="window.open('@{SaveGameR gameE}', 'newwindow', 'width=800, height=300'); return false;">
+          _{MsgSaveGame}
+        <br>
+        <a .linkButton .redButton href="#!" onclick="confirmReplay()">
+          _{MsgWatchReplay}
+      <h3>_{MsgHints}
+      $if devModeOpt
+        <h4>_{MsgRemainingTurns remTurns}
+      $if showCountdown game
+        <h4 .alert>
+          $if remTurns == 0
+            _{MsgLastTurn}
+          $else
+            _{MsgRemainingTurns remTurns}
+      ^{shipsOpponentWidget game Horizontal}
+
+<div .legendH>
+  <div .infoBoxH>
+    <h3>_{MsgLegend}
+    ^{legendWidget Horizontal (rulesMove gameRules)}
+<script>
+  var replayUrl = '@{ReplayR gameE}';
+  var alertCountdown = '#{showAlert}';
+  var alertMessage = '_{MsgRemainingTurns remTurns}';
+  \$(playScriptInit('@{MoveR gameE}', '@{FireR gameE}'))
diff --git a/templates/play.julius b/templates/play.julius
new file mode 100644
--- /dev/null
+++ b/templates/play.julius
@@ -0,0 +1,45 @@
+function clickableInit(elem, target) {
+    elem.click(function (event) {
+        clickableEvent(event, target);
+    });
+}
+
+function clickableEvent(event, target) {
+    var form = document.createElement('form');
+    form.setAttribute('method', 'post');
+    form.setAttribute('action', target);
+
+    var offset = $(event.target).offset();
+    var x = event.pageX - offset.left;
+    var y = event.pageY - offset.top;
+
+    var hiddenField = document.createElement('input');
+    hiddenField.setAttribute('type','hidden');
+    hiddenField.setAttribute('name','X');
+    hiddenField.setAttribute('value',x);
+    form.appendChild(hiddenField);
+
+    hiddenField = document.createElement('input');
+    hiddenField.setAttribute('type','hidden');
+    hiddenField.setAttribute('name','Y');
+    hiddenField.setAttribute('value',-y);
+    form.appendChild(hiddenField);
+
+    document.body.appendChild(form);
+    form.submit();
+}
+
+function playScriptInit(moveUrl, fireUrl) {
+    clickableInit($(".actionMove"), moveUrl);
+    clickableInit($(".actionFire"), fireUrl);
+    if(alertCountdown == "True") {
+        alert(alertMessage);
+    }
+}
+
+function confirmReplay() {
+    conf = window.confirm("#{rawJS (messageRender MsgConfirmReplay)}");
+    if (conf == true) {
+        document.location = replayUrl;
+    }
+}
diff --git a/templates/replay.cassius b/templates/replay.cassius
new file mode 100644
--- /dev/null
+++ b/templates/replay.cassius
@@ -0,0 +1,74 @@
+
+@media all and (max-width: 1329px)
+  div.boards
+    width: 1000px
+
+  div.rightBoard
+    width: 480px
+    float: right
+
+@media all and (max-width: 1629px) and (min-width: 1330px)
+  div.boards
+    width: 1300px
+
+  div.rightBoard
+    width: 480px
+    float: left
+
+@media all and (min-width: 1630px)
+  div.boards
+    width: 1600px
+
+  div.rightBoard
+    width: 500px
+    float: left
+
+div.boards
+  margin: 0px auto
+
+div.boards h3
+  text-align: center
+
+div.leftBoard
+  float: left
+  width: 500px
+
+div.boardContent
+  box-shadow: 0 0 5px #36BBCE
+  background-color: rgba(1, 89, 101, 0.25)
+  width: 480px
+  height: 600px
+
+div.board
+  width: 480px
+  height: 480px
+  position: relative
+  display: none
+
+div.board embed, div.board svg
+  margin: 0px
+  padding: 0px
+  position: absolute
+  top: 40px
+  left: 40px
+
+div.board div
+  position: absolute
+  margin: 0px
+  padding: 0px
+  top: 0px
+  left: 0px
+  width: 480px
+  height: 480px
+  background-image: url(@{gridStatic})
+
+#aiboard0, #humanboard0
+  display: block
+
+.red
+  border: 3px solid #F00
+  background: #F00
+
+div.actionBox
+  text-align: center
+  padding-top: 20px
diff --git a/templates/replay.hamlet b/templates/replay.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/replay.hamlet
@@ -0,0 +1,38 @@
+<div .boards>
+  <div .leftBoard>
+    <div .boardContent>
+      <h3>
+        _{MsgYourFleet}
+
+      $forall (i, humanGrid) <- humanGrids
+        <div .board id="humanboard#{show i}">
+          #{humanGrid}
+          <div>&nbsp;
+
+  <div .rightBoard>
+    <div .boardContent>
+      <h3>
+        _{MsgOpponentsFleet}
+
+      $forall (i, aiGrid) <- aiGrids
+        <div .board id="aiboard#{show i}">
+          #{aiGrid}
+          <div>&nbsp;
+
+      <div .actionBox>
+        <a .linkButton .redButton href="#" #first>
+          |&lt;&lt;
+        <a .linkButton .redButton href="#" #prev>
+          &lt;&lt;
+        <a .linkButton .redButton href="#" #pause>
+          _{MsgPauseButtonLabel}
+        <a .linkButton .redButton href="#" #next>
+          &gt;&gt;
+        <a .linkButton .redButton href="#" #last>
+          &gt;&gt;|
+
+<div .clear>
+    
+
+<script>
+  var numSteps = #{numSteps};
diff --git a/templates/replay.julius b/templates/replay.julius
new file mode 100644
--- /dev/null
+++ b/templates/replay.julius
@@ -0,0 +1,66 @@
+var step = 0;
+var intervalID;
+var intervalDuration = 1000; // milliseconds
+var paused = false;
+
+function updateStep(f) {
+    oldStep = step;
+    newStep = f(step);
+    if(newStep < 0 || newStep >= numSteps)
+      return;
+    $("#humanboard" + oldStep).hide();
+    $("#humanboard" + newStep).show();
+    $("#aiboard" + oldStep).hide();
+    $("#aiboard" + newStep).show();
+    step = newStep
+    updatePauseButton();
+}
+
+function animationStep() {
+    if(!paused)
+        updateStep(function(s) { return s + 1; });
+}
+
+function updatePauseButton() {
+    if(step == numSteps - 1) {
+        paused = true;
+        $("#pause").text(#{toJSON $ messageRender MsgRestartButtonLabel});
+    } else {
+        if(paused)
+          $("#pause").text(#{toJSON $ messageRender MsgUnpauseButtonLabel});
+        else
+          $("#pause").text(#{toJSON $ messageRender MsgPauseButtonLabel});
+    }
+}
+
+function handlePause() {
+    if(step == numSteps - 1) {
+        paused = false;
+        updateStep(function(s) { return 0; })
+    } else {
+        paused = !paused;
+        updatePauseButton();
+    }
+}
+
+$(function() {
+    intervalID = setInterval(animationStep, intervalDuration)
+    updatePauseButton();
+    $("#first").click(function(event) {
+        paused = true;
+        updateStep(function(s) { return 0; })
+    })
+    $("#prev").click(function(event) {
+        paused = true;
+        updateStep(function(s) { return s - 1; });
+    });
+    $("#pause").click(handlePause)
+    $("#next").click(function(event) {
+        paused = true;
+        updateStep(function(s) { return s + 1; });
+    });
+    $("#last").click(function(event) {
+        paused = true;
+        updateStep(function(s) { return (numSteps - 1); })
+    })
+});
diff --git a/templates/rules.cassius b/templates/rules.cassius
new file mode 100644
--- /dev/null
+++ b/templates/rules.cassius
@@ -0,0 +1,19 @@
+div.rulesContent
+  width: 400px
+  margin: 0px auto
+
+div.rulesBox h3
+  text-align: center
+
+div.rulesBox
+  box-shadow: 0 0 5px #36BBCE
+  background-color: rgba(1, 89, 101, 0.25)
+  width: 400px
+  text-align: center
+
+div.rulesFields
+  display: inline-block
+  text-align: left
+
+label[for=inputDevMode]
+  color: #FE3F44
diff --git a/templates/rules.hamlet b/templates/rules.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/rules.hamlet
@@ -0,0 +1,31 @@
+<div .rulesContent>
+  <div .rulesBox>
+    <h3>_{MsgRules}
+    <form name="rules" method="post" action="@{RulesR}">
+      <div .rulesFields>
+        <div .ruleEntry>
+          <input #inputAgain type="checkbox" name="againWhenHit" value="yes" :(againWhenHit defaultOptions):checked>
+          <label for="inputAgain">_{MsgInputAgainWhenHit}
+        <div .ruleEntry>
+          <input #inputMove type="checkbox" name="move" value="yes" :(move defaultOptions):checked>
+          <label for="inputMove">_{MsgInputMove}
+        <div .ruleEntry>
+          <input #inputNoviceMode type="checkbox" name="noviceMode" value="yes" :(noviceMode defaultOptions):checked>
+          <label for="inputNoviceMode">_{MsgInputNoviceMode}
+        <div .ruleEntry>
+          <label for="inputDifficulty">_{MsgInputDifficulty}
+          <select #inputDifficulty name="difficulty">
+            $forall (i, (msg, _)) <- indexedDifficultyList
+              <option value="#{show i}">
+                _{msg}
+        $if development
+          <hr>
+          <div .ruleEntry>
+            <input #inputDevMode type="checkbox" name="devMode" value="yes" :(devMode defaultOptions):checked>
+            <label for="inputDevMode">_{MsgInputDevMode}
+
+      <p .linkBlock>
+        <input .linkButton .yellowButton type="submit" value="_{MsgStartPlacing}">
+
+<script>
+  this.rules.difficulty.selectedIndex = #{indexOfDifficulty (difficulty defaultOptions)};
diff --git a/templates/savegame.cassius b/templates/savegame.cassius
new file mode 100644
--- /dev/null
+++ b/templates/savegame.cassius
@@ -0,0 +1,9 @@
+body
+  font-family: sans-serif
+  overflow-x: hidden
+  background: #020402 url(@{StaticR img_dreadnought_png}) no-repeat
+  background-position: 50% 0px
+  color: #5FC0CE
+
+a
+  color: white
diff --git a/templates/savegame.hamlet b/templates/savegame.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/savegame.hamlet
@@ -0,0 +1,9 @@
+<h1>
+  _{MsgSaveGame}
+
+<p>
+  _{MsgSaveGameExplanation}
+  <br>
+  <br>
+  <a href=@{PlayR True gameE}>
+    _{MsgCurrentGame}
diff --git a/templates/shipsOpponent.cassius b/templates/shipsOpponent.cassius
new file mode 100644
--- /dev/null
+++ b/templates/shipsOpponent.cassius
@@ -0,0 +1,19 @@
+div.shipsOpponent thead tr td
+  border-bottom: 1px solid #D2F870;
+  padding: 2px;
+
+div.shipsOpponent tfoot tr td
+  border-top: 1px solid #D2F870;
+  padding: 2px;
+
+div.shipsOpponent 
+  color: #EEE
+  thead tr td:first-child, tbody tr td:first-child, tfoot tr td:first-child
+    border-right: 1px solid #D2F870;
+    padding: 2px;
+
+#shipsOpponent
+  border-collapse: collapse;
+  width: 100%;
+  text-align: center;
+  color: #EEE
diff --git a/templates/shipsOpponent.hamlet b/templates/shipsOpponent.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/shipsOpponent.hamlet
@@ -0,0 +1,16 @@
+<div .shipsOpponent>
+  <h4>_{MsgOpponentRemainingShips}
+  <table id="shipsOpponent">
+    <thead>
+      <tr>
+        <td>_{MsgShipLength}
+        <td>#_{MsgShipsUnsunk}
+    <tbody>
+      $forall size <- nub fleetShips
+        <tr>
+          <td>#{show size}
+          <td>#{show $ numberShipsOfSize sizes size}
+    <tfoot>
+      <tr>
+          <td>_{MsgShipsTotal}
+          <td>#{length sizes}
